diff --git a/logback-access/src/main/java/ch/qos/logback/access/AccessConstants.java b/logback-access/src/main/java/ch/qos/logback/access/AccessConstants.java index 9b83733980c0dcee6b3ec5891edb203ddd1f38ec..722744af7e58737016353c03fa9448a865d95b4d 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/AccessConstants.java +++ b/logback-access/src/main/java/ch/qos/logback/access/AccessConstants.java @@ -14,19 +14,19 @@ package ch.qos.logback.access; public class AccessConstants { - - public static final String LOGBACK_STATUS_MANAGER_KEY = "LOGBACK_STATUS_MANAGER"; - public static final String LB_INPUT_BUFFER = "LB_INPUT_BUFFER"; - public static final String LB_OUTPUT_BUFFER = "LB_OUTPUT_BUFFER"; - - public static final String X_WWW_FORM_URLECODED = "application/x-www-form-urlencoded"; - - public static final String IMAGE_CONTENT_TYPE = "image/"; - public static final String IMAGE_JPEG = "image/jpeg"; - public static final String IMAGE_GIF = "image/gif"; - public static final String IMAGE_PNG = "image/png"; - public static final String TEE_FILTER_INCLUDES_PARAM = "includes"; - public static final String TEE_FILTER_EXCLUDES_PARAM = "excludes"; + public static final String LOGBACK_STATUS_MANAGER_KEY = "LOGBACK_STATUS_MANAGER"; + public static final String LB_INPUT_BUFFER = "LB_INPUT_BUFFER"; + public static final String LB_OUTPUT_BUFFER = "LB_OUTPUT_BUFFER"; + + public static final String X_WWW_FORM_URLECODED = "application/x-www-form-urlencoded"; + + public static final String IMAGE_CONTENT_TYPE = "image/"; + public static final String IMAGE_JPEG = "image/jpeg"; + public static final String IMAGE_GIF = "image/gif"; + public static final String IMAGE_PNG = "image/png"; + + public static final String TEE_FILTER_INCLUDES_PARAM = "includes"; + public static final String TEE_FILTER_EXCLUDES_PARAM = "excludes"; } diff --git a/logback-access/src/main/java/ch/qos/logback/access/PatternLayout.java b/logback-access/src/main/java/ch/qos/logback/access/PatternLayout.java index 68ebba932b844ae60e202acc7e1b23a2ba992ddb..2eb8bb5d9417f3bb79e689f36bc68ae575945a7e 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/PatternLayout.java +++ b/logback-access/src/main/java/ch/qos/logback/access/PatternLayout.java @@ -64,154 +64,138 @@ import java.util.Map; */ public class PatternLayout extends PatternLayoutBase { - public static final Map defaultConverterMap = new HashMap(); - public static final String HEADER_PREFIX = "#logback.access pattern: "; + public static final Map defaultConverterMap = new HashMap(); + public static final String HEADER_PREFIX = "#logback.access pattern: "; - public static final String CLF_PATTERN = "%h %l %u [%t] \"%r\" %s %b"; - public static final String CLF_PATTERN_NAME = "common"; - public static final String CLF_PATTERN_NAME_2 = "clf"; - public static final String COMBINED_PATTERN = "%h %l %u [%t] \"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\""; - public static final String COMBINED_PATTERN_NAME = "combined"; + public static final String CLF_PATTERN = "%h %l %u [%t] \"%r\" %s %b"; + public static final String CLF_PATTERN_NAME = "common"; + public static final String CLF_PATTERN_NAME_2 = "clf"; + public static final String COMBINED_PATTERN = "%h %l %u [%t] \"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\""; + public static final String COMBINED_PATTERN_NAME = "combined"; - static { - defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); + static { + defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); - defaultConverterMap.put("a", RemoteIPAddressConverter.class.getName()); - defaultConverterMap.put("remoteIP", RemoteIPAddressConverter.class - .getName()); + defaultConverterMap.put("a", RemoteIPAddressConverter.class.getName()); + defaultConverterMap.put("remoteIP", RemoteIPAddressConverter.class.getName()); - defaultConverterMap.put("A", LocalIPAddressConverter.class.getName()); - defaultConverterMap.put("localIP", LocalIPAddressConverter.class.getName()); + defaultConverterMap.put("A", LocalIPAddressConverter.class.getName()); + defaultConverterMap.put("localIP", LocalIPAddressConverter.class.getName()); - defaultConverterMap.put("b", ContentLengthConverter.class.getName()); - defaultConverterMap.put("B", ContentLengthConverter.class.getName()); - defaultConverterMap - .put("bytesSent", ContentLengthConverter.class.getName()); + defaultConverterMap.put("b", ContentLengthConverter.class.getName()); + defaultConverterMap.put("B", ContentLengthConverter.class.getName()); + defaultConverterMap.put("bytesSent", ContentLengthConverter.class.getName()); - defaultConverterMap.put("h", RemoteHostConverter.class.getName()); - defaultConverterMap.put("clientHost", RemoteHostConverter.class.getName()); + defaultConverterMap.put("h", RemoteHostConverter.class.getName()); + defaultConverterMap.put("clientHost", RemoteHostConverter.class.getName()); - defaultConverterMap.put("H", RequestProtocolConverter.class.getName()); - defaultConverterMap.put("protocol", RequestProtocolConverter.class - .getName()); + defaultConverterMap.put("H", RequestProtocolConverter.class.getName()); + defaultConverterMap.put("protocol", RequestProtocolConverter.class.getName()); - defaultConverterMap.put("i", RequestHeaderConverter.class.getName()); - defaultConverterMap.put("header", RequestHeaderConverter.class.getName()); + defaultConverterMap.put("i", RequestHeaderConverter.class.getName()); + defaultConverterMap.put("header", RequestHeaderConverter.class.getName()); - defaultConverterMap.put("l", NAConverter.class.getName()); + defaultConverterMap.put("l", NAConverter.class.getName()); - defaultConverterMap.put("m", RequestMethodConverter.class.getName()); - defaultConverterMap.put("requestMethod", RequestMethodConverter.class - .getName()); + defaultConverterMap.put("m", RequestMethodConverter.class.getName()); + defaultConverterMap.put("requestMethod", RequestMethodConverter.class.getName()); - defaultConverterMap.put("r", RequestURLConverter.class.getName()); - defaultConverterMap.put("requestURL", RequestURLConverter.class.getName()); + defaultConverterMap.put("r", RequestURLConverter.class.getName()); + defaultConverterMap.put("requestURL", RequestURLConverter.class.getName()); - defaultConverterMap.put("s", StatusCodeConverter.class.getName()); - defaultConverterMap.put("statusCode", StatusCodeConverter.class.getName()); + defaultConverterMap.put("s", StatusCodeConverter.class.getName()); + defaultConverterMap.put("statusCode", StatusCodeConverter.class.getName()); - defaultConverterMap.put("t", DateConverter.class.getName()); - defaultConverterMap.put("date", DateConverter.class.getName()); + defaultConverterMap.put("t", DateConverter.class.getName()); + defaultConverterMap.put("date", DateConverter.class.getName()); - defaultConverterMap.put("u", RemoteUserConverter.class.getName()); - defaultConverterMap.put("user", RemoteUserConverter.class.getName()); + defaultConverterMap.put("u", RemoteUserConverter.class.getName()); + defaultConverterMap.put("user", RemoteUserConverter.class.getName()); - defaultConverterMap.put("U", RequestURIConverter.class.getName()); - defaultConverterMap.put("requestURI", RequestURIConverter.class.getName()); + defaultConverterMap.put("U", RequestURIConverter.class.getName()); + defaultConverterMap.put("requestURI", RequestURIConverter.class.getName()); - defaultConverterMap.put("v", ServerNameConverter.class.getName()); - defaultConverterMap.put("server", ServerNameConverter.class.getName()); + defaultConverterMap.put("v", ServerNameConverter.class.getName()); + defaultConverterMap.put("server", ServerNameConverter.class.getName()); - defaultConverterMap.put("localPort", LocalPortConverter.class.getName()); + defaultConverterMap.put("localPort", LocalPortConverter.class.getName()); - defaultConverterMap.put("requestAttribute", RequestAttributeConverter.class - .getName()); - defaultConverterMap.put("reqAttribute", RequestAttributeConverter.class - .getName()); + defaultConverterMap.put("requestAttribute", RequestAttributeConverter.class.getName()); + defaultConverterMap.put("reqAttribute", RequestAttributeConverter.class.getName()); - defaultConverterMap - .put("reqCookie", RequestCookieConverter.class.getName()); - defaultConverterMap - .put("requestCookie", RequestCookieConverter.class.getName()); + defaultConverterMap.put("reqCookie", RequestCookieConverter.class.getName()); + defaultConverterMap.put("requestCookie", RequestCookieConverter.class.getName()); + defaultConverterMap.put("responseHeader", ResponseHeaderConverter.class.getName()); - defaultConverterMap.put("responseHeader", ResponseHeaderConverter.class - .getName()); + defaultConverterMap.put("requestParameter", RequestParameterConverter.class.getName()); + defaultConverterMap.put("reqParameter", RequestParameterConverter.class.getName()); + defaultConverterMap.put("requestContent", RequestContentConverter.class.getName()); - defaultConverterMap.put("requestParameter", RequestParameterConverter.class - .getName()); - defaultConverterMap.put("reqParameter", RequestParameterConverter.class - .getName()); + defaultConverterMap.put("responseContent", ResponseContentConverter.class.getName()); - defaultConverterMap.put("requestContent", RequestContentConverter.class.getName()); + defaultConverterMap.put("fullRequest", FullRequestConverter.class.getName()); + defaultConverterMap.put("fullResponse", FullResponseConverter.class.getName()); - defaultConverterMap.put("responseContent", ResponseContentConverter.class.getName()); + defaultConverterMap.put("elapsedTime", ElapsedTimeConverter.class.getName()); + defaultConverterMap.put("D", ElapsedTimeConverter.class.getName()); - defaultConverterMap.put("fullRequest", FullRequestConverter.class.getName()); - defaultConverterMap.put("fullResponse", FullResponseConverter.class.getName()); + defaultConverterMap.put("n", LineSeparatorConverter.class.getName()); - defaultConverterMap.put("elapsedTime", ElapsedTimeConverter.class.getName()); - defaultConverterMap.put("D", ElapsedTimeConverter.class.getName()); - - defaultConverterMap.put("n", LineSeparatorConverter.class.getName()); - - defaultConverterMap.put("black", BlackCompositeConverter.class.getName()); - defaultConverterMap.put("red", RedCompositeConverter.class.getName()); - defaultConverterMap.put("green", GreenCompositeConverter.class.getName()); - defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName()); - defaultConverterMap.put("blue", BlueCompositeConverter.class.getName()); - defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName()); - defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName()); - defaultConverterMap.put("white", WhiteCompositeConverter.class.getName()); - defaultConverterMap.put("gray", GrayCompositeConverter.class.getName()); - defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName()); - defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName()); - defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName()); - defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName()); - defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName()); - defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName()); - defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName()); - } - - - public PatternLayout() { - // set a default value for pattern - setPattern(CLF_PATTERN); - // by default postCompileProcessor the is an EnsureLineSeparation instance - this.postCompileProcessor = new EnsureLineSeparation(); - } + defaultConverterMap.put("black", BlackCompositeConverter.class.getName()); + defaultConverterMap.put("red", RedCompositeConverter.class.getName()); + defaultConverterMap.put("green", GreenCompositeConverter.class.getName()); + defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName()); + defaultConverterMap.put("blue", BlueCompositeConverter.class.getName()); + defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName()); + defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName()); + defaultConverterMap.put("white", WhiteCompositeConverter.class.getName()); + defaultConverterMap.put("gray", GrayCompositeConverter.class.getName()); + defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName()); + defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName()); + defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName()); + defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName()); + defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName()); + defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName()); + defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName()); + } - /** - * Returns the default converter map for this instance. - */ - @Override - public Map getDefaultConverterMap() { - return defaultConverterMap; - } + public PatternLayout() { + // set a default value for pattern + setPattern(CLF_PATTERN); + // by default postCompileProcessor the is an EnsureLineSeparation instance + this.postCompileProcessor = new EnsureLineSeparation(); + } - @Override - public String doLayout(IAccessEvent event) { - if (!isStarted()) { - return null; + /** + * Returns the default converter map for this instance. + */ + @Override + public Map getDefaultConverterMap() { + return defaultConverterMap; } - return writeLoopOnConverters(event); - } - - @Override - public void start() { - if (getPattern().equalsIgnoreCase(CLF_PATTERN_NAME) - || getPattern().equalsIgnoreCase(CLF_PATTERN_NAME_2)) { - setPattern(CLF_PATTERN); - } else if (getPattern().equalsIgnoreCase(COMBINED_PATTERN_NAME)) { - setPattern(COMBINED_PATTERN); + + @Override + public String doLayout(IAccessEvent event) { + if (!isStarted()) { + return null; + } + return writeLoopOnConverters(event); } - super.start(); - } + @Override + public void start() { + if (getPattern().equalsIgnoreCase(CLF_PATTERN_NAME) || getPattern().equalsIgnoreCase(CLF_PATTERN_NAME_2)) { + setPattern(CLF_PATTERN); + } else if (getPattern().equalsIgnoreCase(COMBINED_PATTERN_NAME)) { + setPattern(COMBINED_PATTERN); + } + super.start(); + } - @Override - protected String getPresentationHeaderPrefix() { - return HEADER_PREFIX; - } + @Override + protected String getPresentationHeaderPrefix() { + return HEADER_PREFIX; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/PatternLayoutEncoder.java b/logback-access/src/main/java/ch/qos/logback/access/PatternLayoutEncoder.java index 5f64ab3bcb4e6be66ea37e0fb8f0cff7a3de1173..92c4a019fcd3b09e842d30cb78457144ee2996e3 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/PatternLayoutEncoder.java +++ b/logback-access/src/main/java/ch/qos/logback/access/PatternLayoutEncoder.java @@ -16,17 +16,16 @@ package ch.qos.logback.access; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.pattern.PatternLayoutEncoderBase; - public class PatternLayoutEncoder extends PatternLayoutEncoderBase { - @Override - public void start() { - PatternLayout patternLayout = new PatternLayout(); - patternLayout.setContext(context); - patternLayout.setPattern(getPattern()); - patternLayout.start(); - this.layout = patternLayout; - super.start(); - } - + @Override + public void start() { + PatternLayout patternLayout = new PatternLayout(); + patternLayout.setContext(context); + patternLayout.setPattern(getPattern()); + patternLayout.start(); + this.layout = patternLayout; + super.start(); + } + } diff --git a/logback-access/src/main/java/ch/qos/logback/access/ViewStatusMessagesServlet.java b/logback-access/src/main/java/ch/qos/logback/access/ViewStatusMessagesServlet.java index 331e883f1e6fcd86c1f77f67da280fce71ede3a7..ce4d448a2f5245571e9754c90a85d06a8bb24dcb 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/ViewStatusMessagesServlet.java +++ b/logback-access/src/main/java/ch/qos/logback/access/ViewStatusMessagesServlet.java @@ -22,30 +22,28 @@ import ch.qos.logback.core.status.ViewStatusMessagesServletBase; public class ViewStatusMessagesServlet extends ViewStatusMessagesServletBase { - private static final long serialVersionUID = 443878494348593337L; - - @Override - protected StatusManager getStatusManager(HttpServletRequest req, - HttpServletResponse resp) { - - ServletContext sc = getServletContext(); - return (StatusManager) sc - .getAttribute(AccessConstants.LOGBACK_STATUS_MANAGER_KEY); - -// if (result != null) { -// System.out.println("from ServletContext"); -// return result; -// } else { -// HttpSession httpSession = req.getSession(true); -// -// System.out.println("from httpSession"); -// return (StatusManager) httpSession -// .getAttribute(AccessConstants.LOGBACK_STATUS_MANAGER_KEY); -// } - } - - @Override - protected String getPageTitle(HttpServletRequest req, HttpServletResponse resp) { - return "

Status messages for logback-access

\r\n"; - } + private static final long serialVersionUID = 443878494348593337L; + + @Override + protected StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp) { + + ServletContext sc = getServletContext(); + return (StatusManager) sc.getAttribute(AccessConstants.LOGBACK_STATUS_MANAGER_KEY); + + // if (result != null) { + // System.out.println("from ServletContext"); + // return result; + // } else { + // HttpSession httpSession = req.getSession(true); + // + // System.out.println("from httpSession"); + // return (StatusManager) httpSession + // .getAttribute(AccessConstants.LOGBACK_STATUS_MANAGER_KEY); + // } + } + + @Override + protected String getPageTitle(HttpServletRequest req, HttpServletResponse resp) { + return "

Status messages for logback-access

\r\n"; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/boolex/JaninoEventEvaluator.java b/logback-access/src/main/java/ch/qos/logback/access/boolex/JaninoEventEvaluator.java index eca044c228d6d44021b9600370ecce6ec3850a54..8c5225316da2ea73f4b529bff90779229c54a7ca 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/boolex/JaninoEventEvaluator.java +++ b/logback-access/src/main/java/ch/qos/logback/access/boolex/JaninoEventEvaluator.java @@ -23,63 +23,62 @@ import ch.qos.logback.core.boolex.Matcher; public class JaninoEventEvaluator extends JaninoEventEvaluatorBase { - public final static List DEFAULT_PARAM_NAME_LIST = new ArrayList(); - public final static List DEFAULT_PARAM_TYPE_LIST = new ArrayList(); - - static { - DEFAULT_PARAM_NAME_LIST.add("event"); - DEFAULT_PARAM_TYPE_LIST.add(IAccessEvent.class); - } - - - @Override - protected String getDecoratedExpression() { - String expression = getExpression(); - if (!expression.contains("return")) { - expression = "return " + expression + ";"; - addInfo("Adding [return] prefix and a semicolon suffix. Expression becomes [" + expression + "]"); - addInfo("See also " + CoreConstants.CODES_URL + "#block"); - } - return expression; - } + public final static List DEFAULT_PARAM_NAME_LIST = new ArrayList(); + public final static List DEFAULT_PARAM_TYPE_LIST = new ArrayList(); - @Override - protected String[] getParameterNames() { - List fullNameList = new ArrayList(); - fullNameList.addAll(DEFAULT_PARAM_NAME_LIST); + static { + DEFAULT_PARAM_NAME_LIST.add("event"); + DEFAULT_PARAM_TYPE_LIST.add(IAccessEvent.class); + } - for (int i = 0; i < matcherList.size(); i++) { - Matcher m = (Matcher) matcherList.get(i); - fullNameList.add(m.getName()); + @Override + protected String getDecoratedExpression() { + String expression = getExpression(); + if (!expression.contains("return")) { + expression = "return " + expression + ";"; + addInfo("Adding [return] prefix and a semicolon suffix. Expression becomes [" + expression + "]"); + addInfo("See also " + CoreConstants.CODES_URL + "#block"); + } + return expression; } - return (String[]) fullNameList.toArray(CoreConstants.EMPTY_STRING_ARRAY); - } + @Override + protected String[] getParameterNames() { + List fullNameList = new ArrayList(); + fullNameList.addAll(DEFAULT_PARAM_NAME_LIST); - @Override - protected Class[] getParameterTypes() { - List fullTypeList = new ArrayList(); - fullTypeList.addAll(DEFAULT_PARAM_TYPE_LIST); - for (int i = 0; i < matcherList.size(); i++) { - fullTypeList.add(Matcher.class); + for (int i = 0; i < matcherList.size(); i++) { + Matcher m = (Matcher) matcherList.get(i); + fullNameList.add(m.getName()); + } + + return (String[]) fullNameList.toArray(CoreConstants.EMPTY_STRING_ARRAY); } - return (Class[]) fullTypeList.toArray(CoreConstants.EMPTY_CLASS_ARRAY); - } - @Override - protected Object[] getParameterValues(IAccessEvent accessEvent) { - final int matcherListSize = matcherList.size(); + @Override + protected Class[] getParameterTypes() { + List fullTypeList = new ArrayList(); + fullTypeList.addAll(DEFAULT_PARAM_TYPE_LIST); + for (int i = 0; i < matcherList.size(); i++) { + fullTypeList.add(Matcher.class); + } + return (Class[]) fullTypeList.toArray(CoreConstants.EMPTY_CLASS_ARRAY); + } - int i = 0; - Object[] values = new Object[DEFAULT_PARAM_NAME_LIST.size() + matcherListSize]; + @Override + protected Object[] getParameterValues(IAccessEvent accessEvent) { + final int matcherListSize = matcherList.size(); - values[i++] = accessEvent; + int i = 0; + Object[] values = new Object[DEFAULT_PARAM_NAME_LIST.size() + matcherListSize]; - for (int j = 0; j < matcherListSize; j++) { - values[i++] = matcherList.get(j); - } + values[i++] = accessEvent; + + for (int j = 0; j < matcherListSize; j++) { + values[i++] = matcherList.get(j); + } - return values; - } + return values; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/db/DBAppender.java b/logback-access/src/main/java/ch/qos/logback/access/db/DBAppender.java index 7fc9df5176578a4d27556b364c6077f44c2ec231..df9242391b7df4a014f862cd546008735b9908c2 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/db/DBAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/db/DBAppender.java @@ -34,114 +34,107 @@ import ch.qos.logback.core.db.DBAppenderBase; * @author Sébastien Pennec */ public class DBAppender extends DBAppenderBase { - protected static final String insertSQL; - protected final String insertHeaderSQL = "INSERT INTO access_event_header (event_id, header_key, header_value) VALUES (?, ?, ?)"; - protected static final Method GET_GENERATED_KEYS_METHOD; - - private boolean insertHeaders = false; - - static { - StringBuilder sql = new StringBuilder(); - sql.append("INSERT INTO access_event ("); - sql.append("timestmp, "); - sql.append("requestURI, "); - sql.append("requestURL, "); - sql.append("remoteHost, "); - sql.append("remoteUser, "); - sql.append("remoteAddr, "); - sql.append("protocol, "); - sql.append("method, "); - sql.append("serverName, "); - sql.append("postContent) "); - sql.append(" VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?)"); - insertSQL = sql.toString(); - - Method getGeneratedKeysMethod; - try { - getGeneratedKeysMethod = PreparedStatement.class.getMethod( - "getGeneratedKeys", (Class[]) null); - } catch (Exception ex) { - getGeneratedKeysMethod = null; + protected static final String insertSQL; + protected final String insertHeaderSQL = "INSERT INTO access_event_header (event_id, header_key, header_value) VALUES (?, ?, ?)"; + protected static final Method GET_GENERATED_KEYS_METHOD; + + private boolean insertHeaders = false; + + static { + StringBuilder sql = new StringBuilder(); + sql.append("INSERT INTO access_event ("); + sql.append("timestmp, "); + sql.append("requestURI, "); + sql.append("requestURL, "); + sql.append("remoteHost, "); + sql.append("remoteUser, "); + sql.append("remoteAddr, "); + sql.append("protocol, "); + sql.append("method, "); + sql.append("serverName, "); + sql.append("postContent) "); + sql.append(" VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?)"); + insertSQL = sql.toString(); + + Method getGeneratedKeysMethod; + try { + getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", (Class[]) null); + } catch (Exception ex) { + getGeneratedKeysMethod = null; + } + GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; } - GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; - } - - @Override - protected void subAppend(IAccessEvent event, Connection connection, - PreparedStatement insertStatement) throws Throwable { - - addAccessEvent(insertStatement, event); - - int updateCount = insertStatement.executeUpdate(); - if (updateCount != 1) { - addWarn("Failed to insert access event"); + + @Override + protected void subAppend(IAccessEvent event, Connection connection, PreparedStatement insertStatement) throws Throwable { + + addAccessEvent(insertStatement, event); + + int updateCount = insertStatement.executeUpdate(); + if (updateCount != 1) { + addWarn("Failed to insert access event"); + } + } + + @Override + protected void secondarySubAppend(IAccessEvent event, Connection connection, long eventId) throws Throwable { + if (insertHeaders) { + addRequestHeaders(event, connection, eventId); + } } - } - @Override - protected void secondarySubAppend(IAccessEvent event, Connection connection, - long eventId) throws Throwable { - if (insertHeaders) { - addRequestHeaders(event, connection, eventId); + void addAccessEvent(PreparedStatement stmt, IAccessEvent event) throws SQLException { + stmt.setLong(1, event.getTimeStamp()); + stmt.setString(2, event.getRequestURI()); + stmt.setString(3, event.getRequestURL()); + stmt.setString(4, event.getRemoteHost()); + stmt.setString(5, event.getRemoteUser()); + stmt.setString(6, event.getRemoteAddr()); + stmt.setString(7, event.getProtocol()); + stmt.setString(8, event.getMethod()); + stmt.setString(9, event.getServerName()); + stmt.setString(10, event.getRequestContent()); } - } - - void addAccessEvent(PreparedStatement stmt, IAccessEvent event) - throws SQLException { - stmt.setLong(1, event.getTimeStamp()); - stmt.setString(2, event.getRequestURI()); - stmt.setString(3, event.getRequestURL()); - stmt.setString(4, event.getRemoteHost()); - stmt.setString(5, event.getRemoteUser()); - stmt.setString(6, event.getRemoteAddr()); - stmt.setString(7, event.getProtocol()); - stmt.setString(8, event.getMethod()); - stmt.setString(9, event.getServerName()); - stmt.setString(10, event.getRequestContent()); - } - - void addRequestHeaders(IAccessEvent event, - Connection connection, long eventId) throws SQLException { - Enumeration names = event.getRequestHeaderNames(); - if (names.hasMoreElements()) { - PreparedStatement insertHeaderStatement = connection - .prepareStatement(insertHeaderSQL); - - - while (names.hasMoreElements()) { - String key = (String) names.nextElement(); - String value = (String) event.getRequestHeader(key); - - insertHeaderStatement.setLong(1, eventId); - insertHeaderStatement.setString(2, key); - insertHeaderStatement.setString(3, value); - - if (cnxSupportsBatchUpdates) { - insertHeaderStatement.addBatch(); - } else { - insertHeaderStatement.execute(); + + void addRequestHeaders(IAccessEvent event, Connection connection, long eventId) throws SQLException { + Enumeration names = event.getRequestHeaderNames(); + if (names.hasMoreElements()) { + PreparedStatement insertHeaderStatement = connection.prepareStatement(insertHeaderSQL); + + while (names.hasMoreElements()) { + String key = (String) names.nextElement(); + String value = (String) event.getRequestHeader(key); + + insertHeaderStatement.setLong(1, eventId); + insertHeaderStatement.setString(2, key); + insertHeaderStatement.setString(3, value); + + if (cnxSupportsBatchUpdates) { + insertHeaderStatement.addBatch(); + } else { + insertHeaderStatement.execute(); + } + } + + if (cnxSupportsBatchUpdates) { + insertHeaderStatement.executeBatch(); + } + + insertHeaderStatement.close(); } - } + } - if (cnxSupportsBatchUpdates) { - insertHeaderStatement.executeBatch(); - } + @Override + protected Method getGeneratedKeysMethod() { + return GET_GENERATED_KEYS_METHOD; + } + + @Override + protected String getInsertSQL() { + return insertSQL; + } - insertHeaderStatement.close(); + public void setInsertHeaders(boolean insertHeaders) { + this.insertHeaders = insertHeaders; } - } - - @Override - protected Method getGeneratedKeysMethod() { - return GET_GENERATED_KEYS_METHOD; - } - - @Override - protected String getInsertSQL() { - return insertSQL; - } - - public void setInsertHeaders(boolean insertHeaders) { - this.insertHeaders = insertHeaders; - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/CountingFilter.java b/logback-access/src/main/java/ch/qos/logback/access/filter/CountingFilter.java index 8049c4c7b7c4a969b37d76e19a0c27cf2cb4cd9d..b2c64048ac6f81cc40d4052cfcd209cd712c8e65 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/CountingFilter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/CountingFilter.java @@ -11,7 +11,7 @@ * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ - package ch.qos.logback.access.filter; +package ch.qos.logback.access.filter; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.FilterReply; @@ -23,61 +23,60 @@ import java.lang.management.ManagementFactory; public class CountingFilter extends Filter { - long total = 0; - final StatisticalViewImpl accessStatsImpl; - - String domain = "ch.qos.logback.access"; - - public CountingFilter() { - accessStatsImpl = new StatisticalViewImpl(this); - } - - @Override - public FilterReply decide(Object event) { - total++; - accessStatsImpl.update(); - return FilterReply.NEUTRAL; - } + long total = 0; + final StatisticalViewImpl accessStatsImpl; - public long getTotal() { - return total; - } - - - @Override - public void start() { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - try { - ObjectName on = new ObjectName(domain+":Name="+getName()); - StandardMBean mbean = new StandardMBean(accessStatsImpl, StatisticalView.class); - if (mbs.isRegistered(on)) { - mbs.unregisterMBean(on); - } - mbs.registerMBean(mbean, on); - super.start(); - } catch (Exception e) { - addError("Failed to create mbean", e); + String domain = "ch.qos.logback.access"; + + public CountingFilter() { + accessStatsImpl = new StatisticalViewImpl(this); + } + + @Override + public FilterReply decide(Object event) { + total++; + accessStatsImpl.update(); + return FilterReply.NEUTRAL; } - } - - @Override - public void stop() { - super.stop(); - try { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName on = new ObjectName("totp:Filter=1"); - mbs.unregisterMBean(on); - } catch(Exception e) { - addError("Failed to unregister mbean", e); + + public long getTotal() { + return total; + } + + @Override + public void start() { + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + try { + ObjectName on = new ObjectName(domain + ":Name=" + getName()); + StandardMBean mbean = new StandardMBean(accessStatsImpl, StatisticalView.class); + if (mbs.isRegistered(on)) { + mbs.unregisterMBean(on); + } + mbs.registerMBean(mbean, on); + super.start(); + } catch (Exception e) { + addError("Failed to create mbean", e); + } } - } - public String getDomain() { - return domain; - } + @Override + public void stop() { + super.stop(); + try { + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + ObjectName on = new ObjectName("totp:Filter=1"); + mbs.unregisterMBean(on); + } catch (Exception e) { + addError("Failed to unregister mbean", e); + } + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } - public void setDomain(String domain) { - this.domain = domain; - } - } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/PeriodicStats.java b/logback-access/src/main/java/ch/qos/logback/access/filter/PeriodicStats.java index 607b202988b626568cbd3e9f567973dab0befbb1..f1019564b1cfdeff838e40cfa01d36e1be930626 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/PeriodicStats.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/PeriodicStats.java @@ -13,53 +13,52 @@ */ package ch.qos.logback.access.filter; - abstract public class PeriodicStats { - - private long nextPeriodBegins = 0; - private long lastTotal = 0; - private long lastCount = 0; - private double average; - private int n; - - PeriodicStats() { - this(System.currentTimeMillis()); - } - - PeriodicStats(long now) { - nextPeriodBegins = computeStartOfNextPeriod(now); - } - - void update(long now, long total) { - if (now > nextPeriodBegins) { - lastCount = total - lastTotal; - lastTotal = total; - average = (average * n + lastCount) / (++n); - nextPeriodBegins = computeStartOfNextPeriod(now); + private long nextPeriodBegins = 0; + private long lastTotal = 0; + private long lastCount = 0; + + private double average; + private int n; + + PeriodicStats() { + this(System.currentTimeMillis()); + } + + PeriodicStats(long now) { + nextPeriodBegins = computeStartOfNextPeriod(now); + } + + void update(long now, long total) { + if (now > nextPeriodBegins) { + lastCount = total - lastTotal; + lastTotal = total; + average = (average * n + lastCount) / (++n); + nextPeriodBegins = computeStartOfNextPeriod(now); + } } - } - public double getAverage() { - return average; - } + public double getAverage() { + return average; + } + + public long getLastCount() { + return lastCount; + } + + void reset(long now) { + nextPeriodBegins = computeStartOfNextPeriod(now); + lastTotal = 0; + lastCount = 0; + average = 0.0; + n = 0; + } + + void reset() { + reset(System.currentTimeMillis()); + } - public long getLastCount() { - return lastCount; - } - - void reset(long now) { - nextPeriodBegins = computeStartOfNextPeriod(now); - lastTotal = 0; - lastCount = 0; - average = 0.0; - n = 0; - } - - void reset() { - reset(System.currentTimeMillis()); - } - - abstract long computeStartOfNextPeriod(long now); + abstract long computeStartOfNextPeriod(long now); } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalView.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalView.java index 1f029986188987cac105229e04bc8b28b86a283d..9df3028cc85d7a881a9a9facf2b2643feddaa25c 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalView.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalView.java @@ -15,25 +15,26 @@ package ch.qos.logback.access.filter; public interface StatisticalView { - - long getTotal(); - - long getLastMinuteCount(); - double getMinuteAverage(); - - - long getLastHoursCount(); - double getHourlyAverage(); - - - long getLastDaysCount(); - double getDailyAverage(); - - - long getLastWeeksCount(); - double getWeeklyAverage(); - - long getLastMonthsCount(); - double getMonthlyAverage(); - + long getTotal(); + + long getLastMinuteCount(); + + double getMinuteAverage(); + + long getLastHoursCount(); + + double getHourlyAverage(); + + long getLastDaysCount(); + + double getDailyAverage(); + + long getLastWeeksCount(); + + double getWeeklyAverage(); + + long getLastMonthsCount(); + + double getMonthlyAverage(); + } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalViewImpl.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalViewImpl.java index 26e22043a72bfd495add481af73fe5a30cd48ad0..0b1fb25fae824c7c20e8241b09d9466cad2464c9 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalViewImpl.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatisticalViewImpl.java @@ -17,114 +17,114 @@ import ch.qos.logback.core.spi.LifeCycle; public class StatisticalViewImpl implements StatisticalView, LifeCycle { - final CountingFilter countingFilter; - boolean started; - - StatsByMinute statsByMinute = new StatsByMinute(); - StatsByHour statsByHour = new StatsByHour(); - StatsByDay statsByDay = new StatsByDay(); - StatsByWeek statsByWeek = new StatsByWeek(); - StatsByMonth statsByMonth = new StatsByMonth(); - - StatisticalViewImpl(CountingFilter countingFilter) { - this.countingFilter = countingFilter; - } - - @Override - public double getDailyAverage() { - return statsByDay.getAverage(); - } - - @Override - public long getLastDaysCount() { - return statsByDay.getLastCount(); - } - - @Override - public double getMonthlyAverage() { - return statsByMonth.getAverage(); - } - - @Override - public long getLastMonthsCount() { - return statsByMonth.getLastCount(); - } - - @Override - public long getTotal() { - return countingFilter.getTotal(); - } - - @Override - public double getWeeklyAverage() { - return statsByWeek.getAverage(); - } - - @Override - public long getLastWeeksCount() { - return statsByWeek.getLastCount(); - } - - void update(long now) { - long total = getTotal(); - statsByMinute.update(now, total); - statsByHour.update(now, total); - statsByDay.update(now, total); - statsByWeek.update(now, total); - statsByMonth.update(now, total); - - } - - void update() { - long now = System.currentTimeMillis(); - update(now); - } - - @Override - public void start() { - System.out.println("StatisticalViewImpl start called"); - started = true; - long now = System.currentTimeMillis(); - statsByMinute = new StatsByMinute(now); - statsByHour = new StatsByHour(now); - statsByDay = new StatsByDay(now); - statsByWeek = new StatsByWeek(now); - statsByMonth = new StatsByMonth(now); - } - - @Override - public boolean isStarted() { - return started; - } - - @Override - public void stop() { - started = false; - statsByMinute.reset(); - statsByHour.reset(); - statsByDay.reset(); - statsByWeek.reset(); - statsByMonth.reset(); - } - - @Override - public long getLastMinuteCount() { - return statsByMinute.getLastCount(); - } - - @Override - public double getMinuteAverage() { - return statsByMinute.getAverage(); - } - - @Override - public double getHourlyAverage() { - return statsByHour.getAverage(); - } - - @Override - public long getLastHoursCount() { - return statsByHour.getLastCount(); - } + final CountingFilter countingFilter; + boolean started; + + StatsByMinute statsByMinute = new StatsByMinute(); + StatsByHour statsByHour = new StatsByHour(); + StatsByDay statsByDay = new StatsByDay(); + StatsByWeek statsByWeek = new StatsByWeek(); + StatsByMonth statsByMonth = new StatsByMonth(); + + StatisticalViewImpl(CountingFilter countingFilter) { + this.countingFilter = countingFilter; + } + + @Override + public double getDailyAverage() { + return statsByDay.getAverage(); + } + + @Override + public long getLastDaysCount() { + return statsByDay.getLastCount(); + } + + @Override + public double getMonthlyAverage() { + return statsByMonth.getAverage(); + } + + @Override + public long getLastMonthsCount() { + return statsByMonth.getLastCount(); + } + + @Override + public long getTotal() { + return countingFilter.getTotal(); + } + + @Override + public double getWeeklyAverage() { + return statsByWeek.getAverage(); + } + + @Override + public long getLastWeeksCount() { + return statsByWeek.getLastCount(); + } + + void update(long now) { + long total = getTotal(); + statsByMinute.update(now, total); + statsByHour.update(now, total); + statsByDay.update(now, total); + statsByWeek.update(now, total); + statsByMonth.update(now, total); + + } + + void update() { + long now = System.currentTimeMillis(); + update(now); + } + + @Override + public void start() { + System.out.println("StatisticalViewImpl start called"); + started = true; + long now = System.currentTimeMillis(); + statsByMinute = new StatsByMinute(now); + statsByHour = new StatsByHour(now); + statsByDay = new StatsByDay(now); + statsByWeek = new StatsByWeek(now); + statsByMonth = new StatsByMonth(now); + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public void stop() { + started = false; + statsByMinute.reset(); + statsByHour.reset(); + statsByDay.reset(); + statsByWeek.reset(); + statsByMonth.reset(); + } + + @Override + public long getLastMinuteCount() { + return statsByMinute.getLastCount(); + } + + @Override + public double getMinuteAverage() { + return statsByMinute.getAverage(); + } + + @Override + public double getHourlyAverage() { + return statsByHour.getAverage(); + } + + @Override + public long getLastHoursCount() { + return statsByHour.getLastCount(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByDay.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByDay.java index 59df924b97618e5702c3d6c9bd1567bafed4daf9..d03f4a7989cbe7e8280b32783c4bd80864859bbb 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByDay.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByDay.java @@ -17,17 +17,17 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByDay extends PeriodicStats { - StatsByDay() { - super(); - } + StatsByDay() { + super(); + } - StatsByDay(long now) { - super(now); - } + StatsByDay(long now) { + super(now); + } - @Override - long computeStartOfNextPeriod(long now) { - return TimeUtil.computeStartOfNextDay(now); - } + @Override + long computeStartOfNextPeriod(long now) { + return TimeUtil.computeStartOfNextDay(now); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByHour.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByHour.java index e5db63ba8490e723873a362f4ee29e7b0303f39c..26d82507ade42590f8d303e3c1f3b09b588cd277 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByHour.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByHour.java @@ -17,17 +17,17 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByHour extends PeriodicStats { - StatsByHour() { - super(); - } + StatsByHour() { + super(); + } - StatsByHour(long now) { - super(now); - } + StatsByHour(long now) { + super(now); + } - @Override - long computeStartOfNextPeriod(long now) { - return TimeUtil.computeStartOfNextHour(now); - } + @Override + long computeStartOfNextPeriod(long now) { + return TimeUtil.computeStartOfNextHour(now); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMinute.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMinute.java index 3dc02035767ce704f489b6467e8705300baee00a..c29e45c7afe6524346e9c5dc222714a37767e301 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMinute.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMinute.java @@ -17,17 +17,17 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByMinute extends PeriodicStats { - StatsByMinute() { - super(); - } + StatsByMinute() { + super(); + } - StatsByMinute(long now) { - super(now); - } + StatsByMinute(long now) { + super(now); + } - @Override - long computeStartOfNextPeriod(long now) { - return TimeUtil.computeStartOfNextMinute(now); - } + @Override + long computeStartOfNextPeriod(long now) { + return TimeUtil.computeStartOfNextMinute(now); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMonth.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMonth.java index c7196c9c664951cf992b7039a2696922d9b20353..74e630e9efd74c1dcc0ed6cda68cb464a6194a1c 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMonth.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByMonth.java @@ -17,17 +17,17 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByMonth extends PeriodicStats { - StatsByMonth() { - super(); - } - - StatsByMonth(long now) { - super(now); - } - - @Override - long computeStartOfNextPeriod(long now) { - return TimeUtil.computeStartOfNextMonth(now); - } - + StatsByMonth() { + super(); + } + + StatsByMonth(long now) { + super(now); + } + + @Override + long computeStartOfNextPeriod(long now) { + return TimeUtil.computeStartOfNextMonth(now); + } + } diff --git a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByWeek.java b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByWeek.java index c800ee9e43f6eb61d27f17cd9bfa979b41f9f0a5..177ba6bbb7c3afba231ce0c0d5b75b8a91331605 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByWeek.java +++ b/logback-access/src/main/java/ch/qos/logback/access/filter/StatsByWeek.java @@ -17,16 +17,17 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByWeek extends PeriodicStats { - StatsByWeek() { - super(); - } - - StatsByWeek(long now) { - super(now); - } - @Override - long computeStartOfNextPeriod(long now) { - return TimeUtil.computeStartOfNextWeek(now); - } - + StatsByWeek() { + super(); + } + + StatsByWeek(long now) { + super(now); + } + + @Override + long computeStartOfNextPeriod(long now) { + return TimeUtil.computeStartOfNextWeek(now); + } + } diff --git a/logback-access/src/main/java/ch/qos/logback/access/html/DefaultCssBuilder.java b/logback-access/src/main/java/ch/qos/logback/access/html/DefaultCssBuilder.java index 5b643de241af14e98e8e1775dc675a07bbb0493e..18e93578a7b196075213f543962b8af93da67ef0 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/html/DefaultCssBuilder.java +++ b/logback-access/src/main/java/ch/qos/logback/access/html/DefaultCssBuilder.java @@ -25,57 +25,54 @@ import ch.qos.logback.core.html.CssBuilder; */ public class DefaultCssBuilder implements CssBuilder { - @Override - public void addCss(StringBuilder sbuf) { - sbuf.append(""); - } + @Override + public void addCss(StringBuilder sbuf) { + sbuf.append(""); + } } \ No newline at end of file diff --git a/logback-access/src/main/java/ch/qos/logback/access/html/HTMLLayout.java b/logback-access/src/main/java/ch/qos/logback/access/html/HTMLLayout.java index f756403cb8602236839e150a4a6f2baacbad91e5..932d2ad97be20229f8a3377732cbeca0259a960b 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/html/HTMLLayout.java +++ b/logback-access/src/main/java/ch/qos/logback/access/html/HTMLLayout.java @@ -39,62 +39,61 @@ import ch.qos.logback.core.pattern.Converter; */ public class HTMLLayout extends HTMLLayoutBase { - /** - * Default pattern string for log output. - */ - static final String DEFAULT_CONVERSION_PATTERN = "%h%l%u%t%r%s%b"; + /** + * Default pattern string for log output. + */ + static final String DEFAULT_CONVERSION_PATTERN = "%h%l%u%t%r%s%b"; - /** - * Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. - * - */ - public HTMLLayout() { - pattern = DEFAULT_CONVERSION_PATTERN; - cssBuilder = new DefaultCssBuilder(); - } - - @Override - protected Map getDefaultConverterMap() { - return PatternLayout.defaultConverterMap; - } - - @Override - public String doLayout(IAccessEvent event) { - StringBuilder buf = new StringBuilder(); - startNewTableIfLimitReached(buf); - - boolean odd = true; - if (((counter++) & 1) == 0) { - odd = false; + /** + * Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. + * + */ + public HTMLLayout() { + pattern = DEFAULT_CONVERSION_PATTERN; + cssBuilder = new DefaultCssBuilder(); } - buf.append(LINE_SEPARATOR); - buf.append(""); - } else { - buf.append(" even\">"); + @Override + protected Map getDefaultConverterMap() { + return PatternLayout.defaultConverterMap; } - buf.append(LINE_SEPARATOR); - Converter c = head; - while (c != null) { - appendEventToBuffer(buf, c, event); - c = c.getNext(); - } - buf.append(""); - buf.append(LINE_SEPARATOR); + @Override + public String doLayout(IAccessEvent event) { + StringBuilder buf = new StringBuilder(); + startNewTableIfLimitReached(buf); + + boolean odd = true; + if (((counter++) & 1) == 0) { + odd = false; + } - return buf.toString(); - } + buf.append(LINE_SEPARATOR); + buf.append(""); + } else { + buf.append(" even\">"); + } + buf.append(LINE_SEPARATOR); - private void appendEventToBuffer(StringBuilder buf, Converter c, - IAccessEvent event) { - buf.append(""); - c.write(buf, event); - buf.append(""); - buf.append(LINE_SEPARATOR); - } + Converter c = head; + while (c != null) { + appendEventToBuffer(buf, c, event); + c = c.getNext(); + } + buf.append(""); + buf.append(LINE_SEPARATOR); + + return buf.toString(); + } + + private void appendEventToBuffer(StringBuilder buf, Converter c, IAccessEvent event) { + buf.append(""); + c.write(buf, event); + buf.append(""); + buf.append(LINE_SEPARATOR); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/html/UrlCssBuilder.java b/logback-access/src/main/java/ch/qos/logback/access/html/UrlCssBuilder.java index bb087216d41e6b590674a3b9afd2b78a4fe9794b..77185b3fcfb1bf02ad6ef60b6f1685c25236e9e7 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/html/UrlCssBuilder.java +++ b/logback-access/src/main/java/ch/qos/logback/access/html/UrlCssBuilder.java @@ -15,7 +15,6 @@ package ch.qos.logback.access.html; import ch.qos.logback.core.html.CssBuilder; - /** * This class helps the HTMLLayout build the CSS link. * It either provides the HTMLLayout with a default css file, @@ -25,20 +24,20 @@ import ch.qos.logback.core.html.CssBuilder; */ public class UrlCssBuilder implements CssBuilder { - String url = "http://logback.qos.ch/css/access.css"; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } + String url = "http://logback.qos.ch/css/access.css"; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } - @Override - public void addCss(StringBuilder sbuf) { - sbuf.append(""); - } + @Override + public void addCss(StringBuilder sbuf) { + sbuf.append(""); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/jetty/JettyServerAdapter.java b/logback-access/src/main/java/ch/qos/logback/access/jetty/JettyServerAdapter.java index 3c2d3038b8bbdcaa8a677bdca2ee89a2265da28a..b472280ae17da74724e0fceb61d2445f6ec179af 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/jetty/JettyServerAdapter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/jetty/JettyServerAdapter.java @@ -31,40 +31,40 @@ import java.util.Map; */ public class JettyServerAdapter implements ServerAdapter { - Request request; - Response response; + Request request; + Response response; - public JettyServerAdapter(Request jettyRequest, Response jettyResponse) { - this.request = jettyRequest; - this.response = jettyResponse; - } + public JettyServerAdapter(Request jettyRequest, Response jettyResponse) { + this.request = jettyRequest; + this.response = jettyResponse; + } - @Override - public long getContentLength() { - return response.getContentCount(); - } + @Override + public long getContentLength() { + return response.getContentCount(); + } - @Override - public int getStatusCode() { - return response.getStatus(); - } + @Override + public int getStatusCode() { + return response.getStatus(); + } - @Override - public long getRequestTimestamp() { - return request.getTimeStamp(); - } + @Override + public long getRequestTimestamp() { + return request.getTimeStamp(); + } - @Override - public Map buildResponseHeaderMap() { - Map responseHeaderMap = new HashMap(); - HttpFields httpFields = response.getHttpFields(); - Enumeration e = httpFields.getFieldNames(); - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - String value = response.getHeader(key); - responseHeaderMap.put(key, value); + @Override + public Map buildResponseHeaderMap() { + Map responseHeaderMap = new HashMap(); + HttpFields httpFields = response.getHttpFields(); + Enumeration e = httpFields.getFieldNames(); + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + String value = response.getHeader(key); + responseHeaderMap.put(key, value); + } + return responseHeaderMap; } - return responseHeaderMap; - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogImpl.java b/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogImpl.java index 371b70b385a4de5c17d71bfc729450f4f0514ff7..b2ba454b014f939089f0460de9e0d5749eea61a1 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogImpl.java +++ b/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogImpl.java @@ -113,216 +113,212 @@ import ch.qos.logback.core.util.OptionHelper; * @author Ceki Gülcü * @author Sébastien Pennec */ -public class RequestLogImpl extends ContextBase implements RequestLog, - AppenderAttachable, FilterAttachable { - - public final static String DEFAULT_CONFIG_FILE = "etc" + File.separatorChar - + "logback-access.xml"; - - AppenderAttachableImpl aai = new AppenderAttachableImpl(); - FilterAttachableImpl fai = new FilterAttachableImpl(); - String fileName; - String resource; - boolean started = false; - boolean quiet = false; - - public RequestLogImpl() { - putObject(CoreConstants.EVALUATOR_MAP, new HashMap>()); - } - - @Override - public void log(Request jettyRequest, Response jettyResponse) { - JettyServerAdapter adapter = new JettyServerAdapter(jettyRequest, - jettyResponse); - IAccessEvent accessEvent = new AccessEvent(jettyRequest, jettyResponse, - adapter); - if (getFilterChainDecision(accessEvent) == FilterReply.DENY) { - return; - } - aai.appendLoopOnAppenders(accessEvent); - } - - private void addInfo(String msg) { - getStatusManager().add(new InfoStatus(msg, this)); - } - - private void addError(String msg) { - getStatusManager().add(new ErrorStatus(msg, this)); - } - - @Override - public void start() { - configure(); - if (!isQuiet()) { - StatusPrinter.print(getStatusManager()); - } - started = true; - } - - protected void configure() { - URL configURL = getConfigurationFileURL(); - if (configURL != null) { - runJoranOnFile(configURL); - } else { - addError("Could not find configuration file for logback-access"); - } - } - - protected URL getConfigurationFileURL() { - if (fileName != null) { - addInfo("Will use configuration file [" + fileName + "]"); - File file = new File(fileName); - if (!file.exists()) - return null; - return FileUtil.fileToURL(file); - } - if (resource != null) { - addInfo("Will use configuration resource [" + resource + "]"); - return this.getClass().getResource(resource); - } - - String jettyHomeProperty = OptionHelper.getSystemProperty("jetty.home"); - String defaultConfigFile = DEFAULT_CONFIG_FILE; - if (!OptionHelper.isEmpty(jettyHomeProperty)) { - defaultConfigFile = jettyHomeProperty + File.separatorChar + DEFAULT_CONFIG_FILE; - } else { - addInfo("[jetty.home] system property not set."); - } - File file = new File(defaultConfigFile); - addInfo("Assuming default configuration file ["+defaultConfigFile+"]"); - if (!file.exists()) - return null; - return FileUtil.fileToURL(file); - } - - private void runJoranOnFile(URL configURL) { - try { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(this); - jc.doConfigure(configURL); - if (getName() == null) { - setName("LogbackRequestLog"); - } - } catch (JoranException e) { - // errors have been registered as status messages - } - } - - @Override - public void stop() { - aai.detachAndStopAllAppenders(); - started = false; - } - - @Override - public boolean isRunning() { - return started; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public void setResource(String resource) { - this.resource = resource; - } - - @Override - public boolean isStarted() { - return started; - } - - @Override - public boolean isStarting() { - return false; - } - - @Override - public boolean isStopping() { - return false; - } - - @Override - public boolean isStopped() { - return !started; - } - - @Override - public boolean isFailed() { - return false; - } - - public boolean isQuiet() { - return quiet; - } - - public void setQuiet(boolean quiet) { - this.quiet = quiet; - } - - @Override - public void addAppender(Appender newAppender) { - aai.addAppender(newAppender); - } - - @Override - public Iterator> iteratorForAppenders() { - return aai.iteratorForAppenders(); - } - - @Override - public Appender getAppender(String name) { - return aai.getAppender(name); - } - - @Override - public boolean isAttached(Appender appender) { - return aai.isAttached(appender); - } - - @Override - public void detachAndStopAllAppenders() { - aai.detachAndStopAllAppenders(); - } - - @Override - public boolean detachAppender(Appender appender) { - return aai.detachAppender(appender); - } - - @Override - public boolean detachAppender(String name) { - return aai.detachAppender(name); - } - - @Override - public void addFilter(Filter newFilter) { - fai.addFilter(newFilter); - } - - @Override - public void clearAllFilters() { - fai.clearAllFilters(); - } - - @Override - public List> getCopyOfAttachedFiltersList() { - return fai.getCopyOfAttachedFiltersList(); - } - - @Override - public FilterReply getFilterChainDecision(IAccessEvent event) { - return fai.getFilterChainDecision(event); - } - - @Override - public void addLifeCycleListener(Listener listener) { - // we'll implement this when asked - } - - @Override - public void removeLifeCycleListener(Listener listener) { - // we'll implement this when asked - } +public class RequestLogImpl extends ContextBase implements RequestLog, AppenderAttachable, FilterAttachable { + + public final static String DEFAULT_CONFIG_FILE = "etc" + File.separatorChar + "logback-access.xml"; + + AppenderAttachableImpl aai = new AppenderAttachableImpl(); + FilterAttachableImpl fai = new FilterAttachableImpl(); + String fileName; + String resource; + boolean started = false; + boolean quiet = false; + + public RequestLogImpl() { + putObject(CoreConstants.EVALUATOR_MAP, new HashMap>()); + } + + @Override + public void log(Request jettyRequest, Response jettyResponse) { + JettyServerAdapter adapter = new JettyServerAdapter(jettyRequest, jettyResponse); + IAccessEvent accessEvent = new AccessEvent(jettyRequest, jettyResponse, adapter); + if (getFilterChainDecision(accessEvent) == FilterReply.DENY) { + return; + } + aai.appendLoopOnAppenders(accessEvent); + } + + private void addInfo(String msg) { + getStatusManager().add(new InfoStatus(msg, this)); + } + + private void addError(String msg) { + getStatusManager().add(new ErrorStatus(msg, this)); + } + + @Override + public void start() { + configure(); + if (!isQuiet()) { + StatusPrinter.print(getStatusManager()); + } + started = true; + } + + protected void configure() { + URL configURL = getConfigurationFileURL(); + if (configURL != null) { + runJoranOnFile(configURL); + } else { + addError("Could not find configuration file for logback-access"); + } + } + + protected URL getConfigurationFileURL() { + if (fileName != null) { + addInfo("Will use configuration file [" + fileName + "]"); + File file = new File(fileName); + if (!file.exists()) + return null; + return FileUtil.fileToURL(file); + } + if (resource != null) { + addInfo("Will use configuration resource [" + resource + "]"); + return this.getClass().getResource(resource); + } + + String jettyHomeProperty = OptionHelper.getSystemProperty("jetty.home"); + String defaultConfigFile = DEFAULT_CONFIG_FILE; + if (!OptionHelper.isEmpty(jettyHomeProperty)) { + defaultConfigFile = jettyHomeProperty + File.separatorChar + DEFAULT_CONFIG_FILE; + } else { + addInfo("[jetty.home] system property not set."); + } + File file = new File(defaultConfigFile); + addInfo("Assuming default configuration file [" + defaultConfigFile + "]"); + if (!file.exists()) + return null; + return FileUtil.fileToURL(file); + } + + private void runJoranOnFile(URL configURL) { + try { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(this); + jc.doConfigure(configURL); + if (getName() == null) { + setName("LogbackRequestLog"); + } + } catch (JoranException e) { + // errors have been registered as status messages + } + } + + @Override + public void stop() { + aai.detachAndStopAllAppenders(); + started = false; + } + + @Override + public boolean isRunning() { + return started; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public void setResource(String resource) { + this.resource = resource; + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public boolean isStarting() { + return false; + } + + @Override + public boolean isStopping() { + return false; + } + + @Override + public boolean isStopped() { + return !started; + } + + @Override + public boolean isFailed() { + return false; + } + + public boolean isQuiet() { + return quiet; + } + + public void setQuiet(boolean quiet) { + this.quiet = quiet; + } + + @Override + public void addAppender(Appender newAppender) { + aai.addAppender(newAppender); + } + + @Override + public Iterator> iteratorForAppenders() { + return aai.iteratorForAppenders(); + } + + @Override + public Appender getAppender(String name) { + return aai.getAppender(name); + } + + @Override + public boolean isAttached(Appender appender) { + return aai.isAttached(appender); + } + + @Override + public void detachAndStopAllAppenders() { + aai.detachAndStopAllAppenders(); + } + + @Override + public boolean detachAppender(Appender appender) { + return aai.detachAppender(appender); + } + + @Override + public boolean detachAppender(String name) { + return aai.detachAppender(name); + } + + @Override + public void addFilter(Filter newFilter) { + fai.addFilter(newFilter); + } + + @Override + public void clearAllFilters() { + fai.clearAllFilters(); + } + + @Override + public List> getCopyOfAttachedFiltersList() { + return fai.getCopyOfAttachedFiltersList(); + } + + @Override + public FilterReply getFilterChainDecision(IAccessEvent event) { + return fai.getFilterChainDecision(event); + } + + @Override + public void addLifeCycleListener(Listener listener) { + // we'll implement this when asked + } + + @Override + public void removeLifeCycleListener(Listener listener) { + // we'll implement this when asked + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogRegistry.java b/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogRegistry.java index c0c203463fe53ef81ea5e44e616709eab66b6998..acdf91dfa8fe701ea5650fd7d98233e95a8ba030 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogRegistry.java +++ b/logback-access/src/main/java/ch/qos/logback/access/jetty/RequestLogRegistry.java @@ -18,15 +18,15 @@ import java.util.Map; // this class is currently not used public class RequestLogRegistry { - - private static Map requestLogRegistry = new HashMap(); - - public static void register(RequestLogImpl requestLogImpl) { - requestLogRegistry.put(requestLogImpl.getName(), requestLogImpl); - } - - public static RequestLogImpl get(String key) { - return requestLogRegistry.get(key); - } + + private static Map requestLogRegistry = new HashMap(); + + public static void register(RequestLogImpl requestLogImpl) { + requestLogRegistry.put(requestLogImpl.getName(), requestLogImpl); + } + + public static RequestLogImpl get(String key) { + return requestLogRegistry.get(key); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/joran/JoranConfigurator.java b/logback-access/src/main/java/ch/qos/logback/access/joran/JoranConfigurator.java index 4cf9f83a88ef64051f03d4de27ba6291382b640b..58ab87ae1b38e8c4afa8d7ed833fc79057bb0eb9 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/joran/JoranConfigurator.java +++ b/logback-access/src/main/java/ch/qos/logback/access/joran/JoranConfigurator.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.access.joran; - import ch.qos.logback.access.PatternLayout; import ch.qos.logback.access.PatternLayoutEncoder; import ch.qos.logback.access.boolex.JaninoEventEvaluator; @@ -35,8 +34,6 @@ import ch.qos.logback.core.joran.spi.ElementSelector; import ch.qos.logback.core.joran.spi.RuleStore; import ch.qos.logback.core.net.ssl.SSLNestedComponentRegistryRules; - - /** * This JoranConfiguratorclass adds rules specific to logback-access. * @@ -44,38 +41,36 @@ import ch.qos.logback.core.net.ssl.SSLNestedComponentRegistryRules; */ public class JoranConfigurator extends JoranConfiguratorBase { - @Override - public void addInstanceRules(RuleStore rs) { - super.addInstanceRules(rs); - - rs.addRule(new ElementSelector("configuration"), new ConfigurationAction()); - rs.addRule(new ElementSelector("configuration/appender-ref"), new AppenderRefAction()); - - rs.addRule(new ElementSelector("configuration/appender/sift"), new SiftAction()); - rs.addRule(new ElementSelector("configuration/appender/sift/*"), new NOPAction()); - - rs.addRule(new ElementSelector("configuration/evaluator"), new EvaluatorAction()); + @Override + public void addInstanceRules(RuleStore rs) { + super.addInstanceRules(rs); + + rs.addRule(new ElementSelector("configuration"), new ConfigurationAction()); + rs.addRule(new ElementSelector("configuration/appender-ref"), new AppenderRefAction()); + + rs.addRule(new ElementSelector("configuration/appender/sift"), new SiftAction()); + rs.addRule(new ElementSelector("configuration/appender/sift/*"), new NOPAction()); + + rs.addRule(new ElementSelector("configuration/evaluator"), new EvaluatorAction()); - // add if-then-else support - rs.addRule(new ElementSelector("*/if"), new IfAction()); - rs.addRule(new ElementSelector("*/if/then"), new ThenAction()); - rs.addRule(new ElementSelector("*/if/then/*"), new NOPAction()); - rs.addRule(new ElementSelector("*/if/else"), new ElseAction()); - rs.addRule(new ElementSelector("*/if/else/*"), new NOPAction()); + // add if-then-else support + rs.addRule(new ElementSelector("*/if"), new IfAction()); + rs.addRule(new ElementSelector("*/if/then"), new ThenAction()); + rs.addRule(new ElementSelector("*/if/then/*"), new NOPAction()); + rs.addRule(new ElementSelector("*/if/else"), new ElseAction()); + rs.addRule(new ElementSelector("*/if/else/*"), new NOPAction()); - rs.addRule(new ElementSelector("configuration/include"), new IncludeAction()); - } + rs.addRule(new ElementSelector("configuration/include"), new IncludeAction()); + } - @Override - protected void addDefaultNestedComponentRegistryRules( - DefaultNestedComponentRegistry registry) { - registry.add(AppenderBase.class, "layout", PatternLayout.class); - registry - .add(EvaluatorFilter.class, "evaluator", JaninoEventEvaluator.class); + @Override + protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + registry.add(AppenderBase.class, "layout", PatternLayout.class); + registry.add(EvaluatorFilter.class, "evaluator", JaninoEventEvaluator.class); - registry.add(AppenderBase.class, "encoder", PatternLayoutEncoder.class); - registry.add(UnsynchronizedAppenderBase.class, "encoder", PatternLayoutEncoder.class); - SSLNestedComponentRegistryRules.addDefaultNestedComponentRegistryRules(registry); - } + registry.add(AppenderBase.class, "encoder", PatternLayoutEncoder.class); + registry.add(UnsynchronizedAppenderBase.class, "encoder", PatternLayoutEncoder.class); + SSLNestedComponentRegistryRules.addDefaultNestedComponentRegistryRules(registry); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/joran/action/ConfigurationAction.java b/logback-access/src/main/java/ch/qos/logback/access/joran/action/ConfigurationAction.java index 0740dcf7f8835598a52d984f0f89d205141bdbda..7092b94de6dc745c789680ef5f5181c9e16111f6 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/joran/action/ConfigurationAction.java +++ b/logback-access/src/main/java/ch/qos/logback/access/joran/action/ConfigurationAction.java @@ -23,37 +23,36 @@ import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.ContextUtil; - public class ConfigurationAction extends Action { - static final String INTERNAL_DEBUG_ATTR = "debug"; - static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback-access.debug"; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) { - - // See LBCLASSIC-225 (the system property is looked up first. Thus, it overrides - // the equivalent property in the config file. This reversal of scope priority is justified - // by the use case: the admin trying to chase rogue config file - String debugAttrib = System.getProperty(DEBUG_SYSTEM_PROPERTY_KEY); - if (debugAttrib == null) { - debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR); + static final String INTERNAL_DEBUG_ATTR = "debug"; + static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback-access.debug"; + + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) { + + // See LBCLASSIC-225 (the system property is looked up first. Thus, it overrides + // the equivalent property in the config file. This reversal of scope priority is justified + // by the use case: the admin trying to chase rogue config file + String debugAttrib = System.getProperty(DEBUG_SYSTEM_PROPERTY_KEY); + if (debugAttrib == null) { + debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR); + } + + if (OptionHelper.isEmpty(debugAttrib) || debugAttrib.equals("false") || debugAttrib.equals("null")) { + addInfo(INTERNAL_DEBUG_ATTR + " attribute not set"); + } else { + StatusListenerConfigHelper.addOnConsoleListenerInstance(context, new OnConsoleStatusListener()); + } + + new ContextUtil(context).addHostNameAsProperty(); + + // the context is appender attachable, so it is pushed on top of the stack + ec.pushObject(getContext()); } - if (OptionHelper.isEmpty(debugAttrib) || debugAttrib.equals("false") || debugAttrib.equals("null")) { - addInfo(INTERNAL_DEBUG_ATTR + " attribute not set"); - } else { - StatusListenerConfigHelper.addOnConsoleListenerInstance(context, new OnConsoleStatusListener()); + @Override + public void end(InterpretationContext ec, String name) { + addInfo("End of configuration."); + ec.popObject(); } - - new ContextUtil(context).addHostNameAsProperty(); - - // the context is appender attachable, so it is pushed on top of the stack - ec.pushObject(getContext()); - } - - @Override - public void end(InterpretationContext ec, String name) { - addInfo("End of configuration."); - ec.popObject(); - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/joran/action/EvaluatorAction.java b/logback-access/src/main/java/ch/qos/logback/access/joran/action/EvaluatorAction.java index 1620573e298866e733c46da2ac00b15a4fde023d..5fa3bff6cf2c22e74ae2ff1a24dfa748db3753e2 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/joran/action/EvaluatorAction.java +++ b/logback-access/src/main/java/ch/qos/logback/access/joran/action/EvaluatorAction.java @@ -16,11 +16,10 @@ package ch.qos.logback.access.joran.action; import ch.qos.logback.access.boolex.JaninoEventEvaluator; import ch.qos.logback.core.joran.action.AbstractEventEvaluatorAction; - public class EvaluatorAction extends AbstractEventEvaluatorAction { - @Override - protected String defaultClassName() { - return JaninoEventEvaluator.class.getName(); - } + @Override + protected String defaultClassName() { + return JaninoEventEvaluator.class.getName(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/AccessEventPreSerializationTransformer.java b/logback-access/src/main/java/ch/qos/logback/access/net/AccessEventPreSerializationTransformer.java index 1729d114f2c833ba1ca97c4a5c4ded30b83cbd1b..b75b4faeefe601d349d343d022abaca3e59c6d65 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/AccessEventPreSerializationTransformer.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/AccessEventPreSerializationTransformer.java @@ -19,16 +19,15 @@ import ch.qos.logback.access.spi.AccessEvent; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.spi.PreSerializationTransformer; -public class AccessEventPreSerializationTransformer implements - PreSerializationTransformer { +public class AccessEventPreSerializationTransformer implements PreSerializationTransformer { - @Override - public Serializable transform(IAccessEvent event) { - if (event instanceof AccessEvent) { - return (AccessEvent)event; - } else { - throw new IllegalArgumentException("Unsupported type "+event.getClass().getName()); + @Override + public Serializable transform(IAccessEvent event) { + if (event instanceof AccessEvent) { + return (AccessEvent) event; + } else { + throw new IllegalArgumentException("Unsupported type " + event.getClass().getName()); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/SMTPAppender.java b/logback-access/src/main/java/ch/qos/logback/access/net/SMTPAppender.java index 64e9f15b0981b6e8ca19976e5886785da0078b11..e40a5afbcec14244e2347ec273de48af55d7f3d8 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/SMTPAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/SMTPAppender.java @@ -33,64 +33,64 @@ import ch.qos.logback.core.net.SMTPAppenderBase; */ public class SMTPAppender extends SMTPAppenderBase { - static final String DEFAULT_SUBJECT_PATTERN = "%m"; + static final String DEFAULT_SUBJECT_PATTERN = "%m"; - /** - * The default constructor will instantiate the appender with a - * {@link EventEvaluator} that will trigger on events with level - * ERROR or higher. - */ - public SMTPAppender() { - } + /** + * The default constructor will instantiate the appender with a + * {@link EventEvaluator} that will trigger on events with level + * ERROR or higher. + */ + public SMTPAppender() { + } - /** - * Use evaluator passed as parameter as the {@link - * EventEvaluator} for this SMTPAppender. - */ - public SMTPAppender(EventEvaluator evaluator) { - this.eventEvaluator = evaluator; - } + /** + * Use evaluator passed as parameter as the {@link + * EventEvaluator} for this SMTPAppender. + */ + public SMTPAppender(EventEvaluator evaluator) { + this.eventEvaluator = evaluator; + } - /** - * Perform SMTPAppender specific appending actions, mainly adding the event to - * the appropriate cyclic buffer. - */ - @Override - protected void subAppend(CyclicBuffer cb, IAccessEvent event) { - cb.add(event); - } + /** + * Perform SMTPAppender specific appending actions, mainly adding the event to + * the appropriate cyclic buffer. + */ + @Override + protected void subAppend(CyclicBuffer cb, IAccessEvent event) { + cb.add(event); + } - @Override - protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf) { - int len = cb.length(); - for (int i = 0; i < len; i++) { - // sbuf.append(MimeUtility.encodeText(layout.format(cb.getOrCreate()))); - IAccessEvent event = cb.get(); - sbuf.append(layout.doLayout(event)); + @Override + protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf) { + int len = cb.length(); + for (int i = 0; i < len; i++) { + // sbuf.append(MimeUtility.encodeText(layout.format(cb.getOrCreate()))); + IAccessEvent event = cb.get(); + sbuf.append(layout.doLayout(event)); + } } - } - @Override - protected Layout makeSubjectLayout(String subjectStr) { - if(subjectStr == null) { - subjectStr = DEFAULT_SUBJECT_PATTERN; + @Override + protected Layout makeSubjectLayout(String subjectStr) { + if (subjectStr == null) { + subjectStr = DEFAULT_SUBJECT_PATTERN; + } + PatternLayout pl = new PatternLayout(); + pl.setPattern(subjectStr); + pl.start(); + return pl; } - PatternLayout pl = new PatternLayout(); - pl.setPattern(subjectStr); - pl.start(); - return pl; - } - @Override - protected PatternLayout makeNewToPatternLayout(String toPattern) { - PatternLayout pl = new PatternLayout(); - pl.setPattern(toPattern); - return pl; - } + @Override + protected PatternLayout makeNewToPatternLayout(String toPattern) { + PatternLayout pl = new PatternLayout(); + pl.setPattern(toPattern); + return pl; + } - @Override - protected boolean eventMarksEndOfLife(IAccessEvent eventObject) { - return false; - } + @Override + protected boolean eventMarksEndOfLife(IAccessEvent eventObject) { + return false; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/SSLSocketAppender.java b/logback-access/src/main/java/ch/qos/logback/access/net/SSLSocketAppender.java index 589a9df262de8b531afd263b43aced5c6fae66b9..a171715eaf8e0d709c02adf50b921325089a08c7 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/SSLSocketAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/SSLSocketAppender.java @@ -27,19 +27,18 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class SSLSocketAppender extends AbstractSSLSocketAppender { - private final PreSerializationTransformer pst = - new AccessEventPreSerializationTransformer(); + private final PreSerializationTransformer pst = new AccessEventPreSerializationTransformer(); - public SSLSocketAppender() { - } + public SSLSocketAppender() { + } - @Override - protected void postProcessEvent(IAccessEvent event) { - event.prepareForDeferredProcessing(); - } + @Override + protected void postProcessEvent(IAccessEvent event) { + event.prepareForDeferredProcessing(); + } + + public PreSerializationTransformer getPST() { + return pst; + } - public PreSerializationTransformer getPST() { - return pst; - } - } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/SimpleSocketServer.java b/logback-access/src/main/java/ch/qos/logback/access/net/SimpleSocketServer.java index 7196fd637cd6d318e836f0507bea95b2492151a7..0dc1ce6de6f8aefb4fee756bbb114be374334cff 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/SimpleSocketServer.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/SimpleSocketServer.java @@ -45,57 +45,56 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class SimpleSocketServer { - static int port; - - private static AccessContext basicContext; + static int port; - public static void main(String argv[]) throws Exception { - if (argv.length == 2) { - init(argv[0], argv[1]); - } else { - usage("Wrong number of arguments."); - } + private static AccessContext basicContext; - runServer(); - } + public static void main(String argv[]) throws Exception { + if (argv.length == 2) { + init(argv[0], argv[1]); + } else { + usage("Wrong number of arguments."); + } - static void runServer() { - try { - System.out.println("Listening on port " + port); - ServerSocket serverSocket = new ServerSocket(port); - while (true) { - System.out.println("Waiting to accept a new client."); - Socket socket = serverSocket.accept(); - System.out.println("Connected to client at " + socket.getInetAddress()); - System.out.println("Starting new socket node."); - new Thread(new SocketNode(socket, basicContext)).start(); - } - } catch (Exception e) { - e.printStackTrace(); + runServer(); } - } - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SimpleSocketServer.class.getName() - + " port configFile"); - System.exit(1); - } + static void runServer() { + try { + System.out.println("Listening on port " + port); + ServerSocket serverSocket = new ServerSocket(port); + while (true) { + System.out.println("Waiting to accept a new client."); + Socket socket = serverSocket.accept(); + System.out.println("Connected to client at " + socket.getInetAddress()); + System.out.println("Starting new socket node."); + new Thread(new SocketNode(socket, basicContext)).start(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } - static void init(String portStr, String configFile) throws JoranException { - try { - port = Integer.parseInt(portStr); - } catch (java.lang.NumberFormatException e) { - e.printStackTrace(); - usage("Could not interpret port number [" + portStr + "]."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SimpleSocketServer.class.getName() + " port configFile"); + System.exit(1); } - basicContext = new AccessContext(); - if (configFile.endsWith(".xml")) { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(basicContext); - configurator.doConfigure(configFile); - StatusPrinter.print(basicContext); + static void init(String portStr, String configFile) throws JoranException { + try { + port = Integer.parseInt(portStr); + } catch (java.lang.NumberFormatException e) { + e.printStackTrace(); + usage("Could not interpret port number [" + portStr + "]."); + } + + basicContext = new AccessContext(); + if (configFile.endsWith(".xml")) { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(basicContext); + configurator.doConfigure(configFile); + StatusPrinter.print(basicContext); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/SocketAppender.java b/logback-access/src/main/java/ch/qos/logback/access/net/SocketAppender.java index 981737da3d43a889cd7c7f7df5b35fdc55573135..8189aee4b395367efd67be96b0b7ea24de9a5d73 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/SocketAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/SocketAppender.java @@ -31,18 +31,18 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class SocketAppender extends AbstractSocketAppender { - - PreSerializationTransformer pst = new AccessEventPreSerializationTransformer(); - - public SocketAppender() { - } - @Override - protected void postProcessEvent(IAccessEvent event) { - event.prepareForDeferredProcessing(); - } + PreSerializationTransformer pst = new AccessEventPreSerializationTransformer(); - public PreSerializationTransformer getPST() { - return pst; - } + public SocketAppender() { + } + + @Override + protected void postProcessEvent(IAccessEvent event) { + event.prepareForDeferredProcessing(); + } + + public PreSerializationTransformer getPST() { + return pst; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/SocketNode.java b/logback-access/src/main/java/ch/qos/logback/access/net/SocketNode.java index 2f78bae018ec8425a5788bb64e05830c0d21c552..95e25cf852a04d1c55c95be5c9f3905a53c4029d 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/SocketNode.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/SocketNode.java @@ -40,51 +40,50 @@ import ch.qos.logback.core.spi.FilterReply; */ public class SocketNode implements Runnable { - Socket socket; - AccessContext context; - ObjectInputStream ois; + Socket socket; + AccessContext context; + ObjectInputStream ois; - public SocketNode(Socket socket, AccessContext context) { - this.socket = socket; - this.context = context; - try { - ois = new ObjectInputStream(new BufferedInputStream(socket - .getInputStream())); - } catch (Exception e) { - System.out.println("Could not open ObjectInputStream to " + socket + e); + public SocketNode(Socket socket, AccessContext context) { + this.socket = socket; + this.context = context; + try { + ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream())); + } catch (Exception e) { + System.out.println("Could not open ObjectInputStream to " + socket + e); + } } - } - @Override - public void run() { - IAccessEvent event; + @Override + public void run() { + IAccessEvent event; - try { - while (true) { - // read an event from the wire - event = (IAccessEvent) ois.readObject(); - //check that the event should be logged - if (context.getFilterChainDecision(event) == FilterReply.DENY) { - break; + try { + while (true) { + // read an event from the wire + event = (IAccessEvent) ois.readObject(); + // check that the event should be logged + if (context.getFilterChainDecision(event) == FilterReply.DENY) { + break; + } + // send it to the appenders + context.callAppenders(event); + } + } catch (java.io.EOFException e) { + System.out.println("Caught java.io.EOFException closing connection."); + } catch (java.net.SocketException e) { + System.out.println("Caught java.net.SocketException closing connection."); + } catch (IOException e) { + System.out.println("Caught java.io.IOException: " + e); + System.out.println("Closing connection."); + } catch (Exception e) { + System.out.println("Unexpected exception. Closing connection." + e); } - //send it to the appenders - context.callAppenders(event); - } - } catch (java.io.EOFException e) { - System.out.println("Caught java.io.EOFException closing connection."); - } catch (java.net.SocketException e) { - System.out.println("Caught java.net.SocketException closing connection."); - } catch (IOException e) { - System.out.println("Caught java.io.IOException: " + e); - System.out.println("Closing connection."); - } catch (Exception e) { - System.out.println("Unexpected exception. Closing connection." + e); - } - try { - ois.close(); - } catch (Exception e) { - System.out.println("Could not close connection." + e); + try { + ois.close(); + } catch (Exception e) { + System.out.println("Could not close connection." + e); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/URLEvaluator.java b/logback-access/src/main/java/ch/qos/logback/access/net/URLEvaluator.java index 3c8e73a1dafb826b7736e3b5d8e1d49275c4e870..17e96a4c61626cf990aa81716d126d41a737fcf6 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/URLEvaluator.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/URLEvaluator.java @@ -24,52 +24,52 @@ import ch.qos.logback.core.spi.LifeCycle; public class URLEvaluator extends ContextAwareBase implements EventEvaluator, LifeCycle { - boolean started; - String name; - private List URLList = new ArrayList(); + boolean started; + String name; + private List URLList = new ArrayList(); - public void addURL(String url) { - URLList.add(url); - } + public void addURL(String url) { + URLList.add(url); + } - @Override - public void start() { - if (URLList.size() == 0) { - addWarn("No URL was given to URLEvaluator"); - } else { - started = true; + @Override + public void start() { + if (URLList.size() == 0) { + addWarn("No URL was given to URLEvaluator"); + } else { + started = true; + } } - } - @Override - public boolean evaluate(Object eventObject) throws NullPointerException, EvaluationException { - IAccessEvent event = (IAccessEvent)eventObject; - String url = event.getRequestURL(); - for(String expected:URLList) { - if (url.contains(expected)) { - return true; - } + @Override + public boolean evaluate(Object eventObject) throws NullPointerException, EvaluationException { + IAccessEvent event = (IAccessEvent) eventObject; + String url = event.getRequestURL(); + for (String expected : URLList) { + if (url.contains(expected)) { + return true; + } + } + return false; } - return false; - } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public void setName(String name) { - this.name = name; - } + @Override + public void setName(String name) { + this.name = name; + } - @Override - public boolean isStarted() { - return started; - } + @Override + public boolean isStarted() { + return started; + } - @Override - public void stop() { - started = false; - } + @Override + public void stop() { + started = false; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/server/SSLServerSocketAppender.java b/logback-access/src/main/java/ch/qos/logback/access/net/server/SSLServerSocketAppender.java index 02239634b529a43012725b14dd733c89cba0afac..916818b9540c1080eb12be6e5f82f9208e84eca2 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/server/SSLServerSocketAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/server/SSLServerSocketAppender.java @@ -25,20 +25,18 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * * @author Carl Harris */ -public class SSLServerSocketAppender - extends SSLServerSocketAppenderBase { +public class SSLServerSocketAppender extends SSLServerSocketAppenderBase { - private static final PreSerializationTransformer pst = - new AccessEventPreSerializationTransformer(); + private static final PreSerializationTransformer pst = new AccessEventPreSerializationTransformer(); - @Override - protected void postProcessEvent(IAccessEvent event) { - event.prepareForDeferredProcessing(); - } + @Override + protected void postProcessEvent(IAccessEvent event) { + event.prepareForDeferredProcessing(); + } - @Override - protected PreSerializationTransformer getPST() { - return pst; - } + @Override + protected PreSerializationTransformer getPST() { + return pst; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/net/server/ServerSocketAppender.java b/logback-access/src/main/java/ch/qos/logback/access/net/server/ServerSocketAppender.java index f992c75ed9cd65afacc5c0e099a887effd77ffa1..24c021d03cc912624ada8f13176bef5facf9ee86 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/net/server/ServerSocketAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/net/server/ServerSocketAppender.java @@ -25,20 +25,18 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * * @author Carl Harris */ -public class ServerSocketAppender - extends AbstractServerSocketAppender { +public class ServerSocketAppender extends AbstractServerSocketAppender { - private static final PreSerializationTransformer pst = - new AccessEventPreSerializationTransformer(); + private static final PreSerializationTransformer pst = new AccessEventPreSerializationTransformer(); - @Override - protected void postProcessEvent(IAccessEvent event) { - event.prepareForDeferredProcessing(); - } + @Override + protected void postProcessEvent(IAccessEvent event) { + event.prepareForDeferredProcessing(); + } - @Override - protected PreSerializationTransformer getPST() { - return pst; - } + @Override + protected PreSerializationTransformer getPST() { + return pst; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/AccessConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/AccessConverter.java index 4ca5c2d6443d0d525c12b22488655d8615977b11..fa5cb645d08e57297d867fadef61708702d07419 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/AccessConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/AccessConverter.java @@ -20,57 +20,56 @@ import ch.qos.logback.core.spi.ContextAware; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.status.Status; - abstract public class AccessConverter extends DynamicConverter implements ContextAware { - public final static char SPACE_CHAR = ' '; - public final static char QUESTION_CHAR = '?'; - - ContextAwareBase cab = new ContextAwareBase(); + public final static char SPACE_CHAR = ' '; + public final static char QUESTION_CHAR = '?'; + + ContextAwareBase cab = new ContextAwareBase(); + + @Override + public void setContext(Context context) { + cab.setContext(context); + } - @Override - public void setContext(Context context) { - cab.setContext(context); - } + @Override + public Context getContext() { + return cab.getContext(); + } - @Override - public Context getContext() { - return cab.getContext(); - } + @Override + public void addStatus(Status status) { + cab.addStatus(status); + } - @Override - public void addStatus(Status status) { - cab.addStatus(status); - } + @Override + public void addInfo(String msg) { + cab.addInfo(msg); + } - @Override - public void addInfo(String msg) { - cab.addInfo(msg); - } + @Override + public void addInfo(String msg, Throwable ex) { + cab.addInfo(msg, ex); + } - @Override - public void addInfo(String msg, Throwable ex) { - cab.addInfo(msg, ex); - } + @Override + public void addWarn(String msg) { + cab.addWarn(msg); + } - @Override - public void addWarn(String msg) { - cab.addWarn(msg); - } + @Override + public void addWarn(String msg, Throwable ex) { + cab.addWarn(msg, ex); + } - @Override - public void addWarn(String msg, Throwable ex) { - cab.addWarn(msg, ex); - } + @Override + public void addError(String msg) { + cab.addError(msg); + } - @Override - public void addError(String msg) { - cab.addError(msg); - } + @Override + public void addError(String msg, Throwable ex) { + cab.addError(msg, ex); + } - @Override - public void addError(String msg, Throwable ex) { - cab.addError(msg, ex); - } - } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/ContentLengthConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/ContentLengthConverter.java index ce4d38a8fa138e0e236dd546f03e9c5fbed565b4..c040513db2c0564610ac398390eaafbb5f782374 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/ContentLengthConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/ContentLengthConverter.java @@ -17,14 +17,14 @@ import ch.qos.logback.access.spi.IAccessEvent; public class ContentLengthConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - long len = accessEvent.getContentLength(); - if(len == IAccessEvent.SENTINEL) { - return IAccessEvent.NA; - } else { - return Long.toString(len); - } - } + @Override + public String convert(IAccessEvent accessEvent) { + long len = accessEvent.getContentLength(); + if (len == IAccessEvent.SENTINEL) { + return IAccessEvent.NA; + } else { + return Long.toString(len); + } + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/DateConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/DateConverter.java index 6a3d9d3b3e6468a19642b1cb84fdf977ab465eb4..def1d863594f5cca872297f2ebbda25a9a94e7d6 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/DateConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/DateConverter.java @@ -20,45 +20,43 @@ import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.util.CachingDateFormatter; - public class DateConverter extends AccessConverter { + CachingDateFormatter cachingDateFormatter = null; - CachingDateFormatter cachingDateFormatter = null; + @Override + public void start() { - @Override - public void start() { - - String datePattern = getFirstOption(); - if(datePattern == null) { - datePattern = CoreConstants.CLF_DATE_PATTERN; - } - - if (datePattern.equals(CoreConstants.ISO8601_STR)) { - datePattern = CoreConstants.ISO8601_PATTERN; - } - - try { - cachingDateFormatter = new CachingDateFormatter(datePattern); - //maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern); - } catch (IllegalArgumentException e) { - addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e); - addWarn("Defaulting to " + CoreConstants.CLF_DATE_PATTERN); - cachingDateFormatter = new CachingDateFormatter(CoreConstants.CLF_DATE_PATTERN); - } - - List optionList = getOptionList(); - - // if the option list contains a TZ option, then set it. - if (optionList != null && optionList.size() > 1) { - TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1)); - cachingDateFormatter.setTimeZone(tz); + String datePattern = getFirstOption(); + if (datePattern == null) { + datePattern = CoreConstants.CLF_DATE_PATTERN; + } + + if (datePattern.equals(CoreConstants.ISO8601_STR)) { + datePattern = CoreConstants.ISO8601_PATTERN; + } + + try { + cachingDateFormatter = new CachingDateFormatter(datePattern); + // maximumCacheValidity = CachedDateFormat.getMaximumCacheValidity(pattern); + } catch (IllegalArgumentException e) { + addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e); + addWarn("Defaulting to " + CoreConstants.CLF_DATE_PATTERN); + cachingDateFormatter = new CachingDateFormatter(CoreConstants.CLF_DATE_PATTERN); + } + + List optionList = getOptionList(); + + // if the option list contains a TZ option, then set it. + if (optionList != null && optionList.size() > 1) { + TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1)); + cachingDateFormatter.setTimeZone(tz); + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - long timestamp = accessEvent.getTimeStamp(); - return cachingDateFormatter.format(timestamp); - } + @Override + public String convert(IAccessEvent accessEvent) { + long timestamp = accessEvent.getTimeStamp(); + return cachingDateFormatter.format(timestamp); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/ElapsedTimeConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/ElapsedTimeConverter.java index 5ea3f6ed739fce807b5c34e107d5bc7742d99152..381d757e76db9880120678eb2bff9899b73bb6bf 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/ElapsedTimeConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/ElapsedTimeConverter.java @@ -17,9 +17,9 @@ import ch.qos.logback.access.spi.IAccessEvent; public class ElapsedTimeConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return Long.toString(accessEvent.getElapsedTime()); - } + @Override + public String convert(IAccessEvent accessEvent) { + return Long.toString(accessEvent.getElapsedTime()); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/EnsureLineSeparation.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/EnsureLineSeparation.java index 9fd694e8df3647a6dbc039d17e442b853dd33e81..2e415d16e5d1a534e257e85e3db741c3ea515f48 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/EnsureLineSeparation.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/EnsureLineSeparation.java @@ -21,20 +21,20 @@ import ch.qos.logback.core.pattern.PostCompileProcessor; public class EnsureLineSeparation implements PostCompileProcessor { - /** - * Add a line separator converter so that access event appears on a separate - * line. - */ + /** + * Add a line separator converter so that access event appears on a separate + * line. + */ @Override - public void process(Context context, Converter head) { - if(head == null) - throw new IllegalArgumentException("Empty converter chain"); + public void process(Context context, Converter head) { + if (head == null) + throw new IllegalArgumentException("Empty converter chain"); - // if head != null, then tail != null as well - Converter tail = ConverterUtil.findTail(head); - Converter newLineConverter = new LineSeparatorConverter(); - if (!(tail instanceof LineSeparatorConverter)) { - tail.setNext(newLineConverter); + // if head != null, then tail != null as well + Converter tail = ConverterUtil.findTail(head); + Converter newLineConverter = new LineSeparatorConverter(); + if (!(tail instanceof LineSeparatorConverter)) { + tail.setNext(newLineConverter); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/FullRequestConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/FullRequestConverter.java index 6f64db4c5678b7b785184b029330e6f140e146f3..5bbdd0c5a77c50ee5d0dac975d296f62e1c6c08e 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/FullRequestConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/FullRequestConverter.java @@ -29,23 +29,23 @@ import ch.qos.logback.core.CoreConstants; */ public class FullRequestConverter extends AccessConverter { - @Override - public String convert(IAccessEvent ae) { - StringBuilder buf = new StringBuilder(); - buf.append(ae.getRequestURL()); - buf.append(CoreConstants.LINE_SEPARATOR); - - Enumeration headerNames = ae.getRequestHeaderNames(); - while(headerNames.hasMoreElements()) { - String name = (String) headerNames.nextElement(); - buf.append(name); - buf.append(": "); - buf.append(ae.getRequestHeader(name)); - buf.append(CoreConstants.LINE_SEPARATOR); + @Override + public String convert(IAccessEvent ae) { + StringBuilder buf = new StringBuilder(); + buf.append(ae.getRequestURL()); + buf.append(CoreConstants.LINE_SEPARATOR); + + Enumeration headerNames = ae.getRequestHeaderNames(); + while (headerNames.hasMoreElements()) { + String name = (String) headerNames.nextElement(); + buf.append(name); + buf.append(": "); + buf.append(ae.getRequestHeader(name)); + buf.append(CoreConstants.LINE_SEPARATOR); + } + buf.append(CoreConstants.LINE_SEPARATOR); + buf.append(ae.getRequestContent()); + return buf.toString(); } - buf.append(CoreConstants.LINE_SEPARATOR); - buf.append(ae.getRequestContent()); - return buf.toString(); - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/FullResponseConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/FullResponseConverter.java index 57e8516392cc2901bbf71e117deb9070e18d2172..e0366cb118bebcfbca0acfafab382206616149da 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/FullResponseConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/FullResponseConverter.java @@ -20,72 +20,112 @@ import ch.qos.logback.core.CoreConstants; public class FullResponseConverter extends AccessConverter { - @Override - public String convert(IAccessEvent ae) { - StringBuilder buf = new StringBuilder(); - - buf.append("HTTP/1.1 "); - int statusCode = ae.getStatusCode(); - buf.append(statusCode); - buf.append(" "); - buf.append(getStatusCodeDescription(statusCode)); - buf.append(CoreConstants.LINE_SEPARATOR); - - List hnList = ae.getResponseHeaderNameList(); - for(String headerName: hnList) { - buf.append(headerName); - buf.append(": "); - buf.append(ae.getResponseHeader(headerName)); - buf.append(CoreConstants.LINE_SEPARATOR); + @Override + public String convert(IAccessEvent ae) { + StringBuilder buf = new StringBuilder(); + + buf.append("HTTP/1.1 "); + int statusCode = ae.getStatusCode(); + buf.append(statusCode); + buf.append(" "); + buf.append(getStatusCodeDescription(statusCode)); + buf.append(CoreConstants.LINE_SEPARATOR); + + List hnList = ae.getResponseHeaderNameList(); + for (String headerName : hnList) { + buf.append(headerName); + buf.append(": "); + buf.append(ae.getResponseHeader(headerName)); + buf.append(CoreConstants.LINE_SEPARATOR); + } + buf.append(CoreConstants.LINE_SEPARATOR); + buf.append(ae.getResponseContent()); + buf.append(CoreConstants.LINE_SEPARATOR); + return buf.toString(); } - buf.append(CoreConstants.LINE_SEPARATOR); - buf.append(ae.getResponseContent()); - buf.append(CoreConstants.LINE_SEPARATOR); - return buf.toString(); - } - static String getStatusCodeDescription(int sc) { - switch(sc) { - case 200: return "OK"; - case 201: return "Created"; - case 202: return "Accepted"; - case 203: return "Non-Authoritative Information"; - case 204: return "No Content"; - case 205: return "Reset Content"; - case 206: return "Partial Content"; - case 300: return "Multiple Choices"; - case 301: return "Moved Permanently"; - case 302: return "Found"; - case 303: return "See Other"; - case 304: return "Not Modified"; - case 305: return "Use Proxy"; - case 306: return "(Unused)"; - case 307: return "Temporary Redirect"; - case 400: return "Bad Request"; - case 401: return "Unauthorized"; - case 402: return "Payment Required"; - case 403: return "Forbidden"; - case 404: return "Not Found"; - case 405: return "Method Not Allowed"; - case 406: return "Not Acceptable"; - case 407: return "Proxy Authentication Required"; - case 408: return "Request Timeout"; - case 409: return "Conflict"; - case 410: return "Gone"; - case 411: return "Length Required"; - case 412: return "Precondition Failed"; - case 413: return "Request Entity Too Large"; - case 414: return "Request-URI Too Long"; - case 415: return "Unsupported Media Type"; - case 416: return "Requested Range Not Satisfiable"; - case 417: return "Expectation Failed"; - case 500: return "Internal Server Error"; - case 501: return "Not Implemented"; - case 502: return "Bad Gateway"; - case 503: return "Service Unavailable"; - case 504: return "Gateway Timeout"; - case 505: return "HTTP Version Not Supported"; - default: return "NA"; + static String getStatusCodeDescription(int sc) { + switch (sc) { + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 203: + return "Non-Authoritative Information"; + case 204: + return "No Content"; + case 205: + return "Reset Content"; + case 206: + return "Partial Content"; + case 300: + return "Multiple Choices"; + case 301: + return "Moved Permanently"; + case 302: + return "Found"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 305: + return "Use Proxy"; + case 306: + return "(Unused)"; + case 307: + return "Temporary Redirect"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 402: + return "Payment Required"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 407: + return "Proxy Authentication Required"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 411: + return "Length Required"; + case 412: + return "Precondition Failed"; + case 413: + return "Request Entity Too Large"; + case 414: + return "Request-URI Too Long"; + case 415: + return "Unsupported Media Type"; + case 416: + return "Requested Range Not Satisfiable"; + case 417: + return "Expectation Failed"; + case 500: + return "Internal Server Error"; + case 501: + return "Not Implemented"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + case 505: + return "HTTP Version Not Supported"; + default: + return "NA"; + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/LineSeparatorConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/LineSeparatorConverter.java index 3bcd87413ced21ab621c1d2d80a8b04be65b7e87..1590a2ab6f95928ce55231e8eaf73c6a27400d22 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/LineSeparatorConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/LineSeparatorConverter.java @@ -16,11 +16,10 @@ package ch.qos.logback.access.pattern; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.CoreConstants; - public class LineSeparatorConverter extends AccessConverter { - @Override - public String convert(IAccessEvent event) { - return CoreConstants.LINE_SEPARATOR; - } + @Override + public String convert(IAccessEvent event) { + return CoreConstants.LINE_SEPARATOR; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalIPAddressConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalIPAddressConverter.java index 917720d4281f351479e4f1d8de1d0efe8457f564..21f576acb33e5d4718db227d1a01a154bceeeb84 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalIPAddressConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalIPAddressConverter.java @@ -20,19 +20,19 @@ import ch.qos.logback.access.spi.IAccessEvent; public class LocalIPAddressConverter extends AccessConverter { - String localIPAddressStr; + String localIPAddressStr; - public LocalIPAddressConverter() { - try { - localIPAddressStr = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException uhe) { - localIPAddressStr = "127.0.0.1"; + public LocalIPAddressConverter() { + try { + localIPAddressStr = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException uhe) { + localIPAddressStr = "127.0.0.1"; + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - return localIPAddressStr; - } + @Override + public String convert(IAccessEvent accessEvent) { + return localIPAddressStr; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalPortConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalPortConverter.java index 08f662691c49f9c03c77bb4b096f1c2ab6c502f6..1b0d5666902ed94da005a4f39785c8b834a0a21f 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalPortConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/LocalPortConverter.java @@ -17,8 +17,8 @@ import ch.qos.logback.access.spi.IAccessEvent; public class LocalPortConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return Integer.toString(accessEvent.getLocalPort()); - } + @Override + public String convert(IAccessEvent accessEvent) { + return Integer.toString(accessEvent.getLocalPort()); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/NAConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/NAConverter.java index 2ae8d55848664fc47051c02315c65a3ba2d2af57..e2172186ee3d1a40cb1a5afba53f533159081df0 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/NAConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/NAConverter.java @@ -23,9 +23,9 @@ import ch.qos.logback.access.spi.IAccessEvent; */ public class NAConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return IAccessEvent.NA; - } + @Override + public String convert(IAccessEvent accessEvent) { + return IAccessEvent.NA; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteHostConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteHostConverter.java index 355aed130334cc4a60d077bb16b02e04f26c5920..bad1c898cb93d12aea94330dd8e662912632ddbb 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteHostConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteHostConverter.java @@ -17,9 +17,9 @@ import ch.qos.logback.access.spi.IAccessEvent; public class RemoteHostConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getRemoteHost(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getRemoteHost(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteIPAddressConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteIPAddressConverter.java index 96edf80228c0e067e96a0bc225fd032b3e904a0a..7f917025213de4ae1df8416b064d0f479af668bf 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteIPAddressConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteIPAddressConverter.java @@ -17,9 +17,9 @@ import ch.qos.logback.access.spi.IAccessEvent; public class RemoteIPAddressConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getRemoteAddr(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getRemoteAddr(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteUserConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteUserConverter.java index 251d806327357fd23751f5d29b35080de9c49ec5..7b0864a9e9a1f4e07977833ca278a724d5eb5b94 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteUserConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RemoteUserConverter.java @@ -17,15 +17,15 @@ import ch.qos.logback.access.spi.IAccessEvent; public class RemoteUserConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - - String user = accessEvent.getRemoteUser(); - if(user == null) { - return IAccessEvent.NA; - } else { - return user; + @Override + public String convert(IAccessEvent accessEvent) { + + String user = accessEvent.getRemoteUser(); + if (user == null) { + return IAccessEvent.NA; + } else { + return user; + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestAttributeConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestAttributeConverter.java index 9063bfefa5b27f474d96e5f81d464de0564279e6..153797511e486fa6b3b89dac41f383de57558f13 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestAttributeConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestAttributeConverter.java @@ -16,28 +16,27 @@ package ch.qos.logback.access.pattern; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.util.OptionHelper; - public class RequestAttributeConverter extends AccessConverter { - String key; + String key; - @Override - public void start() { - key = getFirstOption(); - if (OptionHelper.isEmpty(key)) { - addWarn("Missing key for the request attribute"); - } else { - super.start(); + @Override + public void start() { + key = getFirstOption(); + if (OptionHelper.isEmpty(key)) { + addWarn("Missing key for the request attribute"); + } else { + super.start(); + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - if (!isStarted()) { - return "INACTIVE_REQUEST_ATTRIB_CONV"; - } + @Override + public String convert(IAccessEvent accessEvent) { + if (!isStarted()) { + return "INACTIVE_REQUEST_ATTRIB_CONV"; + } - return accessEvent.getAttribute(key); - } + return accessEvent.getAttribute(key); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestContentConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestContentConverter.java index 2600f2af53a06cc662e4060dba1f8ba5dd39a499..67e409fb4659e873e02381ceadc8918dc8af723c 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestContentConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestContentConverter.java @@ -26,9 +26,9 @@ import ch.qos.logback.access.spi.IAccessEvent; */ public class RequestContentConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getRequestContent(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getRequestContent(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestCookieConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestCookieConverter.java index cd457738aae6ca63a01080af2e068fe3dc579107..0d2f189e8cd62dfb9823a942a905dcc80e2ad9a7 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestCookieConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestCookieConverter.java @@ -16,27 +16,26 @@ package ch.qos.logback.access.pattern; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.util.OptionHelper; - public class RequestCookieConverter extends AccessConverter { - String key; + String key; - @Override - public void start() { - key = getFirstOption(); - if (OptionHelper.isEmpty(key)) { - addWarn("Missing key for the requested header"); - } else { - super.start(); + @Override + public void start() { + key = getFirstOption(); + if (OptionHelper.isEmpty(key)) { + addWarn("Missing key for the requested header"); + } else { + super.start(); + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - if (!isStarted()) { - return "INACTIVE_COOKIE_CONVERTER"; - } + @Override + public String convert(IAccessEvent accessEvent) { + if (!isStarted()) { + return "INACTIVE_COOKIE_CONVERTER"; + } - return accessEvent.getCookie(key); - } + return accessEvent.getCookie(key); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestHeaderConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestHeaderConverter.java index 93fb4f85d016c6a10849cff77bcf0df1c87e8cbc..c3e22f1890664c494ea899341f1c7ab35c79224e 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestHeaderConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestHeaderConverter.java @@ -16,32 +16,31 @@ package ch.qos.logback.access.pattern; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.util.OptionHelper; - public class RequestHeaderConverter extends AccessConverter { - String key; - - @Override - public void start() { - key = getFirstOption(); - if (OptionHelper.isEmpty(key)) { - addWarn("Missing key for the requested header. Defaulting to all keys."); - key = null; - } - super.start(); - } + String key; - @Override - public String convert(IAccessEvent accessEvent) { - if(!isStarted()) { - return "INACTIVE_HEADER_CONV"; + @Override + public void start() { + key = getFirstOption(); + if (OptionHelper.isEmpty(key)) { + addWarn("Missing key for the requested header. Defaulting to all keys."); + key = null; + } + super.start(); } - - if(key != null) { - return accessEvent.getRequestHeader(key); - } else { - return accessEvent.getRequestHeaderMap().toString(); + + @Override + public String convert(IAccessEvent accessEvent) { + if (!isStarted()) { + return "INACTIVE_HEADER_CONV"; + } + + if (key != null) { + return accessEvent.getRequestHeader(key); + } else { + return accessEvent.getRequestHeaderMap().toString(); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestMethodConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestMethodConverter.java index dbbd24693ec5a5d60a430a6b462b5626589b8b62..51b9a82b0362ee7f9a188bd383a10596135db4c1 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestMethodConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestMethodConverter.java @@ -17,8 +17,8 @@ import ch.qos.logback.access.spi.IAccessEvent; public class RequestMethodConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getMethod(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getMethod(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestParameterConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestParameterConverter.java index 690632405a933ef91f0a1ff951033e4d787138ec..0ae0e430ebb242ac11c7b6f136ed97ca110c89a3 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestParameterConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestParameterConverter.java @@ -20,32 +20,32 @@ import ch.qos.logback.core.util.OptionHelper; public class RequestParameterConverter extends AccessConverter { - String key; - - @Override - public void start() { - key = getFirstOption(); - if (OptionHelper.isEmpty(key)) { - addWarn("Missing key for the request parameter"); - } else { - super.start(); + String key; + + @Override + public void start() { + key = getFirstOption(); + if (OptionHelper.isEmpty(key)) { + addWarn("Missing key for the request parameter"); + } else { + super.start(); + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - if (!isStarted()) { - return "INACTIVE_REQUEST_PARAM_CONV"; + @Override + public String convert(IAccessEvent accessEvent) { + if (!isStarted()) { + return "INACTIVE_REQUEST_PARAM_CONV"; + } + + String[] paramArray = accessEvent.getRequestParameter(key); + if (paramArray.length == 1) { + return paramArray[0]; + } else { + // for an array string {"a", "b"} named 'sa', Array.toString(sa) returns the string + // "[a, b]". + return Arrays.toString(paramArray); + } } - String[] paramArray = accessEvent.getRequestParameter(key); - if (paramArray.length == 1) { - return paramArray[0]; - } else { - // for an array string {"a", "b"} named 'sa', Array.toString(sa) returns the string - // "[a, b]". - return Arrays.toString(paramArray); - } - } - } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestProtocolConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestProtocolConverter.java index 2dc64b6c7cfa4b47e8fe4b2241316bc2aea0f45d..a20f7878b3b40beb82bdf2b17d2d211c5d7d7718 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestProtocolConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestProtocolConverter.java @@ -17,8 +17,8 @@ import ch.qos.logback.access.spi.IAccessEvent; public class RequestProtocolConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getProtocol(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getProtocol(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURIConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURIConverter.java index b597ddb8bf467a2788461a42813e7eeb453472d8..7f8cebce05cc46e42aa86beda94f5711e5b3ae9d 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURIConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURIConverter.java @@ -22,9 +22,9 @@ import ch.qos.logback.access.spi.IAccessEvent; */ public class RequestURIConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getRequestURI(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getRequestURI(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURLConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURLConverter.java index a812a66c9f451b429426ad7de3ccc5d476cfaaa0..fd50d7d4a983b51079f945045ef9f7d1094f1844 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURLConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/RequestURLConverter.java @@ -22,8 +22,8 @@ import ch.qos.logback.access.spi.IAccessEvent; */ public class RequestURLConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getRequestURL(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getRequestURL(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseContentConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseContentConverter.java index aa348eb036b771e8bb6c38c92f149eb74a0b40bc..ac5201b860182a84996da123de596b53874ed0ef 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseContentConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseContentConverter.java @@ -26,9 +26,9 @@ import ch.qos.logback.access.spi.IAccessEvent; */ public class ResponseContentConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getResponseContent(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getResponseContent(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseHeaderConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseHeaderConverter.java index a332dffa7ef3b1664a8284f8f7c73821beac909b..3838db30bb995089a167bf3c85cce70e47db11f4 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseHeaderConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/ResponseHeaderConverter.java @@ -16,38 +16,37 @@ package ch.qos.logback.access.pattern; import ch.qos.logback.access.spi.IAccessEvent; import ch.qos.logback.core.util.OptionHelper; - public class ResponseHeaderConverter extends AccessConverter { - String key; + String key; - @Override - public void start() { - key = getFirstOption(); - if (OptionHelper.isEmpty(key)) { - addWarn("Missing key for the response header"); - } else { - super.start(); + @Override + public void start() { + key = getFirstOption(); + if (OptionHelper.isEmpty(key)) { + addWarn("Missing key for the response header"); + } else { + super.start(); + } } - } - @Override - public String convert(IAccessEvent accessEvent) { - if(!isStarted()) { - return "INACTIVE_REPONSE_HEADER_CONV"; + @Override + public String convert(IAccessEvent accessEvent) { + if (!isStarted()) { + return "INACTIVE_REPONSE_HEADER_CONV"; + } + + return accessEvent.getResponseHeader(key); + // return null; + + // HttpServletResponse response = accessEvent.getHttpResponse(); + // + // Object value = null; // = response.getHeader(key); + // if (value == null) { + // return AccessConverter.NA; + // } else { + // return value.toString(); + // } } - - return accessEvent.getResponseHeader(key); - //return null; - -// HttpServletResponse response = accessEvent.getHttpResponse(); -// -// Object value = null; // = response.getHeader(key); -// if (value == null) { -// return AccessConverter.NA; -// } else { -// return value.toString(); -// } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/ServerNameConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/ServerNameConverter.java index 17c6b871bd4595a3e296fb08a20af3e84f36003a..086e8179a6c549f0894db5a8bd2e8be517a609b7 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/ServerNameConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/ServerNameConverter.java @@ -17,8 +17,8 @@ import ch.qos.logback.access.spi.IAccessEvent; public class ServerNameConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return accessEvent.getServerName(); - } + @Override + public String convert(IAccessEvent accessEvent) { + return accessEvent.getServerName(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/pattern/StatusCodeConverter.java b/logback-access/src/main/java/ch/qos/logback/access/pattern/StatusCodeConverter.java index 98fc2cba1af885355e348172ccac6ed8def5394a..d19807415dd5953808d12c2af1fc4bd263e0cfd5 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/pattern/StatusCodeConverter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/pattern/StatusCodeConverter.java @@ -17,9 +17,9 @@ import ch.qos.logback.access.spi.IAccessEvent; public class StatusCodeConverter extends AccessConverter { - @Override - public String convert(IAccessEvent accessEvent) { - return Integer.toString(accessEvent.getStatusCode()); - } + @Override + public String convert(IAccessEvent accessEvent) { + return Integer.toString(accessEvent.getStatusCode()); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeFilter.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeFilter.java index a6f20bb2a72e42b23044c4f5fa2cf9b4ecb47b18..eed0968579c79ef9c7973ea2363a23fd4dad1180 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeFilter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeFilter.java @@ -32,7 +32,6 @@ import static ch.qos.logback.access.AccessConstants.LB_OUTPUT_BUFFER; import static ch.qos.logback.access.AccessConstants.TEE_FILTER_INCLUDES_PARAM; import static ch.qos.logback.access.AccessConstants.TEE_FILTER_EXCLUDES_PARAM; - public class TeeFilter implements Filter { boolean active; @@ -43,25 +42,21 @@ public class TeeFilter implements Filter { } @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filterChain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (active && request instanceof HttpServletRequest) { try { - TeeHttpServletRequest teeRequest = new TeeHttpServletRequest( - (HttpServletRequest) request); - TeeHttpServletResponse teeResponse = new TeeHttpServletResponse( - (HttpServletResponse) response); + TeeHttpServletRequest teeRequest = new TeeHttpServletRequest((HttpServletRequest) request); + TeeHttpServletResponse teeResponse = new TeeHttpServletResponse((HttpServletResponse) response); - //System.out.println("BEFORE TeeFilter. filterChain.doFilter()"); + // System.out.println("BEFORE TeeFilter. filterChain.doFilter()"); filterChain.doFilter(teeRequest, teeResponse); - //System.out.println("AFTER TeeFilter. filterChain.doFilter()"); + // System.out.println("AFTER TeeFilter. filterChain.doFilter()"); teeResponse.finish(); // let the output contents be available for later use by // logback-access-logging - teeRequest.setAttribute(LB_OUTPUT_BUFFER, teeResponse - .getOutputBuffer()); + teeRequest.setAttribute(LB_OUTPUT_BUFFER, teeResponse.getOutputBuffer()); } catch (IOException e) { e.printStackTrace(); throw e; @@ -108,7 +103,6 @@ public class TeeFilter implements Filter { return nameList; } - static String getLocalhostName() { String hostname = "127.0.0.1"; @@ -128,14 +122,15 @@ public class TeeFilter implements Filter { return inIncludesList && (!inExcludesList); } - static boolean mathesIncludesList(String hostname, List includeList) { - if (includeList.isEmpty()) return true; + if (includeList.isEmpty()) + return true; return includeList.contains(hostname); } static boolean mathesExcludesList(String hostname, List excludesList) { - if (excludesList.isEmpty()) return false; + if (excludesList.isEmpty()) + return false; return excludesList.contains(hostname); } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletRequest.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletRequest.java index 7e78afa9192a8e7347701e987ed591145d79dea3..8ab9c6dad1ca48dcddc6ef5ea25ae6e7ed7ec35f 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletRequest.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletRequest.java @@ -22,6 +22,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import static ch.qos.logback.access.AccessConstants.LB_INPUT_BUFFER; + /** * As the "tee" program on Unix, duplicate the request's input stream. * @@ -29,54 +30,54 @@ import static ch.qos.logback.access.AccessConstants.LB_INPUT_BUFFER; */ class TeeHttpServletRequest extends HttpServletRequestWrapper { - private TeeServletInputStream inStream; - private BufferedReader reader; - boolean postedParametersMode = false; + private TeeServletInputStream inStream; + private BufferedReader reader; + boolean postedParametersMode = false; - TeeHttpServletRequest(HttpServletRequest request) { - super(request); - // we can't access the input stream and access the request parameters - // at the same time - if (Util.isFormUrlEncoded(request)) { - postedParametersMode = true; - } else { - inStream = new TeeServletInputStream(request); - // add the contents of the input buffer as an attribute of the request - request.setAttribute(LB_INPUT_BUFFER, inStream.getInputBuffer()); - reader = new BufferedReader(new InputStreamReader(inStream)); - } + TeeHttpServletRequest(HttpServletRequest request) { + super(request); + // we can't access the input stream and access the request parameters + // at the same time + if (Util.isFormUrlEncoded(request)) { + postedParametersMode = true; + } else { + inStream = new TeeServletInputStream(request); + // add the contents of the input buffer as an attribute of the request + request.setAttribute(LB_INPUT_BUFFER, inStream.getInputBuffer()); + reader = new BufferedReader(new InputStreamReader(inStream)); + } - } + } - byte[] getInputBuffer() { - if (postedParametersMode) { - throw new IllegalStateException("Call disallowed in postedParametersMode"); + byte[] getInputBuffer() { + if (postedParametersMode) { + throw new IllegalStateException("Call disallowed in postedParametersMode"); + } + return inStream.getInputBuffer(); } - return inStream.getInputBuffer(); - } - @Override - public ServletInputStream getInputStream() throws IOException { - if (!postedParametersMode) { - return inStream; - } else { - return super.getInputStream(); + @Override + public ServletInputStream getInputStream() throws IOException { + if (!postedParametersMode) { + return inStream; + } else { + return super.getInputStream(); + } } - } - // + // - @Override - public BufferedReader getReader() throws IOException { - if (!postedParametersMode) { - return reader; - } else { - return super.getReader(); + @Override + public BufferedReader getReader() throws IOException { + if (!postedParametersMode) { + return reader; + } else { + return super.getReader(); + } } - } - public boolean isPostedParametersMode() { - return postedParametersMode; - } + public boolean isPostedParametersMode() { + return postedParametersMode; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletResponse.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletResponse.java index 91cc2708771847ec1a8c6469cb846c3c4c88ca49..6dfd6dd2dd71fada58e6b59c4c1bab960a9e978f 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletResponse.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeHttpServletResponse.java @@ -23,52 +23,52 @@ import javax.servlet.http.HttpServletResponseWrapper; public class TeeHttpServletResponse extends HttpServletResponseWrapper { - TeeServletOutputStream teeServletOutputStream; - PrintWriter teeWriter; + TeeServletOutputStream teeServletOutputStream; + PrintWriter teeWriter; - public TeeHttpServletResponse(HttpServletResponse httpServletResponse) { - super(httpServletResponse); - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - if (teeServletOutputStream == null) { - teeServletOutputStream = new TeeServletOutputStream(this.getResponse()); + public TeeHttpServletResponse(HttpServletResponse httpServletResponse) { + super(httpServletResponse); } - return teeServletOutputStream; - } - @Override - public PrintWriter getWriter() throws IOException { - if (this.teeWriter == null) { - this.teeWriter = new PrintWriter(new OutputStreamWriter(getOutputStream(), this.getResponse().getCharacterEncoding()), true); + @Override + public ServletOutputStream getOutputStream() throws IOException { + if (teeServletOutputStream == null) { + teeServletOutputStream = new TeeServletOutputStream(this.getResponse()); + } + return teeServletOutputStream; } - return this.teeWriter; - } - @Override - public void flushBuffer() { - if (this.teeWriter != null) { - this.teeWriter.flush(); + @Override + public PrintWriter getWriter() throws IOException { + if (this.teeWriter == null) { + this.teeWriter = new PrintWriter(new OutputStreamWriter(getOutputStream(), this.getResponse().getCharacterEncoding()), true); + } + return this.teeWriter; } - } - byte[] getOutputBuffer() { - // teeServletOutputStream can be null if the getOutputStream method is never - // called. - if (teeServletOutputStream != null) { - return teeServletOutputStream.getOutputStreamAsByteArray(); - } else { - return null; + @Override + public void flushBuffer() { + if (this.teeWriter != null) { + this.teeWriter.flush(); + } } - } - void finish() throws IOException { - if (this.teeWriter != null) { - this.teeWriter.close(); + byte[] getOutputBuffer() { + // teeServletOutputStream can be null if the getOutputStream method is never + // called. + if (teeServletOutputStream != null) { + return teeServletOutputStream.getOutputStreamAsByteArray(); + } else { + return null; + } } - if (this.teeServletOutputStream != null) { - this.teeServletOutputStream.close(); + + void finish() throws IOException { + if (this.teeWriter != null) { + this.teeWriter.close(); + } + if (this.teeServletOutputStream != null) { + this.teeServletOutputStream.close(); + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletInputStream.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletInputStream.java index 1a46f3e16fb99cdfb49d3f00887ff16d769f2324..b33f91a4c52006e185566cfb25ed9965263fa4a8 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletInputStream.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletInputStream.java @@ -23,53 +23,52 @@ import javax.servlet.http.HttpServletRequest; class TeeServletInputStream extends ServletInputStream { - InputStream in; - byte[] inputBuffer; + InputStream in; + byte[] inputBuffer; - TeeServletInputStream(HttpServletRequest request) { - duplicateInputStream(request); - } - - @Override - public int read() throws IOException { - return in.read(); - } + TeeServletInputStream(HttpServletRequest request) { + duplicateInputStream(request); + } - private void duplicateInputStream(HttpServletRequest request) { - ServletInputStream originalSIS = null; - try { - originalSIS = request.getInputStream(); - inputBuffer = consumeBufferAndReturnAsByteArray(originalSIS); - this.in = new ByteArrayInputStream(inputBuffer); - } catch (IOException e) { - e.printStackTrace(); - } finally { - closeStrean(originalSIS); + @Override + public int read() throws IOException { + return in.read(); } - } - byte[] consumeBufferAndReturnAsByteArray(InputStream is) throws IOException { - int len = 1024; - byte[] temp = new byte[len]; - int c = -1; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while ((c = is.read(temp, 0, len)) != -1) { - baos.write(temp, 0, c); + private void duplicateInputStream(HttpServletRequest request) { + ServletInputStream originalSIS = null; + try { + originalSIS = request.getInputStream(); + inputBuffer = consumeBufferAndReturnAsByteArray(originalSIS); + this.in = new ByteArrayInputStream(inputBuffer); + } catch (IOException e) { + e.printStackTrace(); + } finally { + closeStrean(originalSIS); + } } - return baos.toByteArray(); - } + byte[] consumeBufferAndReturnAsByteArray(InputStream is) throws IOException { + int len = 1024; + byte[] temp = new byte[len]; + int c = -1; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while ((c = is.read(temp, 0, len)) != -1) { + baos.write(temp, 0, c); + } + return baos.toByteArray(); + } - void closeStrean(ServletInputStream is) { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - } + void closeStrean(ServletInputStream is) { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + } + } } - } - byte[] getInputBuffer() { - return inputBuffer; - } + byte[] getInputBuffer() { + return inputBuffer; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletOutputStream.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletOutputStream.java index 4fbd4e9bd8e2299d0ccf9f7f4ebb039ee742bc8c..05502b9fc3839d7d917b4315adb9058fa7915620 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletOutputStream.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/TeeServletOutputStream.java @@ -21,68 +21,65 @@ import javax.servlet.ServletResponse; public class TeeServletOutputStream extends ServletOutputStream { - final ServletOutputStream underlyingStream; - final ByteArrayOutputStream baosCopy; + final ServletOutputStream underlyingStream; + final ByteArrayOutputStream baosCopy; - TeeServletOutputStream(ServletResponse httpServletResponse) - throws IOException { - // System.out.println("TeeServletOutputStream.constructor() called"); - this.underlyingStream = httpServletResponse.getOutputStream(); - baosCopy = new ByteArrayOutputStream(); - } - - byte[] getOutputStreamAsByteArray() { - return baosCopy.toByteArray(); - } + TeeServletOutputStream(ServletResponse httpServletResponse) throws IOException { + // System.out.println("TeeServletOutputStream.constructor() called"); + this.underlyingStream = httpServletResponse.getOutputStream(); + baosCopy = new ByteArrayOutputStream(); + } - @Override - public void write(int val) throws IOException { - if (underlyingStream != null) { - underlyingStream.write(val); - baosCopy.write(val); + byte[] getOutputStreamAsByteArray() { + return baosCopy.toByteArray(); } - } - @Override - public void write(byte[] byteArray) throws IOException { - if (underlyingStream == null) { - return; + @Override + public void write(int val) throws IOException { + if (underlyingStream != null) { + underlyingStream.write(val); + baosCopy.write(val); + } } - // System.out.println("WRITE TeeServletOutputStream.write(byte[]) called"); - write(byteArray, 0, byteArray.length); - } - @Override - public void write(byte byteArray[], int offset, int length) - throws IOException { - if (underlyingStream == null) { - return; + @Override + public void write(byte[] byteArray) throws IOException { + if (underlyingStream == null) { + return; + } + // System.out.println("WRITE TeeServletOutputStream.write(byte[]) called"); + write(byteArray, 0, byteArray.length); } - // System.out.println("WRITE TeeServletOutputStream.write(byte[], int, int) - // called"); - // System.out.println(new String(byteArray, offset, length)); - underlyingStream.write(byteArray, offset, length); - baosCopy.write(byteArray, offset, length); - } - @Override - public void close() throws IOException { - // System.out.println("CLOSE TeeServletOutputStream.close() called"); + @Override + public void write(byte byteArray[], int offset, int length) throws IOException { + if (underlyingStream == null) { + return; + } + // System.out.println("WRITE TeeServletOutputStream.write(byte[], int, int) + // called"); + // System.out.println(new String(byteArray, offset, length)); + underlyingStream.write(byteArray, offset, length); + baosCopy.write(byteArray, offset, length); + } - // If the servlet accessing the stream is using a writer instead of - // an OutputStream, it will probably call os.close() before calling - // writer.close. Thus, the underlying output stream will be called - // before the data sent to the writer could be flushed. - } + @Override + public void close() throws IOException { + // System.out.println("CLOSE TeeServletOutputStream.close() called"); + // If the servlet accessing the stream is using a writer instead of + // an OutputStream, it will probably call os.close() before calling + // writer.close. Thus, the underlying output stream will be called + // before the data sent to the writer could be flushed. + } - @Override - public void flush() throws IOException { - if (underlyingStream == null) { - return; + @Override + public void flush() throws IOException { + if (underlyingStream == null) { + return; + } + // System.out.println("FLUSH TeeServletOutputStream.flush() called"); + underlyingStream.flush(); + baosCopy.flush(); } - // System.out.println("FLUSH TeeServletOutputStream.flush() called"); - underlyingStream.flush(); - baosCopy.flush(); - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/servlet/Util.java b/logback-access/src/main/java/ch/qos/logback/access/servlet/Util.java index a61cf53a182a65a52451bc33090ecd98d687a5f4..241d4398f92fcaffcab4df14556c18cfa34ceb13 100755 --- a/logback-access/src/main/java/ch/qos/logback/access/servlet/Util.java +++ b/logback-access/src/main/java/ch/qos/logback/access/servlet/Util.java @@ -20,26 +20,24 @@ import javax.servlet.http.HttpServletResponse; public class Util { - public static boolean isFormUrlEncoded(HttpServletRequest request) { - - String contentTypeStr = request.getContentType(); - if ("POST".equalsIgnoreCase(request.getMethod()) - && contentTypeStr != null - && contentTypeStr.startsWith(AccessConstants.X_WWW_FORM_URLECODED)) { - return true; - } else { - return false; + public static boolean isFormUrlEncoded(HttpServletRequest request) { + + String contentTypeStr = request.getContentType(); + if ("POST".equalsIgnoreCase(request.getMethod()) && contentTypeStr != null && contentTypeStr.startsWith(AccessConstants.X_WWW_FORM_URLECODED)) { + return true; + } else { + return false; + } } - } - public static boolean isImageResponse(HttpServletResponse response) { + public static boolean isImageResponse(HttpServletResponse response) { - String responseType = response.getContentType(); + String responseType = response.getContentType(); - if (responseType != null && responseType.startsWith(AccessConstants.IMAGE_CONTENT_TYPE)) { - return true; - } else { - return false; + if (responseType != null && responseType.startsWith(AccessConstants.IMAGE_CONTENT_TYPE)) { + return true; + } else { + return false; + } } - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/sift/AccessEventDiscriminator.java b/logback-access/src/main/java/ch/qos/logback/access/sift/AccessEventDiscriminator.java index 17aff9e56a28accecc32c95483e16fad1d117265..820d85d5fef57e9e6363a6ee9ccdfde2c711b236 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/sift/AccessEventDiscriminator.java +++ b/logback-access/src/main/java/ch/qos/logback/access/sift/AccessEventDiscriminator.java @@ -31,161 +31,160 @@ import ch.qos.logback.core.sift.AbstractDiscriminator; */ public class AccessEventDiscriminator extends AbstractDiscriminator { - /** - * At present time the followed fields can be designated: COOKIE, - * REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, - * LOCAL_PORT,REQUEST_URI - * - *

The first three fields require an additional key. For the - * SESSION_ATTRIBUTE field, the additional key named "id" has special meaning - * as it is mapped to the session id of the current http request. - */ - public enum FieldName { - COOKIE, REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, LOCAL_PORT, REQUEST_URI - } - - String defaultValue; - String key; - FieldName fieldName; - String additionalKey; - - @Override - public String getDiscriminatingValue(IAccessEvent acccessEvent) { - String rawValue = getRawDiscriminatingValue(acccessEvent); - if (rawValue == null || rawValue.length() == 0) { - return defaultValue; - } else { - return rawValue; + /** + * At present time the followed fields can be designated: COOKIE, + * REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, + * LOCAL_PORT,REQUEST_URI + * + *

The first three fields require an additional key. For the + * SESSION_ATTRIBUTE field, the additional key named "id" has special meaning + * as it is mapped to the session id of the current http request. + */ + public enum FieldName { + COOKIE, REQUEST_ATTRIBUTE, SESSION_ATTRIBUTE, REMOTE_ADDRESS, LOCAL_PORT, REQUEST_URI } - } - - public String getRawDiscriminatingValue(IAccessEvent acccessEvent) { - switch (fieldName) { - case COOKIE: - // tested - return acccessEvent.getCookie(additionalKey); - case LOCAL_PORT: - return String.valueOf(acccessEvent.getLocalPort()); - case REQUEST_ATTRIBUTE: - // tested - return getRequestAttribute(acccessEvent); - case SESSION_ATTRIBUTE: - return getSessionAttribute(acccessEvent); - case REMOTE_ADDRESS: - return acccessEvent.getRemoteAddr(); - case REQUEST_URI: - // tested - return getRequestURI(acccessEvent); - default: - return null; + + String defaultValue; + String key; + FieldName fieldName; + String additionalKey; + + @Override + public String getDiscriminatingValue(IAccessEvent acccessEvent) { + String rawValue = getRawDiscriminatingValue(acccessEvent); + if (rawValue == null || rawValue.length() == 0) { + return defaultValue; + } else { + return rawValue; + } } - } - - private String getRequestAttribute(IAccessEvent acccessEvent) { - String attr = acccessEvent.getAttribute(additionalKey); - if (IAccessEvent.NA.equals(attr)) { - return null; - } else { - return attr; + + public String getRawDiscriminatingValue(IAccessEvent acccessEvent) { + switch (fieldName) { + case COOKIE: + // tested + return acccessEvent.getCookie(additionalKey); + case LOCAL_PORT: + return String.valueOf(acccessEvent.getLocalPort()); + case REQUEST_ATTRIBUTE: + // tested + return getRequestAttribute(acccessEvent); + case SESSION_ATTRIBUTE: + return getSessionAttribute(acccessEvent); + case REMOTE_ADDRESS: + return acccessEvent.getRemoteAddr(); + case REQUEST_URI: + // tested + return getRequestURI(acccessEvent); + default: + return null; + } } - } - - private String getRequestURI(IAccessEvent acccessEvent) { - String uri = acccessEvent.getRequestURI(); - if (uri != null && uri.length() >= 1 && uri.charAt(0) == '/') { - return uri.substring(1); - } else { - return uri; + + private String getRequestAttribute(IAccessEvent acccessEvent) { + String attr = acccessEvent.getAttribute(additionalKey); + if (IAccessEvent.NA.equals(attr)) { + return null; + } else { + return attr; + } } - } - - private String getSessionAttribute(IAccessEvent acccessEvent) { - HttpServletRequest req = acccessEvent.getRequest(); - if (req != null) { - HttpSession session = req.getSession(false); - if (session != null) { - if ("id".equalsIgnoreCase(additionalKey)) { - return session.getId(); + + private String getRequestURI(IAccessEvent acccessEvent) { + String uri = acccessEvent.getRequestURI(); + if (uri != null && uri.length() >= 1 && uri.charAt(0) == '/') { + return uri.substring(1); } else { - Object v = session.getAttribute(additionalKey); - if (v != null) { - return v.toString(); - } + return uri; + } + } + + private String getSessionAttribute(IAccessEvent acccessEvent) { + HttpServletRequest req = acccessEvent.getRequest(); + if (req != null) { + HttpSession session = req.getSession(false); + if (session != null) { + if ("id".equalsIgnoreCase(additionalKey)) { + return session.getId(); + } else { + Object v = session.getAttribute(additionalKey); + if (v != null) { + return v.toString(); + } + } + } + } + return null; + } + + @Override + public void start() { + + int errorCount = 0; + + if (defaultValue == null) { + addError("\"DefaultValue\" property must be set."); + } + if (fieldName == null) { + addError("\"FieldName\" property must be set."); + errorCount++; + } + + switch (fieldName) { + case SESSION_ATTRIBUTE: + case REQUEST_ATTRIBUTE: + case COOKIE: + if (additionalKey == null) { + addError("\"OptionalKey\" property is mandatory for field name " + fieldName.toString()); + errorCount++; + } + } + + if (errorCount == 0) { + started = true; } - } } - return null; - } - @Override - public void start() { + public void setFieldName(FieldName fieldName) { + this.fieldName = fieldName; + } + + public FieldName getFieldName() { + return fieldName; + } - int errorCount = 0; + public String getAdditionalKey() { + return additionalKey; + } - if (defaultValue == null) { - addError("\"DefaultValue\" property must be set."); + public void setAdditionalKey(String additionalKey) { + this.additionalKey = additionalKey; } - if (fieldName == null) { - addError("\"FieldName\" property must be set."); - errorCount++; + + /** + * @see #setDefaultValue(String) + * @return + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * The default value returned by this discriminator in case it cannot compute + * the discriminating value from the access event. + * + * @param defaultValue + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; } - switch (fieldName) { - case SESSION_ATTRIBUTE: - case REQUEST_ATTRIBUTE: - case COOKIE: - if (additionalKey == null) { - addError("\"OptionalKey\" property is mandatory for field name " - + fieldName.toString()); - errorCount++; - } + public String getKey() { + return key; } - if (errorCount == 0) { - started = true; + public void setKey(String key) { + this.key = key; } - } - - public void setFieldName(FieldName fieldName) { - this.fieldName = fieldName; - } - - public FieldName getFieldName() { - return fieldName; - } - - public String getAdditionalKey() { - return additionalKey; - } - - public void setAdditionalKey(String additionalKey) { - this.additionalKey = additionalKey; - } - - /** - * @see #setDefaultValue(String) - * @return - */ - public String getDefaultValue() { - return defaultValue; - } - - /** - * The default value returned by this discriminator in case it cannot compute - * the discriminating value from the access event. - * - * @param defaultValue - */ - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/sift/AppenderFactoryUsingJoran.java b/logback-access/src/main/java/ch/qos/logback/access/sift/AppenderFactoryUsingJoran.java index ec3eb8704e15ceb9daef2ffa737ceb2ad3ef7597..09c1635cb2fab8bb7588bee47c37ef8080c31ff7 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/sift/AppenderFactoryUsingJoran.java +++ b/logback-access/src/main/java/ch/qos/logback/access/sift/AppenderFactoryUsingJoran.java @@ -23,14 +23,13 @@ import ch.qos.logback.core.sift.SiftingJoranConfiguratorBase; public class AppenderFactoryUsingJoran extends AbstractAppenderFactoryUsingJoran { - AppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { - super(eventList, key, parentPropertyMap); - } + AppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { + super(eventList, key, parentPropertyMap); + } - @Override - public SiftingJoranConfiguratorBase getSiftingJoranConfigurator( - String keyValue) { - return new SiftingJoranConfigurator(key, keyValue, parentPropertyMap); - } + @Override + public SiftingJoranConfiguratorBase getSiftingJoranConfigurator(String keyValue) { + return new SiftingJoranConfigurator(key, keyValue, parentPropertyMap); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftAction.java b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftAction.java index 6e5b67a84a0f3dbdf13139e55b5d20e3de629736..0e985153f37ea73404edf3610c008834b2a1cb73 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftAction.java +++ b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftAction.java @@ -25,38 +25,34 @@ import ch.qos.logback.core.joran.event.SaxEvent; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; -public class SiftAction extends Action implements InPlayListener { - List seList; - - @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { - seList = new ArrayList(); - ic.addInPlayListener(this); - } - - @Override - public void end(InterpretationContext ic, String name) throws ActionException { - ic.removeInPlayListener(this); - Object o = ic.peekObject(); - if (o instanceof SiftingAppender) { - SiftingAppender siftingAppender = (SiftingAppender) o; - Map propertyMap = ic.getCopyOfPropertyMap(); - AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, siftingAppender.getDiscriminatorKey(), propertyMap); - siftingAppender.setAppenderFactory(appenderFactory); - } - } +public class SiftAction extends Action implements InPlayListener { + List seList; - @Override - public void inPlay(SaxEvent event) { - seList.add(event); - } + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { + seList = new ArrayList(); + ic.addInPlayListener(this); + } - public List getSeList() { - return seList; - } + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + ic.removeInPlayListener(this); + Object o = ic.peekObject(); + if (o instanceof SiftingAppender) { + SiftingAppender siftingAppender = (SiftingAppender) o; + Map propertyMap = ic.getCopyOfPropertyMap(); + AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, siftingAppender.getDiscriminatorKey(), propertyMap); + siftingAppender.setAppenderFactory(appenderFactory); + } + } - + @Override + public void inPlay(SaxEvent event) { + seList.add(event); + } + public List getSeList() { + return seList; + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingAppender.java b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingAppender.java index ef970c3679f8f549233055d0bc7fc5d4e77573f9..65eada81bdbb60aaf840d8934c1879b42c24422c 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingAppender.java +++ b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingAppender.java @@ -30,24 +30,24 @@ import ch.qos.logback.core.sift.SiftingAppenderBase; */ public class SiftingAppender extends SiftingAppenderBase { - @Override - public void start() { - super.start(); - } + @Override + public void start() { + super.start(); + } - @Override - protected long getTimestamp(IAccessEvent event) { - return event.getTimeStamp(); - } + @Override + protected long getTimestamp(IAccessEvent event) { + return event.getTimeStamp(); + } - @Override - protected boolean eventMarksEndOfLife(IAccessEvent event) { - return false; - } + @Override + protected boolean eventMarksEndOfLife(IAccessEvent event) { + return false; + } - @Override - @DefaultClass(AccessEventDiscriminator.class) - public void setDiscriminator(Discriminator discriminator) { - super.setDiscriminator(discriminator); - } + @Override + @DefaultClass(AccessEventDiscriminator.class) + public void setDiscriminator(Discriminator discriminator) { + super.setDiscriminator(discriminator); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingJoranConfigurator.java b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingJoranConfigurator.java index 8b2a8eadbf76028aea2d86882f797311a5b87a7d..6d559f7c9a656c91dda4165476f88a873dc243a6 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingJoranConfigurator.java +++ b/logback-access/src/main/java/ch/qos/logback/access/sift/SiftingJoranConfigurator.java @@ -26,49 +26,44 @@ import ch.qos.logback.core.joran.spi.ElementSelector; import ch.qos.logback.core.joran.spi.RuleStore; import ch.qos.logback.core.sift.SiftingJoranConfiguratorBase; -public class SiftingJoranConfigurator extends - SiftingJoranConfiguratorBase { +public class SiftingJoranConfigurator extends SiftingJoranConfiguratorBase { + SiftingJoranConfigurator(String key, String value, Map parentPropertyMap) { + super(key, value, parentPropertyMap); + } + @Override + protected ElementPath initialElementPath() { + return new ElementPath("configuration"); + } - SiftingJoranConfigurator(String key, String value, Map parentPropertyMap) { - super(key, value, parentPropertyMap); - } - - @Override - protected ElementPath initialElementPath() { - return new ElementPath("configuration"); - } - - @Override - protected void addInstanceRules(RuleStore rs) { - rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); - } + @Override + protected void addInstanceRules(RuleStore rs) { + rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); + } - @Override - protected void buildInterpreter() { - super.buildInterpreter(); - Map omap = interpreter.getInterpretationContext() - .getObjectMap(); - omap.put(ActionConst.APPENDER_BAG, new HashMap()); - omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); - Map propertiesMap = new HashMap(); - propertiesMap.putAll(parentPropertyMap); - propertiesMap.put(key, value); - interpreter.setInterpretationContextPropertiesMap(propertiesMap); - } + @Override + protected void buildInterpreter() { + super.buildInterpreter(); + Map omap = interpreter.getInterpretationContext().getObjectMap(); + omap.put(ActionConst.APPENDER_BAG, new HashMap()); + omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); + Map propertiesMap = new HashMap(); + propertiesMap.putAll(parentPropertyMap); + propertiesMap.put(key, value); + interpreter.setInterpretationContextPropertiesMap(propertiesMap); + } - @SuppressWarnings("unchecked") - @Override - public Appender getAppender() { - Map omap = interpreter.getInterpretationContext() - .getObjectMap(); - HashMap appenderMap = (HashMap) omap.get(ActionConst.APPENDER_BAG); - oneAndOnlyOneCheck(appenderMap); - Collection values = appenderMap.values(); - if(values.size() == 0) { - return null; + @SuppressWarnings("unchecked") + @Override + public Appender getAppender() { + Map omap = interpreter.getInterpretationContext().getObjectMap(); + HashMap appenderMap = (HashMap) omap.get(ActionConst.APPENDER_BAG); + oneAndOnlyOneCheck(appenderMap); + Collection values = appenderMap.values(); + if (values.size() == 0) { + return null; + } + return (Appender) values.iterator().next(); } - return (Appender) values.iterator().next(); - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/spi/AccessContext.java b/logback-access/src/main/java/ch/qos/logback/access/spi/AccessContext.java index 154e340f10907089f763cefc1886f4f849d5c42a..569421e240f3fd10b037f820f6f14d6a8d6b8268 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/spi/AccessContext.java +++ b/logback-access/src/main/java/ch/qos/logback/access/spi/AccessContext.java @@ -31,68 +31,67 @@ import ch.qos.logback.core.spi.FilterReply; * * @author Sébastien Pennec */ -public class AccessContext extends ContextBase implements - AppenderAttachable, FilterAttachable { - - AppenderAttachableImpl aai = new AppenderAttachableImpl(); - FilterAttachableImpl fai = new FilterAttachableImpl(); - - public void callAppenders(IAccessEvent event) { - aai.appendLoopOnAppenders(event); - } - - @Override - public void addAppender(Appender newAppender) { - aai.addAppender(newAppender); - } - - @Override - public void detachAndStopAllAppenders() { - aai.detachAndStopAllAppenders(); - } - - @Override - public boolean detachAppender(Appender appender) { - return aai.detachAppender(appender); - } - - @Override - public boolean detachAppender(String name) { - return aai.detachAppender(name); - } - - @Override - public Appender getAppender(String name) { - return aai.getAppender(name); - } - - @Override - public boolean isAttached(Appender appender) { - return aai.isAttached(appender); - } - - @Override - public Iterator> iteratorForAppenders() { - return aai.iteratorForAppenders(); - } - - @Override - public void addFilter(Filter newFilter) { - fai.addFilter(newFilter); - } - - @Override - public void clearAllFilters() { - fai.clearAllFilters(); - } - - @Override - public List> getCopyOfAttachedFiltersList() { - return fai.getCopyOfAttachedFiltersList(); - } - - @Override - public FilterReply getFilterChainDecision(IAccessEvent event) { - return fai.getFilterChainDecision(event); - } +public class AccessContext extends ContextBase implements AppenderAttachable, FilterAttachable { + + AppenderAttachableImpl aai = new AppenderAttachableImpl(); + FilterAttachableImpl fai = new FilterAttachableImpl(); + + public void callAppenders(IAccessEvent event) { + aai.appendLoopOnAppenders(event); + } + + @Override + public void addAppender(Appender newAppender) { + aai.addAppender(newAppender); + } + + @Override + public void detachAndStopAllAppenders() { + aai.detachAndStopAllAppenders(); + } + + @Override + public boolean detachAppender(Appender appender) { + return aai.detachAppender(appender); + } + + @Override + public boolean detachAppender(String name) { + return aai.detachAppender(name); + } + + @Override + public Appender getAppender(String name) { + return aai.getAppender(name); + } + + @Override + public boolean isAttached(Appender appender) { + return aai.isAttached(appender); + } + + @Override + public Iterator> iteratorForAppenders() { + return aai.iteratorForAppenders(); + } + + @Override + public void addFilter(Filter newFilter) { + fai.addFilter(newFilter); + } + + @Override + public void clearAllFilters() { + fai.clearAllFilters(); + } + + @Override + public List> getCopyOfAttachedFiltersList() { + return fai.getCopyOfAttachedFiltersList(); + } + + @Override + public FilterReply getFilterChainDecision(IAccessEvent event) { + return fai.getFilterChainDecision(event); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java b/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java index 20ee17355c2a1acdcc805e547ffa2fd11d8dc870..3e74154f6b9d81dbc253ba3b2d79c05c9143bc00 100755 --- a/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java +++ b/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java @@ -43,513 +43,508 @@ import java.util.Vector; */ public class AccessEvent implements Serializable, IAccessEvent { + private static final long serialVersionUID = 866718993618836343L; + + private static final String EMPTY = ""; + + private transient final HttpServletRequest httpRequest; + private transient final HttpServletResponse httpResponse; + + String requestURI; + String requestURL; + String remoteHost; + String remoteUser; + String remoteAddr; + String protocol; + String method; + String serverName; + String requestContent; + String responseContent; + long elapsedTime; + + Map requestHeaderMap; + Map requestParameterMap; + Map responseHeaderMap; + Map attributeMap; + + long contentLength = SENTINEL; + int statusCode = SENTINEL; + int localPort = SENTINEL; + + transient ServerAdapter serverAdapter; + + /** + * The number of milliseconds elapsed from 1/1/1970 until logging event was + * created. + */ + private long timeStamp = 0; + + public AccessEvent(HttpServletRequest httpRequest, HttpServletResponse httpResponse, ServerAdapter adapter) { + this.httpRequest = httpRequest; + this.httpResponse = httpResponse; + this.timeStamp = System.currentTimeMillis(); + this.serverAdapter = adapter; + this.elapsedTime = calculateElapsedTime(); + } + + /** + * Returns the underlying HttpServletRequest. After serialization the returned + * value will be null. + * + * @return + */ + @Override + public HttpServletRequest getRequest() { + return httpRequest; + } + + /** + * Returns the underlying HttpServletResponse. After serialization the returned + * value will be null. + * + * @return + */ + @Override + public HttpServletResponse getResponse() { + return httpResponse; + } + + @Override + public long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(long timeStamp) { + if (this.timeStamp != 0) { + throw new IllegalStateException("timeStamp has been already set for this event."); + } else { + this.timeStamp = timeStamp; + } + } - private static final long serialVersionUID = 866718993618836343L; - - private static final String EMPTY = ""; - - private transient final HttpServletRequest httpRequest; - private transient final HttpServletResponse httpResponse; - - String requestURI; - String requestURL; - String remoteHost; - String remoteUser; - String remoteAddr; - String protocol; - String method; - String serverName; - String requestContent; - String responseContent; - long elapsedTime; - - Map requestHeaderMap; - Map requestParameterMap; - Map responseHeaderMap; - Map attributeMap; - - long contentLength = SENTINEL; - int statusCode = SENTINEL; - int localPort = SENTINEL; - - transient ServerAdapter serverAdapter; - - /** - * The number of milliseconds elapsed from 1/1/1970 until logging event was - * created. - */ - private long timeStamp = 0; - - public AccessEvent(HttpServletRequest httpRequest, - HttpServletResponse httpResponse, ServerAdapter adapter) { - this.httpRequest = httpRequest; - this.httpResponse = httpResponse; - this.timeStamp = System.currentTimeMillis(); - this.serverAdapter = adapter; - this.elapsedTime = calculateElapsedTime(); - } - - /** - * Returns the underlying HttpServletRequest. After serialization the returned - * value will be null. - * - * @return - */ - @Override - public HttpServletRequest getRequest() { - return httpRequest; - } - - /** - * Returns the underlying HttpServletResponse. After serialization the returned - * value will be null. - * - * @return - */ - @Override - public HttpServletResponse getResponse() { - return httpResponse; - } - - @Override - public long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(long timeStamp) { - if (this.timeStamp != 0) { - throw new IllegalStateException( - "timeStamp has been already set for this event."); - } else { - this.timeStamp = timeStamp; - } - } - - @Override - public String getRequestURI() { - if (requestURI == null) { - if (httpRequest != null) { - requestURI = httpRequest.getRequestURI(); - } else { - requestURI = NA; - } - } - return requestURI; - } - - /** - * The first line of the request. - */ - @Override - public String getRequestURL() { - if (requestURL == null) { - if (httpRequest != null) { - StringBuilder buf = new StringBuilder(); - buf.append(httpRequest.getMethod()); - buf.append(AccessConverter.SPACE_CHAR); - buf.append(httpRequest.getRequestURI()); - final String qStr = httpRequest.getQueryString(); - if (qStr != null) { - buf.append(AccessConverter.QUESTION_CHAR); - buf.append(qStr); - } - buf.append(AccessConverter.SPACE_CHAR); - buf.append(httpRequest.getProtocol()); - requestURL = buf.toString(); - } else { - requestURL = NA; - } - } - return requestURL; - } - - @Override - public String getRemoteHost() { - if (remoteHost == null) { - if (httpRequest != null) { - // the underlying implementation of HttpServletRequest will - // determine if remote lookup will be performed - remoteHost = httpRequest.getRemoteHost(); - } else { - remoteHost = NA; - } - } - return remoteHost; - } - - @Override - public String getRemoteUser() { - if (remoteUser == null) { - if (httpRequest != null) { - remoteUser = httpRequest.getRemoteUser(); - } else { - remoteUser = NA; - } - } - return remoteUser; - } - - @Override - public String getProtocol() { - if (protocol == null) { - if (httpRequest != null) { - protocol = httpRequest.getProtocol(); - } else { - protocol = NA; - } - } - return protocol; - } - - @Override - public String getMethod() { - if (method == null) { - if (httpRequest != null) { - method = httpRequest.getMethod(); - } else { - method = NA; - } - } - return method; - } - - @Override - public String getServerName() { - if (serverName == null) { - if (httpRequest != null) { - serverName = httpRequest.getServerName(); - } else { - serverName = NA; - } - } - return serverName; - } - - @Override - public String getRemoteAddr() { - if (remoteAddr == null) { - if (httpRequest != null) { - remoteAddr = httpRequest.getRemoteAddr(); - } else { - remoteAddr = NA; - } - } - return remoteAddr; - } - - @Override - public String getRequestHeader(String key) { - String result = null; - key = key.toLowerCase(); - if (requestHeaderMap == null) { - if (httpRequest != null) { - buildRequestHeaderMap(); - result = requestHeaderMap.get(key); - } - } else { - result = requestHeaderMap.get(key); - } - - if (result != null) { - return result; - } else { - return NA; - } - } - - @Override - public Enumeration getRequestHeaderNames() { - // post-serialization - if (httpRequest == null) { - Vector list = new Vector(getRequestHeaderMap().keySet()); - return list.elements(); - } - return httpRequest.getHeaderNames(); - } - - @Override - public Map getRequestHeaderMap() { - if (requestHeaderMap == null) { - buildRequestHeaderMap(); - } - return requestHeaderMap; - } - - public void buildRequestHeaderMap() { - // according to RFC 2616 header names are case insensitive - // latest versions of Tomcat return header names in lower-case - requestHeaderMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); - Enumeration e = httpRequest.getHeaderNames(); - if (e == null) { - return; - } - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - requestHeaderMap.put(key, httpRequest.getHeader(key)); - } - } - - public void buildRequestParameterMap() { - requestParameterMap = new HashMap(); - Enumeration e = httpRequest.getParameterNames(); - if (e == null) { - return; - } - while (e.hasMoreElements()) { - String key = (String) e.nextElement(); - requestParameterMap.put(key, httpRequest.getParameterValues(key)); - } - } - - @Override - public Map getRequestParameterMap() { - if (requestParameterMap == null) { - buildRequestParameterMap(); - } - return requestParameterMap; - } - - @Override - public String getAttribute(String key) { - Object value = null; - if (attributeMap != null) { - // Event was prepared for deferred processing so we have a copy of attribute map and must use that copy - value = attributeMap.get(key); - } else if (httpRequest != null) { - // We have original request so take attribute from it - value = httpRequest.getAttribute(key); - } - - return value != null ? value.toString() : NA; - } - - private void copyAttributeMap() { - - if (httpRequest == null) { - return; - } - - attributeMap = new HashMap(); - - Enumeration names = httpRequest.getAttributeNames(); - while (names.hasMoreElements()) { - String name = names.nextElement(); - - Object value = httpRequest.getAttribute(name); - if (shouldCopyAttribute(name, value)) { - attributeMap.put(name, value); - } - } - } - - private boolean shouldCopyAttribute(String name, Object value) { - if (AccessConstants.LB_INPUT_BUFFER.equals(name) || AccessConstants.LB_OUTPUT_BUFFER.equals(name)) { - // Do not copy attributes used by logback internally - these are available via other getters anyway - return false; - } else if (value == null) { - // No reasons to copy nulls - Map.get() will return null for missing keys and the list of attribute - // names is not available through IAccessEvent - return false; - } else { - // Only copy what is serializable - return value instanceof Serializable; - } - } - - @Override - public String[] getRequestParameter(String key) { - if (httpRequest != null) { - String[] value = httpRequest.getParameterValues(key); - if (value == null) { - return new String[]{ NA }; - } else { - return value; - } - } else { - return new String[]{ NA }; - } - } - - @Override - public String getCookie(String key) { - - if (httpRequest != null) { - Cookie[] cookieArray = httpRequest.getCookies(); - if (cookieArray == null) { - return NA; - } + @Override + public String getRequestURI() { + if (requestURI == null) { + if (httpRequest != null) { + requestURI = httpRequest.getRequestURI(); + } else { + requestURI = NA; + } + } + return requestURI; + } + + /** + * The first line of the request. + */ + @Override + public String getRequestURL() { + if (requestURL == null) { + if (httpRequest != null) { + StringBuilder buf = new StringBuilder(); + buf.append(httpRequest.getMethod()); + buf.append(AccessConverter.SPACE_CHAR); + buf.append(httpRequest.getRequestURI()); + final String qStr = httpRequest.getQueryString(); + if (qStr != null) { + buf.append(AccessConverter.QUESTION_CHAR); + buf.append(qStr); + } + buf.append(AccessConverter.SPACE_CHAR); + buf.append(httpRequest.getProtocol()); + requestURL = buf.toString(); + } else { + requestURL = NA; + } + } + return requestURL; + } + + @Override + public String getRemoteHost() { + if (remoteHost == null) { + if (httpRequest != null) { + // the underlying implementation of HttpServletRequest will + // determine if remote lookup will be performed + remoteHost = httpRequest.getRemoteHost(); + } else { + remoteHost = NA; + } + } + return remoteHost; + } + + @Override + public String getRemoteUser() { + if (remoteUser == null) { + if (httpRequest != null) { + remoteUser = httpRequest.getRemoteUser(); + } else { + remoteUser = NA; + } + } + return remoteUser; + } + + @Override + public String getProtocol() { + if (protocol == null) { + if (httpRequest != null) { + protocol = httpRequest.getProtocol(); + } else { + protocol = NA; + } + } + return protocol; + } + + @Override + public String getMethod() { + if (method == null) { + if (httpRequest != null) { + method = httpRequest.getMethod(); + } else { + method = NA; + } + } + return method; + } + + @Override + public String getServerName() { + if (serverName == null) { + if (httpRequest != null) { + serverName = httpRequest.getServerName(); + } else { + serverName = NA; + } + } + return serverName; + } + + @Override + public String getRemoteAddr() { + if (remoteAddr == null) { + if (httpRequest != null) { + remoteAddr = httpRequest.getRemoteAddr(); + } else { + remoteAddr = NA; + } + } + return remoteAddr; + } + + @Override + public String getRequestHeader(String key) { + String result = null; + key = key.toLowerCase(); + if (requestHeaderMap == null) { + if (httpRequest != null) { + buildRequestHeaderMap(); + result = requestHeaderMap.get(key); + } + } else { + result = requestHeaderMap.get(key); + } + + if (result != null) { + return result; + } else { + return NA; + } + } + + @Override + public Enumeration getRequestHeaderNames() { + // post-serialization + if (httpRequest == null) { + Vector list = new Vector(getRequestHeaderMap().keySet()); + return list.elements(); + } + return httpRequest.getHeaderNames(); + } + + @Override + public Map getRequestHeaderMap() { + if (requestHeaderMap == null) { + buildRequestHeaderMap(); + } + return requestHeaderMap; + } + + public void buildRequestHeaderMap() { + // according to RFC 2616 header names are case insensitive + // latest versions of Tomcat return header names in lower-case + requestHeaderMap = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Enumeration e = httpRequest.getHeaderNames(); + if (e == null) { + return; + } + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + requestHeaderMap.put(key, httpRequest.getHeader(key)); + } + } + + public void buildRequestParameterMap() { + requestParameterMap = new HashMap(); + Enumeration e = httpRequest.getParameterNames(); + if (e == null) { + return; + } + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + requestParameterMap.put(key, httpRequest.getParameterValues(key)); + } + } + + @Override + public Map getRequestParameterMap() { + if (requestParameterMap == null) { + buildRequestParameterMap(); + } + return requestParameterMap; + } + + @Override + public String getAttribute(String key) { + Object value = null; + if (attributeMap != null) { + // Event was prepared for deferred processing so we have a copy of attribute map and must use that copy + value = attributeMap.get(key); + } else if (httpRequest != null) { + // We have original request so take attribute from it + value = httpRequest.getAttribute(key); + } + + return value != null ? value.toString() : NA; + } + + private void copyAttributeMap() { + + if (httpRequest == null) { + return; + } - for (Cookie cookie : cookieArray) { - if (key.equals(cookie.getName())) { - return cookie.getValue(); + attributeMap = new HashMap(); + + Enumeration names = httpRequest.getAttributeNames(); + while (names.hasMoreElements()) { + String name = names.nextElement(); + + Object value = httpRequest.getAttribute(name); + if (shouldCopyAttribute(name, value)) { + attributeMap.put(name, value); + } + } + } + + private boolean shouldCopyAttribute(String name, Object value) { + if (AccessConstants.LB_INPUT_BUFFER.equals(name) || AccessConstants.LB_OUTPUT_BUFFER.equals(name)) { + // Do not copy attributes used by logback internally - these are available via other getters anyway + return false; + } else if (value == null) { + // No reasons to copy nulls - Map.get() will return null for missing keys and the list of attribute + // names is not available through IAccessEvent + return false; + } else { + // Only copy what is serializable + return value instanceof Serializable; + } + } + + @Override + public String[] getRequestParameter(String key) { + if (httpRequest != null) { + String[] value = httpRequest.getParameterValues(key); + if (value == null) { + return new String[] { NA }; + } else { + return value; + } + } else { + return new String[] { NA }; + } + } + + @Override + public String getCookie(String key) { + + if (httpRequest != null) { + Cookie[] cookieArray = httpRequest.getCookies(); + if (cookieArray == null) { + return NA; + } + + for (Cookie cookie : cookieArray) { + if (key.equals(cookie.getName())) { + return cookie.getValue(); + } + } } - } + return NA; } - return NA; - } - @Override - public long getContentLength() { - if (contentLength == SENTINEL) { - if (httpResponse != null) { - contentLength = serverAdapter.getContentLength(); + @Override + public long getContentLength() { + if (contentLength == SENTINEL) { + if (httpResponse != null) { + contentLength = serverAdapter.getContentLength(); + return contentLength; + } + } return contentLength; - } } - return contentLength; - } - - public int getStatusCode() { - if (statusCode == SENTINEL) { - if (httpResponse != null) { - statusCode = serverAdapter.getStatusCode(); - } + + public int getStatusCode() { + if (statusCode == SENTINEL) { + if (httpResponse != null) { + statusCode = serverAdapter.getStatusCode(); + } + } + return statusCode; } - return statusCode; - } - public long getElapsedTime() { - return elapsedTime; - } + public long getElapsedTime() { + return elapsedTime; + } - private long calculateElapsedTime() { - if (serverAdapter.getRequestTimestamp() < 0) { - return -1; + private long calculateElapsedTime() { + if (serverAdapter.getRequestTimestamp() < 0) { + return -1; + } + return getTimeStamp() - serverAdapter.getRequestTimestamp(); } - return getTimeStamp() - serverAdapter.getRequestTimestamp(); - } - public String getRequestContent() { - if (requestContent != null) { - return requestContent; + public String getRequestContent() { + if (requestContent != null) { + return requestContent; + } + + if (Util.isFormUrlEncoded(httpRequest)) { + StringBuilder buf = new StringBuilder(); + + Enumeration pramEnumeration = httpRequest.getParameterNames(); + + // example: id=1234&user=cgu + // number=1233&x=1 + int count = 0; + try { + while (pramEnumeration.hasMoreElements()) { + + String key = (String) pramEnumeration.nextElement(); + if (count++ != 0) { + buf.append("&"); + } + buf.append(key); + buf.append("="); + String val = httpRequest.getParameter(key); + if (val != null) { + buf.append(val); + } else { + buf.append(""); + } + } + } catch (Exception e) { + // FIXME Why is try/catch required? + e.printStackTrace(); + } + requestContent = buf.toString(); + } else { + // retrieve the byte array placed by TeeFilter + byte[] inputBuffer = (byte[]) httpRequest.getAttribute(AccessConstants.LB_INPUT_BUFFER); + + if (inputBuffer != null) { + requestContent = new String(inputBuffer); + } + + if (requestContent == null || requestContent.length() == 0) { + requestContent = EMPTY; + } + } + + return requestContent; } - if (Util.isFormUrlEncoded(httpRequest)) { - StringBuilder buf = new StringBuilder(); + public String getResponseContent() { + if (responseContent != null) { + return responseContent; + } - Enumeration pramEnumeration = httpRequest.getParameterNames(); + if (Util.isImageResponse(httpResponse)) { + responseContent = "[IMAGE CONTENTS SUPPRESSED]"; + } else { - // example: id=1234&user=cgu - // number=1233&x=1 - int count = 0; - try { - while (pramEnumeration.hasMoreElements()) { - - String key = (String) pramEnumeration.nextElement(); - if (count++ != 0) { - buf.append("&"); - } - buf.append(key); - buf.append("="); - String val = httpRequest.getParameter(key); - if (val != null) { - buf.append(val); - } else { - buf.append(""); - } - } - } catch (Exception e) { - // FIXME Why is try/catch required? - e.printStackTrace(); - } - requestContent = buf.toString(); - } else { - // retrieve the byte array placed by TeeFilter - byte[] inputBuffer = (byte[]) httpRequest - .getAttribute(AccessConstants.LB_INPUT_BUFFER); - - if (inputBuffer != null) { - requestContent = new String(inputBuffer); - } - - if (requestContent == null || requestContent.length() == 0) { - requestContent = EMPTY; - } - } - - return requestContent; - } - - public String getResponseContent() { - if (responseContent != null) { - return responseContent; - } - - if (Util.isImageResponse(httpResponse)) { - responseContent = "[IMAGE CONTENTS SUPPRESSED]"; - } else { - - // retreive the byte array previously placed by TeeFilter - byte[] outputBuffer = (byte[]) httpRequest - .getAttribute(AccessConstants.LB_OUTPUT_BUFFER); - - if (outputBuffer != null) { - responseContent = new String(outputBuffer); - } - if (responseContent == null || responseContent.length() == 0) { - responseContent = EMPTY; - } - } - - return responseContent; - } - - public int getLocalPort() { - if (localPort == SENTINEL) { - if (httpRequest != null) { - localPort = httpRequest.getLocalPort(); - } - - } - return localPort; - } - - public ServerAdapter getServerAdapter() { - return serverAdapter; - } - - public String getResponseHeader(String key) { - buildResponseHeaderMap(); - return responseHeaderMap.get(key); - } - - void buildResponseHeaderMap() { - if (responseHeaderMap == null) { - responseHeaderMap = serverAdapter.buildResponseHeaderMap(); - } - } - - public Map getResponseHeaderMap() { - buildResponseHeaderMap(); - return responseHeaderMap; - } - - public List getResponseHeaderNameList() { - buildResponseHeaderMap(); - return new ArrayList(responseHeaderMap.keySet()); - } - - public void prepareForDeferredProcessing() { - getRequestHeaderMap(); - getRequestParameterMap(); - getResponseHeaderMap(); - getLocalPort(); - getMethod(); - getProtocol(); - getRemoteAddr(); - getRemoteHost(); - getRemoteUser(); - getRequestURI(); - getRequestURL(); - getServerName(); - getTimeStamp(); - getElapsedTime(); - - getStatusCode(); - getContentLength(); - getRequestContent(); - getResponseContent(); - - copyAttributeMap(); - } + // retreive the byte array previously placed by TeeFilter + byte[] outputBuffer = (byte[]) httpRequest.getAttribute(AccessConstants.LB_OUTPUT_BUFFER); + + if (outputBuffer != null) { + responseContent = new String(outputBuffer); + } + if (responseContent == null || responseContent.length() == 0) { + responseContent = EMPTY; + } + } + + return responseContent; + } + + public int getLocalPort() { + if (localPort == SENTINEL) { + if (httpRequest != null) { + localPort = httpRequest.getLocalPort(); + } + + } + return localPort; + } + + public ServerAdapter getServerAdapter() { + return serverAdapter; + } + + public String getResponseHeader(String key) { + buildResponseHeaderMap(); + return responseHeaderMap.get(key); + } + + void buildResponseHeaderMap() { + if (responseHeaderMap == null) { + responseHeaderMap = serverAdapter.buildResponseHeaderMap(); + } + } + + public Map getResponseHeaderMap() { + buildResponseHeaderMap(); + return responseHeaderMap; + } + + public List getResponseHeaderNameList() { + buildResponseHeaderMap(); + return new ArrayList(responseHeaderMap.keySet()); + } + + public void prepareForDeferredProcessing() { + getRequestHeaderMap(); + getRequestParameterMap(); + getResponseHeaderMap(); + getLocalPort(); + getMethod(); + getProtocol(); + getRemoteAddr(); + getRemoteHost(); + getRemoteUser(); + getRequestURI(); + getRequestURL(); + getServerName(); + getTimeStamp(); + getElapsedTime(); + + getStatusCode(); + getContentLength(); + getRequestContent(); + getResponseContent(); + + copyAttributeMap(); + } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/spi/IAccessEvent.java b/logback-access/src/main/java/ch/qos/logback/access/spi/IAccessEvent.java index 049e8fe413d00a3b1fcf0acc2c6f70af3b46dfcb..969889b17bd0eae9566fa67bc8b38e0970d8c487 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/spi/IAccessEvent.java +++ b/logback-access/src/main/java/ch/qos/logback/access/spi/IAccessEvent.java @@ -35,84 +35,84 @@ import java.util.Map; */ public interface IAccessEvent extends DeferredProcessingAware { - String NA = "-"; - int SENTINEL = -1; + String NA = "-"; + int SENTINEL = -1; - /** - * Returns the underlying HttpServletRequest. After serialization the returned - * value will be null. - * - * @return - */ - HttpServletRequest getRequest(); + /** + * Returns the underlying HttpServletRequest. After serialization the returned + * value will be null. + * + * @return + */ + HttpServletRequest getRequest(); - /** - * Returns the underlying HttpServletResponse. After serialization the returned - * value will be null. - * - * @return - */ - HttpServletResponse getResponse(); + /** + * Returns the underlying HttpServletResponse. After serialization the returned + * value will be null. + * + * @return + */ + HttpServletResponse getResponse(); - /** - * The number of milliseconds elapsed from 1/1/1970 until logging event was - * created. - */ - long getTimeStamp(); + /** + * The number of milliseconds elapsed from 1/1/1970 until logging event was + * created. + */ + long getTimeStamp(); - /** - * The time elapsed between receiving the request and logging it. - */ - long getElapsedTime(); + /** + * The time elapsed between receiving the request and logging it. + */ + long getElapsedTime(); - String getRequestURI(); + String getRequestURI(); - /** - * The first line of the request. - */ - String getRequestURL(); + /** + * The first line of the request. + */ + String getRequestURL(); - String getRemoteHost(); + String getRemoteHost(); - String getRemoteUser(); + String getRemoteUser(); - String getProtocol(); + String getProtocol(); - String getMethod(); + String getMethod(); - String getServerName(); + String getServerName(); - String getRemoteAddr(); + String getRemoteAddr(); - String getRequestHeader(String key); + String getRequestHeader(String key); - Enumeration getRequestHeaderNames(); + Enumeration getRequestHeaderNames(); - Map getRequestHeaderMap(); + Map getRequestHeaderMap(); - Map getRequestParameterMap(); + Map getRequestParameterMap(); - String getAttribute(String key); + String getAttribute(String key); - String[] getRequestParameter(String key); + String[] getRequestParameter(String key); - String getCookie(String key); + String getCookie(String key); - long getContentLength(); + long getContentLength(); - int getStatusCode(); + int getStatusCode(); - String getRequestContent(); + String getRequestContent(); - String getResponseContent(); + String getResponseContent(); - int getLocalPort(); + int getLocalPort(); - ServerAdapter getServerAdapter(); + ServerAdapter getServerAdapter(); - String getResponseHeader(String key); + String getResponseHeader(String key); - Map getResponseHeaderMap(); + Map getResponseHeaderMap(); - List getResponseHeaderNameList(); + List getResponseHeaderNameList(); } diff --git a/logback-access/src/main/java/ch/qos/logback/access/spi/ServerAdapter.java b/logback-access/src/main/java/ch/qos/logback/access/spi/ServerAdapter.java index 7cb93df965cef2e04778f8f50985b429ef365763..72129448edfed5949d068bc746c9a31b5cb6b00a 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/spi/ServerAdapter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/spi/ServerAdapter.java @@ -24,8 +24,11 @@ import java.util.Map; */ public interface ServerAdapter { - long getRequestTimestamp(); - long getContentLength(); - int getStatusCode(); - Map buildResponseHeaderMap(); + long getRequestTimestamp(); + + long getContentLength(); + + int getStatusCode(); + + Map buildResponseHeaderMap(); } diff --git a/logback-access/src/main/java/ch/qos/logback/access/spi/Util.java b/logback-access/src/main/java/ch/qos/logback/access/spi/Util.java index c3b1efeacf6759ce67d220715998b4dfa7d8eba5..815ec60514c7e8f92bf49bfc9446379615f6e1ae 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/spi/Util.java +++ b/logback-access/src/main/java/ch/qos/logback/access/spi/Util.java @@ -18,18 +18,18 @@ import java.io.IOException; import java.io.InputStream; public class Util { - static final int BUF_SIZE= 128; - - public static String readToString(InputStream in) throws IOException { - if(in == null) { - return null; - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buf = new byte[BUF_SIZE]; - int n = 0; - while( (n = in.read(buf, 0, BUF_SIZE)) != -1) { - baos.write(buf, 0, n); + static final int BUF_SIZE = 128; + + public static String readToString(InputStream in) throws IOException { + if (in == null) { + return null; + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[BUF_SIZE]; + int n = 0; + while ((n = in.read(buf, 0, BUF_SIZE)) != -1) { + baos.write(buf, 0, n); + } + return baos.toString(); } - return baos.toString(); - } } diff --git a/logback-access/src/main/java/ch/qos/logback/access/tomcat/LogbackValve.java b/logback-access/src/main/java/ch/qos/logback/access/tomcat/LogbackValve.java index 02fcf2e56413807dc3707d20a2d548a8559cdabd..4dd341b766e28f0836418b8c3d5278d851747c47 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/tomcat/LogbackValve.java +++ b/logback-access/src/main/java/ch/qos/logback/access/tomcat/LogbackValve.java @@ -63,7 +63,6 @@ import ch.qos.logback.core.util.ExecutorServiceUtil; import ch.qos.logback.core.util.Loader; import ch.qos.logback.core.util.OptionHelper; import ch.qos.logback.core.util.StatusListenerConfigHelper; -import ch.qos.logback.core.util.StatusPrinter; //import org.apache.catalina.Lifecycle; diff --git a/logback-access/src/main/java/ch/qos/logback/access/tomcat/TomcatServerAdapter.java b/logback-access/src/main/java/ch/qos/logback/access/tomcat/TomcatServerAdapter.java index f7d0e7a45d40d7072965ac468753c6cd3bc1695a..a08f572c944c3ce4419adc0a5c40195a7bbba260 100644 --- a/logback-access/src/main/java/ch/qos/logback/access/tomcat/TomcatServerAdapter.java +++ b/logback-access/src/main/java/ch/qos/logback/access/tomcat/TomcatServerAdapter.java @@ -28,36 +28,36 @@ import java.util.Map; */ public class TomcatServerAdapter implements ServerAdapter { - Request request; - Response response; - - public TomcatServerAdapter(Request tomcatRequest, Response tomcatResponse) { - this.request = tomcatRequest; - this.response = tomcatResponse; - } - - @Override - public long getContentLength() { - return response.getContentLength(); - } - - @Override - public int getStatusCode() { - return response.getStatus(); - } - - @Override - public long getRequestTimestamp() { - return request.getCoyoteRequest().getStartTime(); - } - - @Override - public Map buildResponseHeaderMap() { - Map responseHeaderMap = new HashMap(); - for (String key : response.getHeaderNames()) { - String value = response.getHeader(key); - responseHeaderMap.put(key, value); + Request request; + Response response; + + public TomcatServerAdapter(Request tomcatRequest, Response tomcatResponse) { + this.request = tomcatRequest; + this.response = tomcatResponse; + } + + @Override + public long getContentLength() { + return response.getContentLength(); + } + + @Override + public int getStatusCode() { + return response.getStatus(); + } + + @Override + public long getRequestTimestamp() { + return request.getCoyoteRequest().getStartTime(); + } + + @Override + public Map buildResponseHeaderMap() { + Map responseHeaderMap = new HashMap(); + for (String key : response.getHeaderNames()) { + String value = response.getHeader(key); + responseHeaderMap.put(key, value); + } + return responseHeaderMap; } - return responseHeaderMap; - } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/AccessTestConstants.java b/logback-access/src/test/java/ch/qos/logback/access/AccessTestConstants.java index 1213f2ff5e9a1403891cb3013648b035b56f1b2d..ea5b625b5d61ba424336d5d6db635cd3df2103e1 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/AccessTestConstants.java +++ b/logback-access/src/test/java/ch/qos/logback/access/AccessTestConstants.java @@ -14,8 +14,8 @@ package ch.qos.logback.access; public class AccessTestConstants { - - public static final String TEST_DIR_PREFIX = "src/test/"; - final static public String INPUT_PREFIX = "src/test/input/"; - final static public String JORAN_INPUT_PREFIX = INPUT_PREFIX + "joran/"; + + public static final String TEST_DIR_PREFIX = "src/test/"; + final static public String INPUT_PREFIX = "src/test/input/"; + final static public String JORAN_INPUT_PREFIX = INPUT_PREFIX + "joran/"; } diff --git a/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java b/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java index 7782e2bdb7fb7deee4cbb9b20c7cd7892b355c96..32ca8fe4d24cc15c7c72f948f91b74bd4a806aef 100755 --- a/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/AllAccessTest.java @@ -18,16 +18,10 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ch.qos.logback.access.spi.PackageTest.class, - ch.qos.logback.access.boolex.PackageTest.class, - ch.qos.logback.access.net.PackageTest.class, - ch.qos.logback.access.db.PackageTest.class, - ch.qos.logback.access.pattern.PackageTest.class, - ch.qos.logback.access.joran.PackageTest.class, - ch.qos.logback.access.jetty.PackageTest.class, - ch.qos.logback.access.filter.PackageTest.class, - ch.qos.logback.access.servlet.PackageTest.class, - ch.qos.logback.access.sift.PackageTest.class}) +@SuiteClasses({ ch.qos.logback.access.spi.PackageTest.class, ch.qos.logback.access.boolex.PackageTest.class, ch.qos.logback.access.net.PackageTest.class, + ch.qos.logback.access.db.PackageTest.class, ch.qos.logback.access.pattern.PackageTest.class, ch.qos.logback.access.joran.PackageTest.class, + ch.qos.logback.access.jetty.PackageTest.class, ch.qos.logback.access.filter.PackageTest.class, ch.qos.logback.access.servlet.PackageTest.class, + ch.qos.logback.access.sift.PackageTest.class }) public class AllAccessTest { } diff --git a/logback-access/src/test/java/ch/qos/logback/access/boolex/JaninoEventEvaluatorTest.java b/logback-access/src/test/java/ch/qos/logback/access/boolex/JaninoEventEvaluatorTest.java index 6334ac37e77acdd69920e6048bc5c1ab8c4799a9..bb5dc3d9e7c50531d6ceaea1d81726edd3f86a52 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/boolex/JaninoEventEvaluatorTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/boolex/JaninoEventEvaluatorTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.access.boolex; - import ch.qos.logback.access.dummy.DummyRequest; import ch.qos.logback.access.dummy.DummyResponse; import ch.qos.logback.access.dummy.DummyServerAdapter; @@ -30,50 +29,48 @@ import static org.junit.Assert.fail; public class JaninoEventEvaluatorTest { - final String expectedURL1 = "testUrl1"; - final String expectedURL2 = "testUrl2"; - Context context = new ContextBase(); - JaninoEventEvaluator evaluator; - DummyRequest request; - DummyResponse response; - DummyServerAdapter serverAdapter; - - @Before - public void setUp() throws Exception { - evaluator = new JaninoEventEvaluator(); - evaluator.setContext(context); - request = new DummyRequest(); - response = new DummyResponse(); - serverAdapter = new DummyServerAdapter(request, response); - } + final String expectedURL1 = "testUrl1"; + final String expectedURL2 = "testUrl2"; + Context context = new ContextBase(); + JaninoEventEvaluator evaluator; + DummyRequest request; + DummyResponse response; + DummyServerAdapter serverAdapter; + @Before + public void setUp() throws Exception { + evaluator = new JaninoEventEvaluator(); + evaluator.setContext(context); + request = new DummyRequest(); + response = new DummyResponse(); + serverAdapter = new DummyServerAdapter(request, response); + } - @Test - public void smoke() throws EvaluationException { - evaluator.setExpression("event.getProtocol().equals(\"testProtocol\")"); - evaluator.start(); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - assertTrue( evaluator.evaluate(ae)); - } + @Test + public void smoke() throws EvaluationException { + evaluator.setExpression("event.getProtocol().equals(\"testProtocol\")"); + evaluator.start(); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + assertTrue(evaluator.evaluate(ae)); + } - @Test - public void block() throws EvaluationException { - evaluator.setExpression("String protocol = event.getProtocol();" + - "return protocol.equals(\"testProtocol\");"); - evaluator.start(); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - assertTrue(evaluator.evaluate(ae)); - } + @Test + public void block() throws EvaluationException { + evaluator.setExpression("String protocol = event.getProtocol();" + "return protocol.equals(\"testProtocol\");"); + evaluator.start(); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + assertTrue(evaluator.evaluate(ae)); + } - @Test - public void invalidExpression() throws EvaluationException { - evaluator.setExpression("return true"); - evaluator.start(); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - try { - evaluator.evaluate(ae); - fail("Was expecting an exception"); - } catch (IllegalStateException e) { - } - } + @Test + public void invalidExpression() throws EvaluationException { + evaluator.setExpression("return true"); + evaluator.start(); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + try { + evaluator.evaluate(ae); + fail("Was expecting an exception"); + } catch (IllegalStateException e) { + } + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/boolex/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/boolex/PackageTest.java index 6a28a9d71cbca66af47375e874f1b9e25c0de2a3..781c311eef104e4344e4ba97f8e821ace1e5e8ea 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/boolex/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/boolex/PackageTest.java @@ -19,6 +19,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({JaninoEventEvaluatorTest.class}) +@SuiteClasses({ JaninoEventEvaluatorTest.class }) public class PackageTest extends TestCase { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java index f4b6017626c38859df7fa50238ac4d6f8c326fef..ce8dd2c3041b129863ca3ede0149eba059fb28c1 100755 --- a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTest.java @@ -38,187 +38,184 @@ import ch.qos.logback.core.db.DriverManagerConnectionSource; import ch.qos.logback.core.util.StatusPrinter; public class DBAppenderHSQLTest { - static DBAppenderHSQLTestFixture DB_APPENDER_HSQL_TEST_FIXTURE; - - - AccessContext context; - DBAppender appender; - DriverManagerConnectionSource connectionSource; - - int existingEventTableRowCount; - Statement stmt; - - @BeforeClass - static public void fixtureSetUp() throws SQLException { - DB_APPENDER_HSQL_TEST_FIXTURE = new DBAppenderHSQLTestFixture(); - DB_APPENDER_HSQL_TEST_FIXTURE.setUp(); - } - - @AfterClass - static public void fixtureTearDown() throws SQLException { - DB_APPENDER_HSQL_TEST_FIXTURE.tearDown(); - } - - @Before - public void setUp() throws SQLException { - context = new AccessContext(); - context.setName("default"); - appender = new DBAppender(); - appender.setName("DB"); - appender.setContext(context); - connectionSource = new DriverManagerConnectionSource(); - connectionSource.setContext(context); - connectionSource.setDriverClass(DBAppenderHSQLTestFixture.DRIVER_CLASS); - connectionSource.setUrl(DB_APPENDER_HSQL_TEST_FIXTURE.url); - connectionSource.setUser(DB_APPENDER_HSQL_TEST_FIXTURE.user); - connectionSource.setPassword(DB_APPENDER_HSQL_TEST_FIXTURE.password); - connectionSource.start(); - appender.setConnectionSource(connectionSource); - - stmt = connectionSource.getConnection().createStatement(); - existingEventTableRowCount = existingEventTableRowCount(stmt); - } - - @After - public void tearDown() throws SQLException { - context = null; - appender = null; - connectionSource = null; - stmt.close(); - } - - int existingEventTableRowCount(Statement stmt) throws SQLException { - ResultSet rs = stmt.executeQuery("SELECT count(*) FROM access_event"); - int result = -1; - if (rs.next()) { - result = rs.getInt(1); + static DBAppenderHSQLTestFixture DB_APPENDER_HSQL_TEST_FIXTURE; + + AccessContext context; + DBAppender appender; + DriverManagerConnectionSource connectionSource; + + int existingEventTableRowCount; + Statement stmt; + + @BeforeClass + static public void fixtureSetUp() throws SQLException { + DB_APPENDER_HSQL_TEST_FIXTURE = new DBAppenderHSQLTestFixture(); + DB_APPENDER_HSQL_TEST_FIXTURE.setUp(); } - rs.close(); - return result; - } - - private void setInsertHeadersAndStart(boolean insert) { - appender.setInsertHeaders(insert); - appender.start(); - } - - - @Test - public void testAppendAccessEvent() throws SQLException { - setInsertHeadersAndStart(false); - - IAccessEvent event = createAccessEvent(); - appender.append(event); - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM access_event where EVENT_ID = " + existingEventTableRowCount); - if (rs.next()) { - assertEquals(event.getTimeStamp(), rs.getLong(1)); - assertEquals(event.getRequestURI(), rs.getString(2)); - assertEquals(event.getRequestURL(), rs.getString(3)); - assertEquals(event.getRemoteHost(), rs.getString(4)); - assertEquals(event.getRemoteUser(), rs.getString(5)); - assertEquals(event.getRemoteAddr(), rs.getString(6)); - assertEquals(event.getProtocol(), rs.getString(7)); - assertEquals(event.getMethod(), rs.getString(8)); - assertEquals(event.getServerName(), rs.getString(9)); - assertEquals(event.getRequestContent(), rs.getString(10)); - } else { - fail("No row was inserted in the database"); + + @AfterClass + static public void fixtureTearDown() throws SQLException { + DB_APPENDER_HSQL_TEST_FIXTURE.tearDown(); } - rs.close(); - stmt.close(); - } - - - @Test - public void testCheckNoHeadersAreInserted() throws Exception { - setInsertHeadersAndStart(false); - - IAccessEvent event = createAccessEvent(); - appender.append(event); - StatusPrinter.print(context.getStatusManager()); - - //Check that no headers were inserted - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM access_event_header where EVENT_ID = " + existingEventTableRowCount); - - assertFalse(rs.next()); - rs.close(); - stmt.close(); - } - - @Test - public void testAppendHeaders() throws SQLException { - setInsertHeadersAndStart(true); - - IAccessEvent event = createAccessEvent(); - appender.append(event); - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM access_event_header"); - String key; - String value; - if (!rs.next()) { - fail("There should be results to this query"); - } else { - key = rs.getString(2); - value = rs.getString(3); - assertNotNull(key); - assertNotNull(value); - assertEquals(event.getRequestHeader(key), value); - rs.next(); - key = rs.getString(2); - value = rs.getString(3); - assertNotNull(key); - assertNotNull(value); - assertEquals(event.getRequestHeader(key), value); + + @Before + public void setUp() throws SQLException { + context = new AccessContext(); + context.setName("default"); + appender = new DBAppender(); + appender.setName("DB"); + appender.setContext(context); + connectionSource = new DriverManagerConnectionSource(); + connectionSource.setContext(context); + connectionSource.setDriverClass(DBAppenderHSQLTestFixture.DRIVER_CLASS); + connectionSource.setUrl(DB_APPENDER_HSQL_TEST_FIXTURE.url); + connectionSource.setUser(DB_APPENDER_HSQL_TEST_FIXTURE.user); + connectionSource.setPassword(DB_APPENDER_HSQL_TEST_FIXTURE.password); + connectionSource.start(); + appender.setConnectionSource(connectionSource); + + stmt = connectionSource.getConnection().createStatement(); + existingEventTableRowCount = existingEventTableRowCount(stmt); } - if (rs.next()) { - fail("There should be no more rows available"); + + @After + public void tearDown() throws SQLException { + context = null; + appender = null; + connectionSource = null; + stmt.close(); } - rs.close(); - stmt.close(); - } - - @Test - public void testAppendMultipleEvents() throws SQLException { - setInsertHeadersAndStart(false); - String uri = "testAppendMultipleEvents"; - for (int i = 0; i < 10; i++) { - IAccessEvent event = createAccessEvent(uri); - appender.append(event); + int existingEventTableRowCount(Statement stmt) throws SQLException { + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM access_event"); + int result = -1; + if (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + return result; } - StatusPrinter.print(context); + private void setInsertHeadersAndStart(boolean insert) { + appender.setInsertHeaders(insert); + appender.start(); + } - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM access_event where requestURI='" + uri + "'"); - int count = 0; - while (rs.next()) { - count++; + @Test + public void testAppendAccessEvent() throws SQLException { + setInsertHeadersAndStart(false); + + IAccessEvent event = createAccessEvent(); + appender.append(event); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM access_event where EVENT_ID = " + existingEventTableRowCount); + if (rs.next()) { + assertEquals(event.getTimeStamp(), rs.getLong(1)); + assertEquals(event.getRequestURI(), rs.getString(2)); + assertEquals(event.getRequestURL(), rs.getString(3)); + assertEquals(event.getRemoteHost(), rs.getString(4)); + assertEquals(event.getRemoteUser(), rs.getString(5)); + assertEquals(event.getRemoteAddr(), rs.getString(6)); + assertEquals(event.getProtocol(), rs.getString(7)); + assertEquals(event.getMethod(), rs.getString(8)); + assertEquals(event.getServerName(), rs.getString(9)); + assertEquals(event.getRequestContent(), rs.getString(10)); + } else { + fail("No row was inserted in the database"); + } + rs.close(); + stmt.close(); } - assertEquals(10, count); - rs.close(); - stmt.close(); - } + @Test + public void testCheckNoHeadersAreInserted() throws Exception { + setInsertHeadersAndStart(false); - private IAccessEvent createAccessEvent() { - return createAccessEvent(""); - } + IAccessEvent event = createAccessEvent(); + appender.append(event); + StatusPrinter.print(context.getStatusManager()); - private IAccessEvent createAccessEvent(String uri) { - DummyRequest request = new DummyRequest(); - request.setRequestUri(uri); - DummyResponse response = new DummyResponse(); - DummyServerAdapter adapter = new DummyServerAdapter(request, response); + // Check that no headers were inserted + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM access_event_header where EVENT_ID = " + existingEventTableRowCount); + + assertFalse(rs.next()); + rs.close(); + stmt.close(); + } - return new AccessEvent(request, response, adapter); - } + @Test + public void testAppendHeaders() throws SQLException { + setInsertHeadersAndStart(true); + + IAccessEvent event = createAccessEvent(); + appender.append(event); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM access_event_header"); + String key; + String value; + if (!rs.next()) { + fail("There should be results to this query"); + } else { + key = rs.getString(2); + value = rs.getString(3); + assertNotNull(key); + assertNotNull(value); + assertEquals(event.getRequestHeader(key), value); + rs.next(); + key = rs.getString(2); + value = rs.getString(3); + assertNotNull(key); + assertNotNull(value); + assertEquals(event.getRequestHeader(key), value); + } + if (rs.next()) { + fail("There should be no more rows available"); + } + + rs.close(); + stmt.close(); + } + + @Test + public void testAppendMultipleEvents() throws SQLException { + setInsertHeadersAndStart(false); + String uri = "testAppendMultipleEvents"; + for (int i = 0; i < 10; i++) { + IAccessEvent event = createAccessEvent(uri); + appender.append(event); + } + + StatusPrinter.print(context); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM access_event where requestURI='" + uri + "'"); + int count = 0; + while (rs.next()) { + count++; + } + assertEquals(10, count); + + rs.close(); + stmt.close(); + } + + private IAccessEvent createAccessEvent() { + return createAccessEvent(""); + } + + private IAccessEvent createAccessEvent(String uri) { + DummyRequest request = new DummyRequest(); + request.setRequestUri(uri); + DummyResponse response = new DummyResponse(); + DummyServerAdapter adapter = new DummyServerAdapter(request, response); + + return new AccessEvent(request, response, adapter); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java index ca24b26dcd69409785ebaa6be50ce61a479eed32..69325d330f6f6883913038d8c6e6e39b6d72b138 100755 --- a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderHSQLTestFixture.java @@ -22,107 +22,106 @@ import org.hsqldb.Server; public class DBAppenderHSQLTestFixture { - public static final String DRIVER_CLASS = "org.hsqldb.jdbcDriver"; - String serverProps; - String url; - String user = "sa"; - String password = ""; - Server server; - boolean isNetwork = true; - - - void setUp() throws SQLException { - if (isNetwork) { - if (url == null) { - url = "jdbc:hsqldb:hsql://localhost/test"; - } - - server = new Server(); - - server.setDatabaseName(0, "test"); - server.setDatabasePath(0, "mem:test;sql.enforce_strict_size=true"); - server.setLogWriter(null); - server.setErrWriter(null); - server.setTrace(false); - server.setSilent(true); - server.start(); - } else { - if (url == null) { - url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; - } + public static final String DRIVER_CLASS = "org.hsqldb.jdbcDriver"; + String serverProps; + String url; + String user = "sa"; + String password = ""; + Server server; + boolean isNetwork = true; + + void setUp() throws SQLException { + if (isNetwork) { + if (url == null) { + url = "jdbc:hsqldb:hsql://localhost/test"; + } + + server = new Server(); + + server.setDatabaseName(0, "test"); + server.setDatabasePath(0, "mem:test;sql.enforce_strict_size=true"); + server.setLogWriter(null); + server.setErrWriter(null); + server.setTrace(false); + server.setSilent(true); + server.start(); + } else { + if (url == null) { + url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; + } + } + + try { + Class.forName(DRIVER_CLASS); + } catch (Exception e) { + e.printStackTrace(); + System.out.println(this + ".setUp() error: " + e.getMessage()); + } + Thread.yield(); + + createTables(); } - try { - Class.forName(DRIVER_CLASS); - } catch (Exception e) { - e.printStackTrace(); - System.out.println(this + ".setUp() error: " + e.getMessage()); + void tearDown() throws SQLException { + dropTables(); + if (isNetwork) { + server.stop(); + server = null; + } } - Thread.yield(); - - createTables(); - } - - void tearDown() throws SQLException { - dropTables(); - if (isNetwork) { - server.stop(); - server = null; + + Connection newConnection() throws SQLException { + return DriverManager.getConnection(url, user, password); } - } - - Connection newConnection() throws SQLException { - return DriverManager.getConnection(url, user, password); - } - - private void createTables() throws SQLException { - Connection conn = newConnection(); - StringBuilder buf = new StringBuilder(); - buf.append("CREATE TABLE access_event ("); - buf.append("timestmp BIGINT NOT NULL,"); - buf.append("requestURI VARCHAR(254),"); - buf.append("requestURL VARCHAR(254),"); - buf.append("remoteHost VARCHAR(254),"); - buf.append("remoteUser VARCHAR(254),"); - buf.append("remoteAddr VARCHAR(254),"); - buf.append("protocol VARCHAR(254),"); - buf.append("method VARCHAR(254),"); - buf.append("serverName VARCHAR(254),"); - buf.append("postContent VARCHAR(254),"); - buf.append("event_id INT NOT NULL IDENTITY);"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("CREATE TABLE access_event_header ("); - buf.append("event_id INT NOT NULL,"); - buf.append("header_key VARCHAR(254) NOT NULL,"); - buf.append("header_value LONGVARCHAR,"); - buf.append("PRIMARY KEY(event_id, header_key),"); - buf.append("FOREIGN KEY (event_id) REFERENCES access_event(event_id));"); - query(conn, buf.toString()); - } - - private void dropTables() throws SQLException { - Connection conn = newConnection(); - - StringBuilder buf = new StringBuilder(); - buf.append("DROP TABLE access_event_header IF EXISTS;"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("DROP TABLE access_event IF EXISTS;"); - query(conn, buf.toString()); - } - - private void query(Connection conn, String expression) throws SQLException { - Statement st = null; - st = conn.createStatement(); - - int i = st.executeUpdate(expression); - if (i == -1) { - System.out.println("db error : " + expression); + + private void createTables() throws SQLException { + Connection conn = newConnection(); + StringBuilder buf = new StringBuilder(); + buf.append("CREATE TABLE access_event ("); + buf.append("timestmp BIGINT NOT NULL,"); + buf.append("requestURI VARCHAR(254),"); + buf.append("requestURL VARCHAR(254),"); + buf.append("remoteHost VARCHAR(254),"); + buf.append("remoteUser VARCHAR(254),"); + buf.append("remoteAddr VARCHAR(254),"); + buf.append("protocol VARCHAR(254),"); + buf.append("method VARCHAR(254),"); + buf.append("serverName VARCHAR(254),"); + buf.append("postContent VARCHAR(254),"); + buf.append("event_id INT NOT NULL IDENTITY);"); + query(conn, buf.toString()); + + buf = new StringBuilder(); + buf.append("CREATE TABLE access_event_header ("); + buf.append("event_id INT NOT NULL,"); + buf.append("header_key VARCHAR(254) NOT NULL,"); + buf.append("header_value LONGVARCHAR,"); + buf.append("PRIMARY KEY(event_id, header_key),"); + buf.append("FOREIGN KEY (event_id) REFERENCES access_event(event_id));"); + query(conn, buf.toString()); } - st.close(); - } + private void dropTables() throws SQLException { + Connection conn = newConnection(); + + StringBuilder buf = new StringBuilder(); + buf.append("DROP TABLE access_event_header IF EXISTS;"); + query(conn, buf.toString()); + + buf = new StringBuilder(); + buf.append("DROP TABLE access_event IF EXISTS;"); + query(conn, buf.toString()); + } + + private void query(Connection conn, String expression) throws SQLException { + Statement st = null; + st = conn.createStatement(); + + int i = st.executeUpdate(expression); + if (i == -1) { + System.out.println("db error : " + expression); + } + + st.close(); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderIntegrationTest.java b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderIntegrationTest.java index 2989ac4233033d45c8a35451890f451aa274820a..340b57c91ced578f4881ff2935861a88578b4de8 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderIntegrationTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/DBAppenderIntegrationTest.java @@ -38,101 +38,101 @@ import ch.qos.logback.core.util.StatusPrinter; public class DBAppenderIntegrationTest { - static String LOCAL_HOST_NAME = EnvUtilForTests.getLocalHostName(); - static String[] CONFORMING_HOST_LIST = new String[] { "Orion" }; - - int diff = new Random(System.nanoTime()).nextInt(10000); - AccessContext context = new AccessContext(); - StatusChecker statusChecker = new StatusChecker(context); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - - } - - public void doTest(String configFile) throws JoranException { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(context); - configurator.doConfigure(configFile); - - Appender appender = context.getAppender("DB"); - - for (int i = 0; i < 10; i++) { - IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); - appender.doAppend(event); + static String LOCAL_HOST_NAME = EnvUtilForTests.getLocalHostName(); + static String[] CONFORMING_HOST_LIST = new String[] { "Orion" }; + + int diff = new Random(System.nanoTime()).nextInt(10000); + AccessContext context = new AccessContext(); + StatusChecker statusChecker = new StatusChecker(context); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { } - - StatusPrinter.print(context); - - // check that there were no errors - assertEquals(Status.INFO, statusChecker.getHighestLevel(0)); - - } - - static boolean isConformingHostAndJDK16OrHigher() { - if(!EnvUtil.isJDK6OrHigher()) { - return false; + + @AfterClass + public static void tearDownAfterClass() throws Exception { } - return EnvUtilForTests.isLocalHostNameInList(CONFORMING_HOST_LIST); - } - - @Test - public void sqlserver() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; + + @Before + public void setUp() throws Exception { } - doTest("src/test/input/integration/db/sqlserver-with-driver.xml"); - } - - @Test - @Ignore - public void oracle10g() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; + + @After + public void tearDown() throws Exception { + } - doTest("src/test/input/integration/db/oracle10g-with-driver.xml"); - } - - @Test - @Ignore - public void oracle11g() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; + + public void doTest(String configFile) throws JoranException { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(context); + configurator.doConfigure(configFile); + + Appender appender = context.getAppender("DB"); + + for (int i = 0; i < 10; i++) { + IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); + appender.doAppend(event); + } + + StatusPrinter.print(context); + + // check that there were no errors + assertEquals(Status.INFO, statusChecker.getHighestLevel(0)); + } - doTest("src/test/input/integration/db/oracle11g-with-driver.xml"); - } - - @Test - public void mysql() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; + + static boolean isConformingHostAndJDK16OrHigher() { + if (!EnvUtil.isJDK6OrHigher()) { + return false; + } + return EnvUtilForTests.isLocalHostNameInList(CONFORMING_HOST_LIST); + } + + @Test + public void sqlserver() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/sqlserver-with-driver.xml"); } - doTest("src/test/input/integration/db/mysql-with-driver.xml"); - } - - @Test - public void postgres() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; + + @Test + @Ignore + public void oracle10g() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/oracle10g-with-driver.xml"); + } + + @Test + @Ignore + public void oracle11g() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/oracle11g-with-driver.xml"); } - doTest("src/test/input/integration/db/postgresql-with-driver.xml"); - } - + + @Test + public void mysql() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/mysql-with-driver.xml"); + } + + @Test + public void postgres() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/postgresql-with-driver.xml"); + } + } diff --git a/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java index 13f2af5a458187f21740cb802d9f6f9dfdbd5345..35a4c380c73775f7f539fd1892b6dd6f27e5730b 100755 --- a/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/db/PackageTest.java @@ -17,7 +17,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({DBAppenderHSQLTest.class, DBAppenderIntegrationTest.class}) -public class PackageTest { +@Suite.SuiteClasses({ DBAppenderHSQLTest.class, DBAppenderIntegrationTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyAccessEventBuilder.java b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyAccessEventBuilder.java index 840459fcf28e63341cb085370fae33e02f87461e..2f050c242c534e0579810b7ea3c871e6291d399f 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyAccessEventBuilder.java +++ b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyAccessEventBuilder.java @@ -18,13 +18,12 @@ import ch.qos.logback.access.spi.IAccessEvent; public class DummyAccessEventBuilder { - - static public IAccessEvent buildNewAccessEvent() { - DummyRequest request = new DummyRequest(); - DummyResponse response = new DummyResponse(); - DummyServerAdapter adapter = new DummyServerAdapter(request, response); - - return new AccessEvent(request, response, adapter); - } - + static public IAccessEvent buildNewAccessEvent() { + DummyRequest request = new DummyRequest(); + DummyResponse response = new DummyResponse(); + DummyServerAdapter adapter = new DummyServerAdapter(request, response); + + return new AccessEvent(request, response, adapter); + } + } diff --git a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyRequest.java b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyRequest.java index 9710d6bc1d44722b0f8bca835c4335c9620d0c1d..c50f5888cb16d838a05fe3305176852164f3dbc3 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyRequest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyRequest.java @@ -25,297 +25,296 @@ import java.util.*; public class DummyRequest implements HttpServletRequest { - public final static String DUMMY_CONTENT_STRING = "request contents"; - public final static byte[] DUMMY_CONTENT_BYTES = DUMMY_CONTENT_STRING.getBytes(); + public final static String DUMMY_CONTENT_STRING = "request contents"; + public final static byte[] DUMMY_CONTENT_BYTES = DUMMY_CONTENT_STRING.getBytes(); - public static final Map DUMMY_DEFAULT_ATTR_MAP = new HashMap(); - - public static final String DUMMY_RESPONSE_CONTENT_STRING = "response contents"; - public static final byte[] DUMMY_RESPONSE_CONTENT_BYTES =DUMMY_RESPONSE_CONTENT_STRING.getBytes(); - - Hashtable headerNames; - String uri; - Map attributes; - - static { - DUMMY_DEFAULT_ATTR_MAP.put("testKey", "testKey"); - DUMMY_DEFAULT_ATTR_MAP.put(AccessConstants.LB_INPUT_BUFFER, DUMMY_CONTENT_BYTES); - DUMMY_DEFAULT_ATTR_MAP.put(AccessConstants.LB_OUTPUT_BUFFER, DUMMY_RESPONSE_CONTENT_BYTES); - } - - public DummyRequest() { - headerNames = new Hashtable(); - headerNames.put("headerName1", "headerValue1"); - headerNames.put("headerName2", "headerValue2"); + public static final Map DUMMY_DEFAULT_ATTR_MAP = new HashMap(); - attributes = new HashMap(DUMMY_DEFAULT_ATTR_MAP); - } - - public String getAuthType() { - return null; - } - - public String getContextPath() { - return null; - } - - public Cookie[] getCookies() { - Cookie cookie = new Cookie("testName", "testCookie"); - return new Cookie[] { cookie }; - } + public static final String DUMMY_RESPONSE_CONTENT_STRING = "response contents"; + public static final byte[] DUMMY_RESPONSE_CONTENT_BYTES = DUMMY_RESPONSE_CONTENT_STRING.getBytes(); - public long getDateHeader(String arg0) { - return 0; - } + Hashtable headerNames; + String uri; + Map attributes; - public String getHeader(String key) { - return headerNames.get(key); - } + static { + DUMMY_DEFAULT_ATTR_MAP.put("testKey", "testKey"); + DUMMY_DEFAULT_ATTR_MAP.put(AccessConstants.LB_INPUT_BUFFER, DUMMY_CONTENT_BYTES); + DUMMY_DEFAULT_ATTR_MAP.put(AccessConstants.LB_OUTPUT_BUFFER, DUMMY_RESPONSE_CONTENT_BYTES); + } - public Enumeration getHeaderNames() { - return headerNames.keys(); - } + public DummyRequest() { + headerNames = new Hashtable(); + headerNames.put("headerName1", "headerValue1"); + headerNames.put("headerName2", "headerValue2"); - public Enumeration getHeaders(String arg0) { - return null; - } + attributes = new HashMap(DUMMY_DEFAULT_ATTR_MAP); + } - public int getIntHeader(String arg0) { - return 0; - } + public String getAuthType() { + return null; + } - public String getMethod() { - return "testMethod"; - } + public String getContextPath() { + return null; + } - public String getPathInfo() { - return null; - } + public Cookie[] getCookies() { + Cookie cookie = new Cookie("testName", "testCookie"); + return new Cookie[] { cookie }; + } - public String getPathTranslated() { - return null; - } + public long getDateHeader(String arg0) { + return 0; + } - public String getQueryString() { - return null; - } + public String getHeader(String key) { + return headerNames.get(key); + } - public String getRemoteUser() { - return "testUser"; - } + public Enumeration getHeaderNames() { + return headerNames.keys(); + } - public String getRequestURI() { - return uri; - } + public Enumeration getHeaders(String arg0) { + return null; + } - public StringBuffer getRequestURL() { - return new StringBuffer(uri); - } + public int getIntHeader(String arg0) { + return 0; + } - public String getRequestedSessionId() { - return null; - } + public String getMethod() { + return "testMethod"; + } - public String getServletPath() { - return null; - } + public String getPathInfo() { + return null; + } - public HttpSession getSession() { - return null; - } + public String getPathTranslated() { + return null; + } - public HttpSession getSession(boolean arg0) { - return null; - } + public String getQueryString() { + return null; + } - public Principal getUserPrincipal() { - return null; - } - - public boolean isRequestedSessionIdFromCookie() { - return false; - } + public String getRemoteUser() { + return "testUser"; + } - public boolean isRequestedSessionIdFromURL() { - return false; - } + public String getRequestURI() { + return uri; + } - public boolean isRequestedSessionIdFromUrl() { - return false; - } + public StringBuffer getRequestURL() { + return new StringBuffer(uri); + } - public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { - return false; //To change body of implemented methods use File | Settings | File Templates. - } + public String getRequestedSessionId() { + return null; + } - public void login(String username, String password) throws ServletException { - //To change body of implemented methods use File | Settings | File Templates. - } + public String getServletPath() { + return null; + } - public void logout() throws ServletException { - //To change body of implemented methods use File | Settings | File Templates. - } + public HttpSession getSession() { + return null; + } - public Collection getParts() throws IOException, IllegalStateException, ServletException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public HttpSession getSession(boolean arg0) { + return null; + } - public Part getPart(String name) throws IOException, IllegalStateException, ServletException { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public Principal getUserPrincipal() { + return null; + } - public boolean isRequestedSessionIdValid() { - return false; - } + public boolean isRequestedSessionIdFromCookie() { + return false; + } - public boolean isUserInRole(String arg0) { - return false; - } + public boolean isRequestedSessionIdFromURL() { + return false; + } - public Object getAttribute(String key) { - return attributes.get(key); - } + public boolean isRequestedSessionIdFromUrl() { + return false; + } - public Enumeration getAttributeNames() { - return Collections.enumeration(attributes.keySet()); - } + public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { + return false; // To change body of implemented methods use File | Settings | File Templates. + } - public String getCharacterEncoding() { - return null; - } + public void login(String username, String password) throws ServletException { + // To change body of implemented methods use File | Settings | File Templates. + } - public int getContentLength() { - return 0; - } + public void logout() throws ServletException { + // To change body of implemented methods use File | Settings | File Templates. + } - public String getContentType() { - return null; - } + public Collection getParts() throws IOException, IllegalStateException, ServletException { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public ServletInputStream getInputStream() throws IOException { - return null; - } + public Part getPart(String name) throws IOException, IllegalStateException, ServletException { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public String getLocalAddr() { - return null; - } + public boolean isRequestedSessionIdValid() { + return false; + } - public String getLocalName() { - return null; - } + public boolean isUserInRole(String arg0) { + return false; + } - public int getLocalPort() { - return 11; - } + public Object getAttribute(String key) { + return attributes.get(key); + } - public ServletContext getServletContext() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public Enumeration getAttributeNames() { + return Collections.enumeration(attributes.keySet()); + } - public AsyncContext startAsync() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public String getCharacterEncoding() { + return null; + } - public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public int getContentLength() { + return 0; + } - public boolean isAsyncStarted() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } + public String getContentType() { + return null; + } - public boolean isAsyncSupported() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } + public ServletInputStream getInputStream() throws IOException { + return null; + } - public AsyncContext getAsyncContext() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public String getLocalAddr() { + return null; + } - public DispatcherType getDispatcherType() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + public String getLocalName() { + return null; + } - public Locale getLocale() { - return null; - } + public int getLocalPort() { + return 11; + } - public Enumeration getLocales() { - return null; - } + public ServletContext getServletContext() { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public String getParameter(String arg0) { - return null; - } + public AsyncContext startAsync() { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public Map getParameterMap() { - return null; - } + public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public Enumeration getParameterNames() { - return null; - } + public boolean isAsyncStarted() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } - public String[] getParameterValues(String arg0) { - return null; - } + public boolean isAsyncSupported() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } - public String getProtocol() { - return "testProtocol"; - } + public AsyncContext getAsyncContext() { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public BufferedReader getReader() throws IOException { - return null; - } + public DispatcherType getDispatcherType() { + return null; // To change body of implemented methods use File | Settings | File Templates. + } - public String getRealPath(String arg0) { - return null; - } + public Locale getLocale() { + return null; + } - public String getRemoteAddr() { - return "testRemoteAddress"; - } + public Enumeration getLocales() { + return null; + } - public String getRemoteHost() { - return "testHost"; - } + public String getParameter(String arg0) { + return null; + } - public int getRemotePort() { - return 0; - } + public Map getParameterMap() { + return null; + } - public RequestDispatcher getRequestDispatcher(String arg0) { - return null; - } + public Enumeration getParameterNames() { + return null; + } - public String getScheme() { - return null; - } + public String[] getParameterValues(String arg0) { + return null; + } - public String getServerName() { - return "testServerName"; - } + public String getProtocol() { + return "testProtocol"; + } - public int getServerPort() { - return 0; - } + public BufferedReader getReader() throws IOException { + return null; + } - public boolean isSecure() { - return false; - } + public String getRealPath(String arg0) { + return null; + } - public void removeAttribute(String arg0) { - } - - public void setAttribute(String name, Object value) { - attributes.put(name, value); - } - - public void setCharacterEncoding(String arg0) - throws UnsupportedEncodingException { - } - - public void setRequestUri(String uri) { - this.uri = uri; - } + public String getRemoteAddr() { + return "testRemoteAddress"; + } + + public String getRemoteHost() { + return "testHost"; + } + + public int getRemotePort() { + return 0; + } + + public RequestDispatcher getRequestDispatcher(String arg0) { + return null; + } + + public String getScheme() { + return null; + } + + public String getServerName() { + return "testServerName"; + } + + public int getServerPort() { + return 0; + } + + public boolean isSecure() { + return false; + } + + public void removeAttribute(String arg0) { + } + + public void setAttribute(String name, Object value) { + attributes.put(name, value); + } + + public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { + } + + public void setRequestUri(String uri) { + this.uri = uri; + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyResponse.java b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyResponse.java index dc0c879511d51fceaa7c041f154d47ad2e6d0600..5dd2a3fce87a9399addce0d0a403d6aaed8ecf08 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyResponse.java +++ b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyResponse.java @@ -23,162 +23,161 @@ import javax.servlet.http.HttpServletResponse; public class DummyResponse implements HttpServletResponse { - public static final int DUMMY_DEFAULT_STATUS = 200; - public static final int DUMMY_DEFAULT_CONTENT_COUNT = 1000; - public static final Map DUMMY_DEFAULT_HDEADER_MAP = new HashMap(); - ; + public static final int DUMMY_DEFAULT_STATUS = 200; + public static final int DUMMY_DEFAULT_CONTENT_COUNT = 1000; + public static final Map DUMMY_DEFAULT_HDEADER_MAP = new HashMap();; - static { - DUMMY_DEFAULT_HDEADER_MAP.put("headerName1", "headerValue1"); - DUMMY_DEFAULT_HDEADER_MAP.put("headerName2", "headerValue2"); - } + static { + DUMMY_DEFAULT_HDEADER_MAP.put("headerName1", "headerValue1"); + DUMMY_DEFAULT_HDEADER_MAP.put("headerName2", "headerValue2"); + } - int status = DUMMY_DEFAULT_STATUS; - public Map headerMap; + int status = DUMMY_DEFAULT_STATUS; + public Map headerMap; - String characterEncoding = null; - ServletOutputStream outputStream = null; + String characterEncoding = null; + ServletOutputStream outputStream = null; - public DummyResponse() { - headerMap = DUMMY_DEFAULT_HDEADER_MAP; - } + public DummyResponse() { + headerMap = DUMMY_DEFAULT_HDEADER_MAP; + } - public void addCookie(Cookie arg0) { - } + public void addCookie(Cookie arg0) { + } - public void addDateHeader(String arg0, long arg1) { - } + public void addDateHeader(String arg0, long arg1) { + } - public void addHeader(String arg0, String arg1) { - } + public void addHeader(String arg0, String arg1) { + } - public void addIntHeader(String arg0, int arg1) { - } + public void addIntHeader(String arg0, int arg1) { + } - public boolean containsHeader(String arg0) { - return false; - } + public boolean containsHeader(String arg0) { + return false; + } - public String encodeRedirectURL(String arg0) { - return null; - } + public String encodeRedirectURL(String arg0) { + return null; + } - public String encodeRedirectUrl(String arg0) { - return null; - } + public String encodeRedirectUrl(String arg0) { + return null; + } - public String encodeURL(String arg0) { - return null; - } + public String encodeURL(String arg0) { + return null; + } - public String encodeUrl(String arg0) { - return null; - } + public String encodeUrl(String arg0) { + return null; + } - public void sendError(int arg0) throws IOException { - } + public void sendError(int arg0) throws IOException { + } - public void sendError(int arg0, String arg1) throws IOException { - } + public void sendError(int arg0, String arg1) throws IOException { + } - public void sendRedirect(String arg0) throws IOException { - } + public void sendRedirect(String arg0) throws IOException { + } - public void setDateHeader(String arg0, long arg1) { - } + public void setDateHeader(String arg0, long arg1) { + } - public void setHeader(String arg0, String arg1) { - } + public void setHeader(String arg0, String arg1) { + } - public void setIntHeader(String arg0, int arg1) { - } + public void setIntHeader(String arg0, int arg1) { + } - public void setStatus(int arg0, String arg1) { - } + public void setStatus(int arg0, String arg1) { + } - public void flushBuffer() throws IOException { - } + public void flushBuffer() throws IOException { + } - public int getBufferSize() { - return 0; - } + public int getBufferSize() { + return 0; + } - public String getCharacterEncoding() { - return characterEncoding; - } + public String getCharacterEncoding() { + return characterEncoding; + } - public String getContentType() { - return null; - } + public String getContentType() { + return null; + } - public Locale getLocale() { - return null; - } + public Locale getLocale() { + return null; + } - public ServletOutputStream getOutputStream() throws IOException { - return outputStream; - } + public ServletOutputStream getOutputStream() throws IOException { + return outputStream; + } - public void setOutputStream(ServletOutputStream outputStream) { - this.outputStream = outputStream; - } + public void setOutputStream(ServletOutputStream outputStream) { + this.outputStream = outputStream; + } - public PrintWriter getWriter() throws IOException { - return null; - } + public PrintWriter getWriter() throws IOException { + return null; + } - public boolean isCommitted() { - return false; - } + public boolean isCommitted() { + return false; + } - public void reset() { - } + public void reset() { + } - public void resetBuffer() { - } + public void resetBuffer() { + } - public void setBufferSize(int arg0) { - } + public void setBufferSize(int arg0) { + } - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - } + public void setCharacterEncoding(String characterEncoding) { + this.characterEncoding = characterEncoding; + } - public void setContentLength(int arg0) { - } + public void setContentLength(int arg0) { + } - public void setContentType(String arg0) { - } + public void setContentType(String arg0) { + } - public void setLocale(Locale arg0) { - } + public void setLocale(Locale arg0) { + } - public String getHeader(String key) { - return headerMap.get(key); - } + public String getHeader(String key) { + return headerMap.get(key); + } - public Collection getHeaders(String name) { - String val = headerMap.get(name); - List list = new ArrayList(); - if (val != null) - list.add(val); - return list; - } + public Collection getHeaders(String name) { + String val = headerMap.get(name); + List list = new ArrayList(); + if (val != null) + list.add(val); + return list; + } - public Collection getHeaderNames() { - return headerMap.keySet(); - } + public Collection getHeaderNames() { + return headerMap.keySet(); + } - public long getContentCount() { - return DUMMY_DEFAULT_CONTENT_COUNT; - } + public long getContentCount() { + return DUMMY_DEFAULT_CONTENT_COUNT; + } - public int getStatus() { - return status; - } + public int getStatus() { + return status; + } - public void setStatus(int status) { - this.status = status; - } + public void setStatus(int status) { + this.status = status; + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServerAdapter.java b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServerAdapter.java index afeaf3950f836afb8e1dbb94ba6370023fed28ae..7af921da302323f841b096f19ca14e6990de71fd 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServerAdapter.java +++ b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServerAdapter.java @@ -19,28 +19,28 @@ import java.util.Map; public class DummyServerAdapter implements ServerAdapter { - DummyRequest request; - DummyResponse response; + DummyRequest request; + DummyResponse response; - public DummyServerAdapter(DummyRequest dummyRequest, DummyResponse dummyResponse) { - this.request = dummyRequest; - this.response = dummyResponse; - } + public DummyServerAdapter(DummyRequest dummyRequest, DummyResponse dummyResponse) { + this.request = dummyRequest; + this.response = dummyResponse; + } - public long getContentLength() { - return response.getContentCount(); - } + public long getContentLength() { + return response.getContentCount(); + } - public int getStatusCode() { - return response.getStatus(); - } + public int getStatusCode() { + return response.getStatus(); + } - public long getRequestTimestamp() { - return -1; - } + public long getRequestTimestamp() { + return -1; + } - public Map buildResponseHeaderMap() { - return response.headerMap; - } + public Map buildResponseHeaderMap() { + return response.headerMap; + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServletOutputStream.java b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServletOutputStream.java index cb5bf8516330e8a903bfed4c781282d6a7c88fd9..1e66bf6dc7ce2b13ff10098d01e58f9b1369d1f3 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServletOutputStream.java +++ b/logback-access/src/test/java/ch/qos/logback/access/dummy/DummyServletOutputStream.java @@ -19,24 +19,24 @@ import java.io.OutputStream; public class DummyServletOutputStream extends ServletOutputStream { - private final OutputStream targetStream; + private final OutputStream targetStream; - public DummyServletOutputStream(OutputStream targetStream) { - this.targetStream = targetStream; - } + public DummyServletOutputStream(OutputStream targetStream) { + this.targetStream = targetStream; + } - @Override - public void write(int b) throws IOException { - this.targetStream.write(b); - } + @Override + public void write(int b) throws IOException { + this.targetStream.write(b); + } - public void flush() throws IOException { - super.flush(); - this.targetStream.flush(); - } + public void flush() throws IOException { + super.flush(); + this.targetStream.flush(); + } - public void close() throws IOException { - super.close(); - this.targetStream.close(); - } + public void close() throws IOException { + super.close(); + this.targetStream.close(); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/filter/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/filter/PackageTest.java index d6f002c69e0e2cc5ff11d31284733aa0680d5357..9498170d1a0534c37b9506332e4475415a573826 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/filter/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/filter/PackageTest.java @@ -20,6 +20,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({StatsByDayTest.class}) +@SuiteClasses({ StatsByDayTest.class }) public class PackageTest extends TestCase { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/filter/StatsByDayTest.java b/logback-access/src/test/java/ch/qos/logback/access/filter/StatsByDayTest.java index 18d082378942c7adde7a2ea377ce440584ca9c26..a503e8f65bdbd11c872eddc79b2cff1d3e8942fe 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/filter/StatsByDayTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/filter/StatsByDayTest.java @@ -21,56 +21,56 @@ import ch.qos.logback.core.util.TimeUtil; public class StatsByDayTest { - @Test - public void testBasic() { - // Tue Nov 21 18:05:36 CET 2006 - long now = 1164128736369L; - StatsByDay statsByDay = new StatsByDay(now); - - int total = 0; - // test fresh start - statsByDay.update(now, 0); - assertEquals(0, statsByDay.getLastCount()); - assertEquals(0, statsByDay.getAverage(), 0.01); - - total++; - statsByDay.update(now, total); - assertEquals(0, statsByDay.getLastCount()); - assertEquals(0.0, statsByDay.getAverage(), 0.01); - - long nextDay0 = TimeUtil.computeStartOfNextDay(now); - nextDay0 += 99; - - // there should be one event the next day, avg should also be 1 - statsByDay.update(nextDay0, total); - assertEquals(1.0, statsByDay.getLastCount(), 0.01); - assertEquals(1.0, statsByDay.getAverage(), 0.01); - - total += 2; - - statsByDay.update(nextDay0, total); - assertEquals(1, statsByDay.getLastCount()); - assertEquals(1.0, statsByDay.getAverage(), 0.01); - - long nextDay1 = TimeUtil.computeStartOfNextDay(nextDay0) + 6747; - statsByDay.update(nextDay1, total); - assertEquals(2, statsByDay.getLastCount()); - assertEquals(1.5, statsByDay.getAverage(), 0.01); - - nextDay1 += 4444; - total += 4; - - statsByDay.update(nextDay1, total); - // values should remain unchanged - assertEquals(2, statsByDay.getLastCount()); - assertEquals(1.5, statsByDay.getAverage(), 0.01); - - long nextDay2 = TimeUtil.computeStartOfNextDay(nextDay1) + 11177; - - statsByDay.update(nextDay2, total); - // values should remain unchanged - assertEquals(4, statsByDay.getLastCount()); - assertEquals(7.0 / 3, statsByDay.getAverage(), 0.01); - } + @Test + public void testBasic() { + // Tue Nov 21 18:05:36 CET 2006 + long now = 1164128736369L; + StatsByDay statsByDay = new StatsByDay(now); + + int total = 0; + // test fresh start + statsByDay.update(now, 0); + assertEquals(0, statsByDay.getLastCount()); + assertEquals(0, statsByDay.getAverage(), 0.01); + + total++; + statsByDay.update(now, total); + assertEquals(0, statsByDay.getLastCount()); + assertEquals(0.0, statsByDay.getAverage(), 0.01); + + long nextDay0 = TimeUtil.computeStartOfNextDay(now); + nextDay0 += 99; + + // there should be one event the next day, avg should also be 1 + statsByDay.update(nextDay0, total); + assertEquals(1.0, statsByDay.getLastCount(), 0.01); + assertEquals(1.0, statsByDay.getAverage(), 0.01); + + total += 2; + + statsByDay.update(nextDay0, total); + assertEquals(1, statsByDay.getLastCount()); + assertEquals(1.0, statsByDay.getAverage(), 0.01); + + long nextDay1 = TimeUtil.computeStartOfNextDay(nextDay0) + 6747; + statsByDay.update(nextDay1, total); + assertEquals(2, statsByDay.getLastCount()); + assertEquals(1.5, statsByDay.getAverage(), 0.01); + + nextDay1 += 4444; + total += 4; + + statsByDay.update(nextDay1, total); + // values should remain unchanged + assertEquals(2, statsByDay.getLastCount()); + assertEquals(1.5, statsByDay.getAverage(), 0.01); + + long nextDay2 = TimeUtil.computeStartOfNextDay(nextDay1) + 11177; + + statsByDay.update(nextDay2, total); + // values should remain unchanged + assertEquals(4, statsByDay.getLastCount()); + assertEquals(7.0 / 3, statsByDay.getAverage(), 0.01); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyBasicTest.java b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyBasicTest.java index 7e41a9cc33f29b24da08a7bce34d392e9c6fedcb..abc1acf27b7b3d25b880caa30f79f3566b5f6cf1 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyBasicTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyBasicTest.java @@ -34,91 +34,87 @@ import ch.qos.logback.core.testUtil.RandomUtil; public class JettyBasicTest { - static RequestLogImpl REQUEST_LOG_IMPL; - static JettyFixtureWithListAndConsoleAppenders JETTY_FIXTURE; - - private static final int TIMEOUT = 5; - static int RANDOM_SERVER_PORT = RandomUtil.getRandomServerPort(); - - @BeforeClass - static public void startServer() throws Exception { - REQUEST_LOG_IMPL = new RequestLogImpl(); - JETTY_FIXTURE = new JettyFixtureWithListAndConsoleAppenders(REQUEST_LOG_IMPL, RANDOM_SERVER_PORT); - JETTY_FIXTURE.start(); - } - - @AfterClass - static public void stopServer() throws Exception { - if (JETTY_FIXTURE != null) { - JETTY_FIXTURE.stop(); + static RequestLogImpl REQUEST_LOG_IMPL; + static JettyFixtureWithListAndConsoleAppenders JETTY_FIXTURE; + + private static final int TIMEOUT = 5; + static int RANDOM_SERVER_PORT = RandomUtil.getRandomServerPort(); + + @BeforeClass + static public void startServer() throws Exception { + REQUEST_LOG_IMPL = new RequestLogImpl(); + JETTY_FIXTURE = new JettyFixtureWithListAndConsoleAppenders(REQUEST_LOG_IMPL, RANDOM_SERVER_PORT); + JETTY_FIXTURE.start(); + } + + @AfterClass + static public void stopServer() throws Exception { + if (JETTY_FIXTURE != null) { + JETTY_FIXTURE.stop(); + } + } + + @Test + public void getRequest() throws Exception { + URL url = new URL("http://localhost:" + RANDOM_SERVER_PORT + "/"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoInput(true); + + String result = Util.readToString(connection.getInputStream()); + + assertEquals("hello world", result); + + NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL.getAppender("list"); + listAppender.list.clear(); + } + + @Test + public void eventGoesToAppenders() throws Exception { + URL url = new URL(JETTY_FIXTURE.getUrl()); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoInput(true); + + String result = Util.readToString(connection.getInputStream()); + + assertEquals("hello world", result); + + NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL.getAppender("list"); + IAccessEvent event = listAppender.list.poll(TIMEOUT, TimeUnit.SECONDS); + assertNotNull("No events received", event); + + assertEquals("127.0.0.1", event.getRemoteHost()); + assertEquals("localhost", event.getServerName()); + listAppender.list.clear(); + } + + @Test + public void postContentConverter() throws Exception { + URL url = new URL(JETTY_FIXTURE.getUrl()); + String msg = "test message"; + + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + // this line is necessary to make the stream aware of when the message is + // over. + connection.setFixedLengthStreamingMode(msg.getBytes().length); + ((HttpURLConnection) connection).setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setUseCaches(false); + connection.setRequestProperty("Content-Type", "text/plain"); + + PrintWriter output = new PrintWriter(new OutputStreamWriter(connection.getOutputStream())); + output.print(msg); + output.flush(); + output.close(); + + // StatusPrinter.print(requestLogImpl.getStatusManager()); + + NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL.getAppender("list"); + + IAccessEvent event = listAppender.list.poll(TIMEOUT, TimeUnit.SECONDS); + assertNotNull("No events received", event); + + // we should test the contents of the requests + // assertEquals(msg, event.getRequestContent()); } - } - - @Test - public void getRequest() throws Exception { - URL url = new URL("http://localhost:" + RANDOM_SERVER_PORT + "/"); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setDoInput(true); - - String result = Util.readToString(connection.getInputStream()); - - assertEquals("hello world", result); - - NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL - .getAppender("list"); - listAppender.list.clear(); - } - - @Test - public void eventGoesToAppenders() throws Exception { - URL url = new URL(JETTY_FIXTURE.getUrl()); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setDoInput(true); - - String result = Util.readToString(connection.getInputStream()); - - assertEquals("hello world", result); - - NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL - .getAppender("list"); - IAccessEvent event = listAppender.list.poll(TIMEOUT, TimeUnit.SECONDS); - assertNotNull("No events received", event); - - assertEquals("127.0.0.1", event.getRemoteHost()); - assertEquals("localhost", event.getServerName()); - listAppender.list.clear(); - } - - @Test - public void postContentConverter() throws Exception { - URL url = new URL(JETTY_FIXTURE.getUrl()); - String msg = "test message"; - - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - // this line is necessary to make the stream aware of when the message is - // over. - connection.setFixedLengthStreamingMode(msg.getBytes().length); - ((HttpURLConnection) connection).setRequestMethod("POST"); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setUseCaches(false); - connection.setRequestProperty("Content-Type", "text/plain"); - - PrintWriter output = new PrintWriter(new OutputStreamWriter(connection - .getOutputStream())); - output.print(msg); - output.flush(); - output.close(); - - // StatusPrinter.print(requestLogImpl.getStatusManager()); - - NotifyingListAppender listAppender = (NotifyingListAppender) REQUEST_LOG_IMPL - .getAppender("list"); - - IAccessEvent event = listAppender.list.poll(TIMEOUT, TimeUnit.SECONDS); - assertNotNull("No events received", event); - - // we should test the contents of the requests - // assertEquals(msg, event.getRequestContent()); - } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureBase.java b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureBase.java index 5e56cb5ac03f456b14deb4568614e112058a4cc5..e461c5842edf35ba3f87f7d50498a5bec6221e14 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureBase.java +++ b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureBase.java @@ -30,72 +30,69 @@ import java.io.IOException; import java.io.OutputStream; public class JettyFixtureBase { - final protected RequestLogImpl requestLogImpl; - protected Handler handler = new BasicHandler(); - private final int port; - Server server; - protected String url; - - public JettyFixtureBase(RequestLogImpl impl, int port) { - requestLogImpl = impl; - this.port = port; - url = "http://localhost:" + port + "/"; - } - - public String getName() { - return "Jetty Test Setup"; - } - - public String getUrl() { - return url; - } - - public void start() throws Exception { - server = new Server(); - Connector connector = new SelectChannelConnector(); - connector.setPort(port); - server.setConnectors(new Connector[]{connector}); - - RequestLogHandler requestLogHandler = new RequestLogHandler(); - configureRequestLogImpl(); - requestLogHandler.setRequestLog(requestLogImpl); - - HandlerList handlers = new HandlerList(); - handlers.addHandler(requestLogHandler); - handlers.addHandler(getRequestHandler()); - - server.setHandler(handlers); - server.start(); - } - - public void stop() throws Exception { - server.stop(); - server = null; - } - - protected void configureRequestLogImpl() { - requestLogImpl.start(); - } - - protected Handler getRequestHandler() { - return handler; - } - - - class BasicHandler extends AbstractHandler { - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - OutputStream out = response.getOutputStream(); - ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(); - writer.write("hello world"); - writer.flush(); - response.setContentLength(writer.size()); - writer.writeTo(out); - out.flush(); - - baseRequest.setHandled(true); + final protected RequestLogImpl requestLogImpl; + protected Handler handler = new BasicHandler(); + private final int port; + Server server; + protected String url; + + public JettyFixtureBase(RequestLogImpl impl, int port) { + requestLogImpl = impl; + this.port = port; + url = "http://localhost:" + port + "/"; + } + public String getName() { + return "Jetty Test Setup"; + } + + public String getUrl() { + return url; + } + + public void start() throws Exception { + server = new Server(); + Connector connector = new SelectChannelConnector(); + connector.setPort(port); + server.setConnectors(new Connector[] { connector }); + + RequestLogHandler requestLogHandler = new RequestLogHandler(); + configureRequestLogImpl(); + requestLogHandler.setRequestLog(requestLogImpl); + + HandlerList handlers = new HandlerList(); + handlers.addHandler(requestLogHandler); + handlers.addHandler(getRequestHandler()); + + server.setHandler(handlers); + server.start(); } - } -} + public void stop() throws Exception { + server.stop(); + server = null; + } + + protected void configureRequestLogImpl() { + requestLogImpl.start(); + } + + protected Handler getRequestHandler() { + return handler; + } + class BasicHandler extends AbstractHandler { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + OutputStream out = response.getOutputStream(); + ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(); + writer.write("hello world"); + writer.flush(); + response.setContentLength(writer.size()); + writer.writeTo(out); + out.flush(); + + baseRequest.setHandled(true); + + } + } +} diff --git a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureWithListAndConsoleAppenders.java b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureWithListAndConsoleAppenders.java index c196deea082b131771e64c64a3b50d3ae621e3e9..741f5f75cef06b77cba186b485b4e04939efd096 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureWithListAndConsoleAppenders.java +++ b/logback-access/src/test/java/ch/qos/logback/access/jetty/JettyFixtureWithListAndConsoleAppenders.java @@ -20,40 +20,39 @@ import ch.qos.logback.core.ConsoleAppender; public class JettyFixtureWithListAndConsoleAppenders extends JettyFixtureBase { - public JettyFixtureWithListAndConsoleAppenders(RequestLogImpl impl, int port) { - super(impl, port); - url = "http://localhost:" + port + "/"; - } - - public void start() throws Exception { - super.start(); - Thread.yield(); - } - - public void stop() throws Exception { - super.stop(); - Thread.sleep(500); - } - - @Override - protected void configureRequestLogImpl() { - NotifyingListAppender appender = new NotifyingListAppender(); - appender.setContext(requestLogImpl); - appender.setName("list"); - appender.start(); - - ConsoleAppender console = new ConsoleAppender(); - console.setContext(requestLogImpl); - console.setName("console"); - PatternLayoutEncoder layout = new PatternLayoutEncoder(); - layout.setContext(requestLogImpl); - layout.setPattern("%date %server %clientHost"); - console.setEncoder(layout); - layout.start(); - console.start(); - - requestLogImpl.addAppender(appender); - requestLogImpl.addAppender(console); - } + public JettyFixtureWithListAndConsoleAppenders(RequestLogImpl impl, int port) { + super(impl, port); + url = "http://localhost:" + port + "/"; + } + + public void start() throws Exception { + super.start(); + Thread.yield(); + } + + public void stop() throws Exception { + super.stop(); + Thread.sleep(500); + } + + @Override + protected void configureRequestLogImpl() { + NotifyingListAppender appender = new NotifyingListAppender(); + appender.setContext(requestLogImpl); + appender.setName("list"); + appender.start(); + + ConsoleAppender console = new ConsoleAppender(); + console.setContext(requestLogImpl); + console.setName("console"); + PatternLayoutEncoder layout = new PatternLayoutEncoder(); + layout.setContext(requestLogImpl); + layout.setPattern("%date %server %clientHost"); + console.setEncoder(layout); + layout.start(); + console.start(); + + requestLogImpl.addAppender(appender); + requestLogImpl.addAppender(console); + } } - diff --git a/logback-access/src/test/java/ch/qos/logback/access/jetty/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/jetty/PackageTest.java index c9a70fbc9f29c7afea784ae5ca9504e6f8906c69..45731f4796c09d4bfb8dd5f5175881d19b86ac3d 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/jetty/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/jetty/PackageTest.java @@ -18,7 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({JettyBasicTest.class}) -public class PackageTest { +@SuiteClasses({ JettyBasicTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/joran/ConditionalTest.java b/logback-access/src/test/java/ch/qos/logback/access/joran/ConditionalTest.java index 0959ae3034426146daf349b03d056a590311494b..2bb73a3d584944c9f0b5f7e25ff3acbe497d08dd 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/joran/ConditionalTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/joran/ConditionalTest.java @@ -37,59 +37,57 @@ import static org.junit.Assert.assertTrue; */ public class ConditionalTest { - AccessContext context = new AccessContext(); - StatusChecker checker = new StatusChecker(context); + AccessContext context = new AccessContext(); + StatusChecker checker = new StatusChecker(context); - int diff = RandomUtil.getPositiveInt(); - String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; + int diff = RandomUtil.getPositiveInt(); + String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; - @Before - public void setUp() { - InetAddress localhost = null; - try { - localhost = InetAddress.getLocalHost(); - context.putProperty("aHost", localhost.getHostName()); - } catch (UnknownHostException e) { - e.printStackTrace(); + @Before + public void setUp() { + InetAddress localhost = null; + try { + localhost = InetAddress.getLocalHost(); + context.putProperty("aHost", localhost.getHostName()); + } catch (UnknownHostException e) { + e.printStackTrace(); + } } - } - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(context); - jc.doConfigure(file); - } + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + jc.doConfigure(file); + } - @Test - public void conditionalConsoleApp_IF_THEN_True() throws JoranException, UnknownHostException { - configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); - ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); - assertNotNull(consoleAppender); - assertTrue(checker.isErrorFree(0)); - } + @Test + public void conditionalConsoleApp_IF_THEN_True() throws JoranException, UnknownHostException { + configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); + ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); + assertNotNull(consoleAppender); + assertTrue(checker.isErrorFree(0)); + } - @Test - public void conditionalConsoleApp_IF_THEN_False() throws JoranException, - IOException, InterruptedException { - context.putProperty("aHost", null); - configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); + @Test + public void conditionalConsoleApp_IF_THEN_False() throws JoranException, IOException, InterruptedException { + context.putProperty("aHost", null); + configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); - ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); - assertNull(consoleAppender); + ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); + assertNull(consoleAppender); - StatusChecker checker = new StatusChecker(context); - assertTrue(checker.isErrorFree(0)); - } + StatusChecker checker = new StatusChecker(context); + assertTrue(checker.isErrorFree(0)); + } - @Test - public void conditionalConsoleApp_ELSE() throws JoranException, - IOException, InterruptedException { - configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole_ELSE.xml"); - ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); - assertNull(consoleAppender); + @Test + public void conditionalConsoleApp_ELSE() throws JoranException, IOException, InterruptedException { + configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole_ELSE.xml"); + ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); + assertNull(consoleAppender); - ListAppender listAppender = (ListAppender) context.getAppender("LIST"); - assertNotNull(listAppender); - assertTrue(checker.isErrorFree(0)); - } + ListAppender listAppender = (ListAppender) context.getAppender("LIST"); + assertNotNull(listAppender); + assertTrue(checker.isErrorFree(0)); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/joran/JoranConfiguratorTest.java b/logback-access/src/test/java/ch/qos/logback/access/joran/JoranConfiguratorTest.java index d12b724d843513f43d9bdccfafd8610b5f0bd34a..c4d91058eea7ad50a55a7440bc984272a19bcb2f 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/joran/JoranConfiguratorTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/joran/JoranConfiguratorTest.java @@ -31,47 +31,45 @@ import ch.qos.logback.core.testUtil.StringListAppender; public class JoranConfiguratorTest { - AccessContext context = new AccessContext(); + AccessContext context = new AccessContext(); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(context); - jc.doConfigure(file); - } + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + jc.doConfigure(file); + } - @Test - public void smoke() throws Exception { - configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/smoke.xml"); + @Test + public void smoke() throws Exception { + configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/smoke.xml"); - ListAppender listAppender = (ListAppender) context - .getAppender("LIST"); - IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); - listAppender.doAppend(event); + ListAppender listAppender = (ListAppender) context.getAppender("LIST"); + IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); + listAppender.doAppend(event); - assertEquals(1, listAppender.list.size()); + assertEquals(1, listAppender.list.size()); - assertEquals(1, listAppender.list.size()); - IAccessEvent ae = listAppender.list.get(0); - assertNotNull(ae); - } + assertEquals(1, listAppender.list.size()); + IAccessEvent ae = listAppender.list.get(0); + assertNotNull(ae); + } - @Test - public void defaultLayout() throws Exception { - configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/defaultLayout.xml"); - StringListAppender listAppender = (StringListAppender) context - .getAppender("STR_LIST"); - IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); - listAppender.doAppend(event); - assertEquals(1, listAppender.strList.size()); - // the result contains a line separator at the end - assertTrue(listAppender.strList.get(0).startsWith("testMethod")); - } + @Test + public void defaultLayout() throws Exception { + configure(AccessTestConstants.TEST_DIR_PREFIX + "input/joran/defaultLayout.xml"); + StringListAppender listAppender = (StringListAppender) context.getAppender("STR_LIST"); + IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); + listAppender.doAppend(event); + assertEquals(1, listAppender.strList.size()); + // the result contains a line separator at the end + assertTrue(listAppender.strList.get(0).startsWith("testMethod")); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/joran/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/joran/PackageTest.java index 5e2c995e5aaaf74aa707331432a65e6149c3bc41..6501b12208219c1cfb916e55f37be44ea4ef5a57 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/joran/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/joran/PackageTest.java @@ -20,6 +20,6 @@ import org.junit.runners.Suite; * @author Ceki Gücü */ @RunWith(Suite.class) -@Suite.SuiteClasses({JoranConfiguratorTest.class, ConditionalTest.class}) +@Suite.SuiteClasses({ JoranConfiguratorTest.class, ConditionalTest.class }) public class PackageTest { } diff --git a/logback-access/src/test/java/ch/qos/logback/access/net/NOPOutputStream.java b/logback-access/src/test/java/ch/qos/logback/access/net/NOPOutputStream.java index 42d8df3f978b31bf50288b79b2dc9c3b04bd0ce8..bcb24588eaef26381d5aba54a994ae6824063314 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/net/NOPOutputStream.java +++ b/logback-access/src/test/java/ch/qos/logback/access/net/NOPOutputStream.java @@ -18,10 +18,10 @@ import java.io.OutputStream; public class NOPOutputStream extends OutputStream { - @Override - public void write(int b) throws IOException { - // do nothing + @Override + public void write(int b) throws IOException { + // do nothing - } + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/net/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/net/PackageTest.java index d739bc56e225ec411d6a86b56e5e752096665fec..c18da6b2418ecf59a596c839e08e969ec843ad99 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/net/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/net/PackageTest.java @@ -20,6 +20,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({URLEvaluatorTest.class}) +@SuiteClasses({ URLEvaluatorTest.class }) public class PackageTest extends TestCase { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/net/SerializationPerfTest.java b/logback-access/src/test/java/ch/qos/logback/access/net/SerializationPerfTest.java index 55e0cc076d5c2101c77f4b1cabbeda6f8df697c7..df39c1fe975ead109f0984559ebb74d5bcefd062 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/net/SerializationPerfTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/net/SerializationPerfTest.java @@ -22,87 +22,83 @@ import ch.qos.logback.access.dummy.DummyAccessEventBuilder; public class SerializationPerfTest extends TestCase { - ObjectOutputStream oos; - - int loopNumber = 10000; - int resetFrequency = 100; - int pauseFrequency = 10; - long pauseLengthInMillis = 20; - + ObjectOutputStream oos; - public void setUp() throws Exception { - super.setUp(); - oos = new ObjectOutputStream(new NOPOutputStream()); + int loopNumber = 10000; + int resetFrequency = 100; + int pauseFrequency = 10; + long pauseLengthInMillis = 20; - } + public void setUp() throws Exception { + super.setUp(); + oos = new ObjectOutputStream(new NOPOutputStream()); - public void tearDown() throws Exception { - super.tearDown(); - oos.close(); - oos = null; - } - - public void test1() throws Exception { - // first run for just in time compiler - int resetCounter = 0; - int pauseCounter = 0; - for (int i = 0; i < loopNumber; i++) { - try { - IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); - //average time for the next method: 5000 nanos - ae.prepareForDeferredProcessing(); - oos.writeObject(ae); - oos.flush(); - if (++resetCounter >= resetFrequency) { - oos.reset(); - resetCounter = 0; - } - if (++pauseCounter >= pauseFrequency) { - Thread.sleep(pauseLengthInMillis); - pauseCounter = 0; - } + } - } catch (IOException ex) { - fail(ex.getMessage()); - } + public void tearDown() throws Exception { + super.tearDown(); + oos.close(); + oos = null; } - - // second run - Long t1; - Long t2; - Long total = 0L; - resetCounter = 0; - pauseCounter = 0; - // System.out.println("Beginning mesured run"); - for (int i = 0; i < loopNumber; i++) { - try { - IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); - t1 = System.nanoTime(); - //average length of the next method: 4000 nanos - ae.prepareForDeferredProcessing(); - oos.writeObject(ae); - oos.flush(); - t2 = System.nanoTime(); - total += (t2 - t1); - if (++resetCounter >= resetFrequency) { - oos.reset(); - resetCounter = 0; + + public void test1() throws Exception { + // first run for just in time compiler + int resetCounter = 0; + int pauseCounter = 0; + for (int i = 0; i < loopNumber; i++) { + try { + IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); + // average time for the next method: 5000 nanos + ae.prepareForDeferredProcessing(); + oos.writeObject(ae); + oos.flush(); + if (++resetCounter >= resetFrequency) { + oos.reset(); + resetCounter = 0; + } + if (++pauseCounter >= pauseFrequency) { + Thread.sleep(pauseLengthInMillis); + pauseCounter = 0; + } + + } catch (IOException ex) { + fail(ex.getMessage()); + } } - if (++pauseCounter >= pauseFrequency) { - Thread.sleep(pauseLengthInMillis); - pauseCounter = 0; + + // second run + Long t1; + Long t2; + Long total = 0L; + resetCounter = 0; + pauseCounter = 0; + // System.out.println("Beginning mesured run"); + for (int i = 0; i < loopNumber; i++) { + try { + IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); + t1 = System.nanoTime(); + // average length of the next method: 4000 nanos + ae.prepareForDeferredProcessing(); + oos.writeObject(ae); + oos.flush(); + t2 = System.nanoTime(); + total += (t2 - t1); + if (++resetCounter >= resetFrequency) { + oos.reset(); + resetCounter = 0; + } + if (++pauseCounter >= pauseFrequency) { + Thread.sleep(pauseLengthInMillis); + pauseCounter = 0; + } + } catch (IOException ex) { + fail(ex.getMessage()); + } } - } catch (IOException ex) { - fail(ex.getMessage()); - } + + total /= (1000);// nanos -> micros + System.out.println("Loop done : average time = " + total / loopNumber + " microsecs after " + loopNumber + " writes."); + // average time: 26-30 microsec = 0.030 millis } - - total /= (1000);//nanos -> micros - System.out.println("Loop done : average time = " + total / loopNumber - + " microsecs after " + loopNumber + " writes."); - //average time: 26-30 microsec = 0.030 millis - } - - } diff --git a/logback-access/src/test/java/ch/qos/logback/access/net/URLEvaluatorTest.java b/logback-access/src/test/java/ch/qos/logback/access/net/URLEvaluatorTest.java index 9cebdb7a13a5dd62422b78a3ad7ad3cc0179b42a..e0d4d453b921bcc1438cf6be367c8e85a31805ed 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/net/URLEvaluatorTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/net/URLEvaluatorTest.java @@ -28,56 +28,56 @@ import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.boolex.EvaluationException; -public class URLEvaluatorTest { +public class URLEvaluatorTest { - final String expectedURL1 = "testUrl1"; - final String expectedURL2 = "testUrl2"; - Context context = new ContextBase(); - URLEvaluator evaluator; - DummyRequest request; - DummyResponse response; - DummyServerAdapter serverAdapter; - - @Before - public void setUp() throws Exception { - evaluator = new URLEvaluator(); - evaluator.setContext(context); - evaluator.addURL(expectedURL1); - evaluator.start(); - request = new DummyRequest(); - response = new DummyResponse(); - serverAdapter = new DummyServerAdapter(request, response); - } - - @After - public void tearDown() throws Exception { - evaluator.stop(); - evaluator = null; - request = null; - response = null; - serverAdapter = null; - context = null; - } - - @Test - public void testExpectFalse() throws EvaluationException { - request.setRequestUri("test"); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - assertFalse(evaluator.evaluate(ae)); - } - - @Test - public void testExpectTrue() throws EvaluationException { - request.setRequestUri(expectedURL1); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - assertTrue(evaluator.evaluate(ae)); - } - - @Test - public void testExpectTrueMultiple() throws EvaluationException { - evaluator.addURL(expectedURL2); - request.setRequestUri(expectedURL2); - IAccessEvent ae = new AccessEvent(request, response, serverAdapter); - assertTrue(evaluator.evaluate(ae)); - } + final String expectedURL1 = "testUrl1"; + final String expectedURL2 = "testUrl2"; + Context context = new ContextBase(); + URLEvaluator evaluator; + DummyRequest request; + DummyResponse response; + DummyServerAdapter serverAdapter; + + @Before + public void setUp() throws Exception { + evaluator = new URLEvaluator(); + evaluator.setContext(context); + evaluator.addURL(expectedURL1); + evaluator.start(); + request = new DummyRequest(); + response = new DummyResponse(); + serverAdapter = new DummyServerAdapter(request, response); + } + + @After + public void tearDown() throws Exception { + evaluator.stop(); + evaluator = null; + request = null; + response = null; + serverAdapter = null; + context = null; + } + + @Test + public void testExpectFalse() throws EvaluationException { + request.setRequestUri("test"); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + assertFalse(evaluator.evaluate(ae)); + } + + @Test + public void testExpectTrue() throws EvaluationException { + request.setRequestUri(expectedURL1); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + assertTrue(evaluator.evaluate(ae)); + } + + @Test + public void testExpectTrueMultiple() throws EvaluationException { + evaluator.addURL(expectedURL2); + request.setRequestUri(expectedURL2); + IAccessEvent ae = new AccessEvent(request, response, serverAdapter); + assertTrue(evaluator.evaluate(ae)); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/pattern/ConverterTest.java b/logback-access/src/test/java/ch/qos/logback/access/pattern/ConverterTest.java index 92491f8876c90d55eb8ab6e90fb1b1c7d37f6e35..b126cdea659bbd0ef95e189e26a4ee8385ca8999 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/pattern/ConverterTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/pattern/ConverterTest.java @@ -30,171 +30,170 @@ import ch.qos.logback.access.dummy.DummyResponse; import ch.qos.logback.access.dummy.DummyServerAdapter; import ch.qos.logback.access.spi.AccessEvent; -public class ConverterTest { - - IAccessEvent event; - DummyRequest request; - DummyResponse response; - - @Before - public void setUp() throws Exception { - request = new DummyRequest(); - response = new DummyResponse(); - event = createEvent(); - } - - @After - public void tearDown() throws Exception { - event = null; - request = null; - response = null; - } - - @Test - public void testContentLengthConverter() { - ContentLengthConverter converter = new ContentLengthConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(Long.toString(event.getServerAdapter().getContentLength()), result); - } - - @Test - public void testDateConverter() { - DateConverter converter = new DateConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(converter.cachingDateFormatter.format(event.getTimeStamp()), result); - } - - public void testLineLocalPortConverter() { - LocalPortConverter converter = new LocalPortConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(Integer.toString(request.getLocalPort()), result); - } - - @Test - public void testRemoteHostConverter() { - RemoteHostConverter converter = new RemoteHostConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getRemoteHost(), result); - } - - @Test - public void testRemoteIPAddressConverter() { - RemoteIPAddressConverter converter = new RemoteIPAddressConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getRemoteAddr(), result); - } - - @Test - public void testRemoteUserConverter() { - RemoteUserConverter converter = new RemoteUserConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getRemoteUser(), result); - } - - @Test - public void testRequestAttributeConverter() { - RequestAttributeConverter converter = new RequestAttributeConverter(); - List optionList = new ArrayList(); - optionList.add("testKey"); - converter.setOptionList(optionList); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getAttribute("testKey"), result); - } - - @Test - public void testRequestCookieConverter() { - RequestCookieConverter converter = new RequestCookieConverter(); - List optionList = new ArrayList(); - optionList.add("testName"); - converter.setOptionList(optionList); - converter.start(); - String result = converter.convert(event); - Cookie cookie = request.getCookies()[0]; - assertEquals(cookie.getValue(), result); - } - - @Test - public void testRequestHeaderConverter() { - RequestHeaderConverter converter = new RequestHeaderConverter(); - List optionList = new ArrayList(); - optionList.add("headerName1"); - converter.setOptionList(optionList); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getHeader("headerName1"), result); - } - - @Test - public void testRequestMethodConverter() { - RequestMethodConverter converter = new RequestMethodConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getMethod(), result); - } - - @Test - public void testRequestProtocolConverter() { - RequestProtocolConverter converter = new RequestProtocolConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getProtocol(), result); - } - - @Test - public void testRequestURIConverter() { - RequestURIConverter converter = new RequestURIConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getRequestURI(), result); - } - - @Test - public void testRequestURLConverter() { - RequestURLConverter converter = new RequestURLConverter(); - converter.start(); - String result = converter.convert(event); - String expected = request.getMethod() + " " + request.getRequestURI() + " " - + request.getProtocol(); - assertEquals(expected, result); - } - - @Test - public void testResponseHeaderConverter() { - ResponseHeaderConverter converter = new ResponseHeaderConverter(); - List optionList = new ArrayList(); - optionList.add("headerName1"); - converter.setOptionList(optionList); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getHeader("headerName1"), result); - } - - @Test - public void testServerNameConverter() { - ServerNameConverter converter = new ServerNameConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(request.getServerName(), result); - } - - @Test - public void testStatusCodeConverter() { - StatusCodeConverter converter = new StatusCodeConverter(); - converter.start(); - String result = converter.convert(event); - assertEquals(Integer.toString(event.getServerAdapter().getStatusCode()), result); - } - - private IAccessEvent createEvent() { - DummyServerAdapter dummyAdapter = new DummyServerAdapter(request, response); - return new AccessEvent(request, response, dummyAdapter); - } +public class ConverterTest { + + IAccessEvent event; + DummyRequest request; + DummyResponse response; + + @Before + public void setUp() throws Exception { + request = new DummyRequest(); + response = new DummyResponse(); + event = createEvent(); + } + + @After + public void tearDown() throws Exception { + event = null; + request = null; + response = null; + } + + @Test + public void testContentLengthConverter() { + ContentLengthConverter converter = new ContentLengthConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(Long.toString(event.getServerAdapter().getContentLength()), result); + } + + @Test + public void testDateConverter() { + DateConverter converter = new DateConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(converter.cachingDateFormatter.format(event.getTimeStamp()), result); + } + + public void testLineLocalPortConverter() { + LocalPortConverter converter = new LocalPortConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(Integer.toString(request.getLocalPort()), result); + } + + @Test + public void testRemoteHostConverter() { + RemoteHostConverter converter = new RemoteHostConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getRemoteHost(), result); + } + + @Test + public void testRemoteIPAddressConverter() { + RemoteIPAddressConverter converter = new RemoteIPAddressConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getRemoteAddr(), result); + } + + @Test + public void testRemoteUserConverter() { + RemoteUserConverter converter = new RemoteUserConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getRemoteUser(), result); + } + + @Test + public void testRequestAttributeConverter() { + RequestAttributeConverter converter = new RequestAttributeConverter(); + List optionList = new ArrayList(); + optionList.add("testKey"); + converter.setOptionList(optionList); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getAttribute("testKey"), result); + } + + @Test + public void testRequestCookieConverter() { + RequestCookieConverter converter = new RequestCookieConverter(); + List optionList = new ArrayList(); + optionList.add("testName"); + converter.setOptionList(optionList); + converter.start(); + String result = converter.convert(event); + Cookie cookie = request.getCookies()[0]; + assertEquals(cookie.getValue(), result); + } + + @Test + public void testRequestHeaderConverter() { + RequestHeaderConverter converter = new RequestHeaderConverter(); + List optionList = new ArrayList(); + optionList.add("headerName1"); + converter.setOptionList(optionList); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getHeader("headerName1"), result); + } + + @Test + public void testRequestMethodConverter() { + RequestMethodConverter converter = new RequestMethodConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getMethod(), result); + } + + @Test + public void testRequestProtocolConverter() { + RequestProtocolConverter converter = new RequestProtocolConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getProtocol(), result); + } + + @Test + public void testRequestURIConverter() { + RequestURIConverter converter = new RequestURIConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getRequestURI(), result); + } + + @Test + public void testRequestURLConverter() { + RequestURLConverter converter = new RequestURLConverter(); + converter.start(); + String result = converter.convert(event); + String expected = request.getMethod() + " " + request.getRequestURI() + " " + request.getProtocol(); + assertEquals(expected, result); + } + + @Test + public void testResponseHeaderConverter() { + ResponseHeaderConverter converter = new ResponseHeaderConverter(); + List optionList = new ArrayList(); + optionList.add("headerName1"); + converter.setOptionList(optionList); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getHeader("headerName1"), result); + } + + @Test + public void testServerNameConverter() { + ServerNameConverter converter = new ServerNameConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(request.getServerName(), result); + } + + @Test + public void testStatusCodeConverter() { + StatusCodeConverter converter = new StatusCodeConverter(); + converter.start(); + String result = converter.convert(event); + assertEquals(Integer.toString(event.getServerAdapter().getStatusCode()), result); + } + + private IAccessEvent createEvent() { + DummyServerAdapter dummyAdapter = new DummyServerAdapter(request, response); + return new AccessEvent(request, response, dummyAdapter); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/pattern/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/pattern/PackageTest.java index 81afa162e97fd1f46bd953947988e94b547d180b..f019c3e41de4bc1dbf0def4222b280893ab3eb91 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/pattern/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/pattern/PackageTest.java @@ -18,8 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ConverterTest.class}) -public class PackageTest { - +@SuiteClasses({ ConverterTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/servlet/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/servlet/PackageTest.java index 9b9b60bee2c072303a6a2afdd96a065be5492de2..8520fcda4f194cf0d71d7a842a333b4e02708916 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/servlet/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/servlet/PackageTest.java @@ -19,6 +19,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({TeeFilterTest.class}) +@SuiteClasses({ TeeFilterTest.class }) public class PackageTest extends TestCase { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeFilterTest.java b/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeFilterTest.java index 3d920081a34d215bb0c3f36116572deb4df59775..163a153ae1ae7cae666c9252aabebf7f5c4b2da9 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeFilterTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeFilterTest.java @@ -23,13 +23,12 @@ import static org.junit.Assert.assertEquals; public class TeeFilterTest { - @Test public void extractNameList() { - assertEquals(Arrays.asList(new String[]{"a"}), TeeFilter.extractNameList("a")); - assertEquals(Arrays.asList(new String[]{"a", "b"}), TeeFilter.extractNameList("a, b")); - assertEquals(Arrays.asList(new String[]{"a", "b"}), TeeFilter.extractNameList("a; b")); - assertEquals(Arrays.asList(new String[]{"a", "b", "c"}), TeeFilter.extractNameList("a; b, c")); + assertEquals(Arrays.asList(new String[] { "a" }), TeeFilter.extractNameList("a")); + assertEquals(Arrays.asList(new String[] { "a", "b" }), TeeFilter.extractNameList("a, b")); + assertEquals(Arrays.asList(new String[] { "a", "b" }), TeeFilter.extractNameList("a; b")); + assertEquals(Arrays.asList(new String[] { "a", "b", "c" }), TeeFilter.extractNameList("a; b, c")); } @Test @@ -46,7 +45,6 @@ public class TeeFilterTest { assertFalse(TeeFilter.computeActivation("a", "b, c", null)); } - @Test public void withExcludesOnly() { assertFalse(TeeFilter.computeActivation("a", null, "a")); @@ -55,7 +53,6 @@ public class TeeFilterTest { assertTrue(TeeFilter.computeActivation("a", null, "b, c")); } - @Test public void withIncludesAndExcludes() { assertFalse(TeeFilter.computeActivation("a", "a", "a")); diff --git a/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeHttpServletResponseTest.java b/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeHttpServletResponseTest.java index 3fb079ffd47092b26cd589fd64dda0c100c2db5f..798d3668c6432496ba6e35b257d05f299c2075de 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeHttpServletResponseTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/servlet/TeeHttpServletResponseTest.java @@ -30,39 +30,38 @@ import static org.junit.Assert.assertArrayEquals; @RunWith(Parameterized.class) public class TeeHttpServletResponseTest { - String characterEncoding; - String testString; - byte[] expectedBytes; + String characterEncoding; + String testString; + byte[] expectedBytes; - public TeeHttpServletResponseTest(String characterEncoding, String testString, byte[] expectedBytes) { - this.characterEncoding = characterEncoding; - this.testString = testString; - this.expectedBytes = expectedBytes; - } + public TeeHttpServletResponseTest(String characterEncoding, String testString, byte[] expectedBytes) { + this.characterEncoding = characterEncoding; + this.testString = testString; + this.expectedBytes = expectedBytes; + } - @Parameterized.Parameters - public static Collection inputValues() { - return Arrays.asList(new Object[][]{ - { "utf-8", "Gülcü", new byte[] { (byte) 0x47, (byte) 0xC3, (byte) 0xBC, (byte) 0x6C, (byte) 0x63, (byte) 0xC3, (byte) 0xBC }}, - { "iso-8859-1", "Gülcü", new byte[] { (byte) 0x47, (byte) 0xFC, (byte) 0x6C, (byte) 0x63, (byte) 0xFC }} - }); - } + @Parameterized.Parameters + public static Collection inputValues() { + return Arrays.asList(new Object[][] { + { "utf-8", "Gülcü", new byte[] { (byte) 0x47, (byte) 0xC3, (byte) 0xBC, (byte) 0x6C, (byte) 0x63, (byte) 0xC3, (byte) 0xBC } }, + { "iso-8859-1", "Gülcü", new byte[] { (byte) 0x47, (byte) 0xFC, (byte) 0x6C, (byte) 0x63, (byte) 0xFC } } }); + } - @Test - public void testWriterEncoding() throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + @Test + public void testWriterEncoding() throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - DummyResponse dummyResponse = new DummyResponse(); - dummyResponse.setCharacterEncoding(characterEncoding); - dummyResponse.setOutputStream(new DummyServletOutputStream(byteArrayOutputStream)); + DummyResponse dummyResponse = new DummyResponse(); + dummyResponse.setCharacterEncoding(characterEncoding); + dummyResponse.setOutputStream(new DummyServletOutputStream(byteArrayOutputStream)); - TeeHttpServletResponse teeServletResponse = new TeeHttpServletResponse(dummyResponse); + TeeHttpServletResponse teeServletResponse = new TeeHttpServletResponse(dummyResponse); - PrintWriter writer = teeServletResponse.getWriter(); - writer.write(testString); - writer.flush(); + PrintWriter writer = teeServletResponse.getWriter(); + writer.write(testString); + writer.flush(); - assertArrayEquals(expectedBytes, byteArrayOutputStream.toByteArray()); - } + assertArrayEquals(expectedBytes, byteArrayOutputStream.toByteArray()); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/sift/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/sift/PackageTest.java index 5fe5cb888a2702b4836a8b184c35e767bfcd34b0..977c6ef42506b658935292dff0144ae9c784fbef 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/sift/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/sift/PackageTest.java @@ -18,7 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({SiftingAppenderTest.class}) -public class PackageTest { +@SuiteClasses({ SiftingAppenderTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/sift/SiftingAppenderTest.java b/logback-access/src/test/java/ch/qos/logback/access/sift/SiftingAppenderTest.java index 257ef614d0d9814c00ec50d276e3f21b5790777b..2c20edebcbeb0649b1a152355fbb4d60623dd1d0 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/sift/SiftingAppenderTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/sift/SiftingAppenderTest.java @@ -33,61 +33,59 @@ import ch.qos.logback.core.testUtil.RandomUtil; import ch.qos.logback.core.util.StatusPrinter; public class SiftingAppenderTest { - static final String PREFIX = "src/test/input/jetty/"; - static int RANDOM_SERVER_PORT = RandomUtil.getRandomServerPort(); + static final String PREFIX = "src/test/input/jetty/"; + static int RANDOM_SERVER_PORT = RandomUtil.getRandomServerPort(); - JettyFixtureBase jettyFixture; - RequestLogImpl rli = new RequestLogImpl(); + JettyFixtureBase jettyFixture; + RequestLogImpl rli = new RequestLogImpl(); - @Before - public void startServer() throws Exception { - jettyFixture = new JettyFixtureBase(rli, RANDOM_SERVER_PORT); - } + @Before + public void startServer() throws Exception { + jettyFixture = new JettyFixtureBase(rli, RANDOM_SERVER_PORT); + } - @After - public void stopServer() throws Exception { - if (jettyFixture != null) { - jettyFixture.stop(); + @After + public void stopServer() throws Exception { + if (jettyFixture != null) { + jettyFixture.stop(); + } } - } - @Test - public void invokingDifferentPathShouldBeSiftedAccordingly() throws Exception { - rli.setFileName(PREFIX + "sifting.xml"); - jettyFixture.start(); - invokeServer("/"); - invokeServer("/x"); - invokeServer("/x"); - invokeServer("/y"); + @Test + public void invokingDifferentPathShouldBeSiftedAccordingly() throws Exception { + rli.setFileName(PREFIX + "sifting.xml"); + jettyFixture.start(); + invokeServer("/"); + invokeServer("/x"); + invokeServer("/x"); + invokeServer("/y"); - StatusPrinter.print(rli); - SiftingAppender siftingAppender = (SiftingAppender) rli - .getAppender("SIFTING"); - Set keySet = siftingAppender.getAppenderTracker().allKeys(); - assertEquals(3, keySet.size()); + StatusPrinter.print(rli); + SiftingAppender siftingAppender = (SiftingAppender) rli.getAppender("SIFTING"); + Set keySet = siftingAppender.getAppenderTracker().allKeys(); + assertEquals(3, keySet.size()); - Set witnessSet = new LinkedHashSet(); - witnessSet.add("NA"); - witnessSet.add("x"); - witnessSet.add("y"); - assertEquals(witnessSet, keySet); + Set witnessSet = new LinkedHashSet(); + witnessSet.add("NA"); + witnessSet.add("x"); + witnessSet.add("y"); + assertEquals(witnessSet, keySet); - check(siftingAppender, "NA", 1); - check(siftingAppender, "x", 2); - check(siftingAppender, "y", 1); - } + check(siftingAppender, "NA", 1); + check(siftingAppender, "x", 2); + check(siftingAppender, "y", 1); + } - private void check(SiftingAppender siftingAppender, String key, int expectedCount) { - ListAppender listAppender = (ListAppender) siftingAppender - .getAppenderTracker().find(key); - assertEquals(expectedCount, listAppender.list.size()); - } + private void check(SiftingAppender siftingAppender, String key, int expectedCount) { + ListAppender listAppender = (ListAppender) siftingAppender.getAppenderTracker().find(key); + assertEquals(expectedCount, listAppender.list.size()); + } - void invokeServer(String uri) throws Exception { - URL url = new URL("http://localhost:" + RANDOM_SERVER_PORT + uri); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setDoInput(true); - Util.readToString(connection.getInputStream()); - Thread.sleep(10); - } + void invokeServer(String uri) throws Exception { + URL url = new URL("http://localhost:" + RANDOM_SERVER_PORT + uri); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoInput(true); + Util.readToString(connection.getInputStream()); + Thread.sleep(10); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/spi/AccessEventSerializationTest.java b/logback-access/src/test/java/ch/qos/logback/access/spi/AccessEventSerializationTest.java index 2d61a4f66e5d4ba0beb73859ca114d0cb284fc7e..cbbd69247cd76ec6400c6e3a455fb9075935b73e 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/spi/AccessEventSerializationTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/spi/AccessEventSerializationTest.java @@ -24,72 +24,62 @@ import java.io.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class AccessEventSerializationTest { - - private Object buildSerializedAccessEvent() throws IOException, - ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); - // average time for the next method: 5000 nanos - ae.prepareForDeferredProcessing(); - oos.writeObject(ae); - oos.flush(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - ObjectInputStream ois = new ObjectInputStream(bais); - - return ois.readObject(); - } - - @Test - public void testSerialization() throws IOException, ClassNotFoundException { - Object o = buildSerializedAccessEvent(); - assertNotNull(o); - IAccessEvent aeBack = (IAccessEvent) o; - - - assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP, aeBack - .getResponseHeaderMap()); - assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.get("x"), aeBack - .getResponseHeader("x")); - assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.get("headerName1"), - aeBack.getResponseHeader("headerName1")); - assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.size(), aeBack - .getResponseHeaderNameList().size()); - assertEquals(DummyResponse.DUMMY_DEFAULT_CONTENT_COUNT, aeBack - .getContentLength()); - assertEquals(DummyResponse.DUMMY_DEFAULT_STATUS, aeBack.getStatusCode()); - - assertEquals(DummyRequest.DUMMY_CONTENT_STRING, aeBack - .getRequestContent()); - - assertEquals(DummyRequest.DUMMY_RESPONSE_CONTENT_STRING, aeBack - .getResponseContent()); - - assertEquals(DummyRequest.DUMMY_DEFAULT_ATTR_MAP.get("testKey"), aeBack - .getAttribute("testKey")); - } - - // Web containers may (and will) recycle requests objects. So we must make sure that after - // we prepared an event for deferred processing it won't be using data from the original - // HttpRequest object which may at that time represent another request - @Test - public void testAttributesAreNotTakenFromRecycledRequestWhenProcessingDeferred() { - - DummyRequest request = new DummyRequest(); - DummyResponse response = new DummyResponse(); - DummyServerAdapter adapter = new DummyServerAdapter(request, response); - - IAccessEvent event = new AccessEvent(request, response, adapter); - - request.setAttribute("testKey", "ORIGINAL"); - - event.prepareForDeferredProcessing(); - - request.setAttribute("testKey", "NEW"); - - // Event should capture the original value - assertEquals("ORIGINAL", event.getAttribute("testKey")); - } +public class AccessEventSerializationTest { + + private Object buildSerializedAccessEvent() throws IOException, ClassNotFoundException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + IAccessEvent ae = DummyAccessEventBuilder.buildNewAccessEvent(); + // average time for the next method: 5000 nanos + ae.prepareForDeferredProcessing(); + oos.writeObject(ae); + oos.flush(); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais); + + return ois.readObject(); + } + + @Test + public void testSerialization() throws IOException, ClassNotFoundException { + Object o = buildSerializedAccessEvent(); + assertNotNull(o); + IAccessEvent aeBack = (IAccessEvent) o; + + assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP, aeBack.getResponseHeaderMap()); + assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.get("x"), aeBack.getResponseHeader("x")); + assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.get("headerName1"), aeBack.getResponseHeader("headerName1")); + assertEquals(DummyResponse.DUMMY_DEFAULT_HDEADER_MAP.size(), aeBack.getResponseHeaderNameList().size()); + assertEquals(DummyResponse.DUMMY_DEFAULT_CONTENT_COUNT, aeBack.getContentLength()); + assertEquals(DummyResponse.DUMMY_DEFAULT_STATUS, aeBack.getStatusCode()); + + assertEquals(DummyRequest.DUMMY_CONTENT_STRING, aeBack.getRequestContent()); + + assertEquals(DummyRequest.DUMMY_RESPONSE_CONTENT_STRING, aeBack.getResponseContent()); + + assertEquals(DummyRequest.DUMMY_DEFAULT_ATTR_MAP.get("testKey"), aeBack.getAttribute("testKey")); + } + + // Web containers may (and will) recycle requests objects. So we must make sure that after + // we prepared an event for deferred processing it won't be using data from the original + // HttpRequest object which may at that time represent another request + @Test + public void testAttributesAreNotTakenFromRecycledRequestWhenProcessingDeferred() { + + DummyRequest request = new DummyRequest(); + DummyResponse response = new DummyResponse(); + DummyServerAdapter adapter = new DummyServerAdapter(request, response); + + IAccessEvent event = new AccessEvent(request, response, adapter); + + request.setAttribute("testKey", "ORIGINAL"); + + event.prepareForDeferredProcessing(); + + request.setAttribute("testKey", "NEW"); + + // Event should capture the original value + assertEquals("ORIGINAL", event.getAttribute("testKey")); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/spi/PackageTest.java b/logback-access/src/test/java/ch/qos/logback/access/spi/PackageTest.java index 1038db56602ca94ce4874eb7e579049cc01e4ae1..a40373256e52dbc3b1e1ced9e29aeb5b59a8de71 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/spi/PackageTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/spi/PackageTest.java @@ -20,6 +20,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({AccessEventSerializationTest.class}) +@SuiteClasses({ AccessEventSerializationTest.class }) public class PackageTest extends TestCase { } \ No newline at end of file diff --git a/logback-access/src/test/java/ch/qos/logback/access/testUtil/NotifyingListAppender.java b/logback-access/src/test/java/ch/qos/logback/access/testUtil/NotifyingListAppender.java index 84fd57627c2322e91da555e1486e7bdbd9fa026e..5061c9fc4166285b0dd49a558bda075b44812c8b 100644 --- a/logback-access/src/test/java/ch/qos/logback/access/testUtil/NotifyingListAppender.java +++ b/logback-access/src/test/java/ch/qos/logback/access/testUtil/NotifyingListAppender.java @@ -20,9 +20,9 @@ import ch.qos.logback.core.AppenderBase; public class NotifyingListAppender extends AppenderBase { - public final LinkedBlockingQueue list = new LinkedBlockingQueue(); - - protected void append(IAccessEvent e) { - list.add(e); - } + public final LinkedBlockingQueue list = new LinkedBlockingQueue(); + + protected void append(IAccessEvent e) { + list.add(e); + } } diff --git a/logback-access/src/test/java/ch/qos/logback/access/tomcat/LogbackValveTest.java b/logback-access/src/test/java/ch/qos/logback/access/tomcat/LogbackValveTest.java index 038b43689464fcaa5ed43c85a369946432173ff6..48a21a23775d1ec84d27bc765ae7173a4fe09302 100755 --- a/logback-access/src/test/java/ch/qos/logback/access/tomcat/LogbackValveTest.java +++ b/logback-access/src/test/java/ch/qos/logback/access/tomcat/LogbackValveTest.java @@ -27,13 +27,12 @@ public class LogbackValveTest { LogbackValve valve = new LogbackValve(); StatusChecker checker = new StatusChecker(valve); - - @After + @After public void tearDown() { - System.clearProperty(LogbackValve.CATALINA_BASE_KEY); - System.clearProperty(LogbackValve.CATALINA_HOME_KEY); + System.clearProperty(LogbackValve.CATALINA_BASE_KEY); + System.clearProperty(LogbackValve.CATALINA_HOME_KEY); } - + @Test public void nonExistingConfigFileShouldResultInWarning() throws LifecycleException { final String resourceName = "logback-test2-config.xml"; @@ -44,7 +43,7 @@ public class LogbackValveTest { @Test public void fileUnderCatalinaBaseShouldBeFound() throws LifecycleException { - System.setProperty(LogbackValve.CATALINA_BASE_KEY, AccessTestConstants.JORAN_INPUT_PREFIX+"tomcat/"); + System.setProperty(LogbackValve.CATALINA_BASE_KEY, AccessTestConstants.JORAN_INPUT_PREFIX + "tomcat/"); final String fileName = "logback-access.xml"; setupValve(fileName); valve.start(); @@ -52,27 +51,27 @@ public class LogbackValveTest { checker.assertContainsMatch("Done configuring"); checker.assertIsErrorFree(); } - + @Test public void fileUnderCatalinaHomeShouldBeFound() throws LifecycleException { - System.setProperty(LogbackValve.CATALINA_HOME_KEY, AccessTestConstants.JORAN_INPUT_PREFIX+"tomcat/"); + System.setProperty(LogbackValve.CATALINA_HOME_KEY, AccessTestConstants.JORAN_INPUT_PREFIX + "tomcat/"); final String fileName = "logback-access.xml"; setupValve(fileName); valve.start(); checker.assertContainsMatch("Found configuration file"); checker.assertContainsMatch("Done configuring"); checker.assertIsErrorFree(); - } - + } + @Test public void resourceShouldBeFound() throws LifecycleException { final String fileName = "logback-asResource.xml"; setupValve(fileName); valve.start(); - checker.assertContainsMatch("Found ."+fileName+". as a resource."); + checker.assertContainsMatch("Found ." + fileName + ". as a resource."); checker.assertContainsMatch("Done configuring"); checker.assertIsErrorFree(); - } + } private void setupValve(final String resourceName) { valve.setFilename(resourceName); diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/AsyncAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/AsyncAppender.java index aa876b1cea63a7f3489e025479962d1dd10d3612..b514b8221d8ffeb3d3efadd7525690aec93304b2 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/AsyncAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/AsyncAppender.java @@ -27,32 +27,30 @@ import ch.qos.logback.core.AsyncAppenderBase; */ public class AsyncAppender extends AsyncAppenderBase { - - boolean includeCallerData = false; - - - /** - * Events of level TRACE, DEBUG and INFO are deemed to be discardable. - * @param event - * @return true if the event is of level TRACE, DEBUG or INFO false otherwise. - */ - protected boolean isDiscardable(ILoggingEvent event) { - Level level = event.getLevel(); - return level.toInt() <= Level.INFO_INT; - } - - protected void preprocess(ILoggingEvent eventObject) { - eventObject.prepareForDeferredProcessing(); - if(includeCallerData) - eventObject.getCallerData(); - } - - public boolean isIncludeCallerData() { - return includeCallerData; - } - - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } + boolean includeCallerData = false; + + /** + * Events of level TRACE, DEBUG and INFO are deemed to be discardable. + * @param event + * @return true if the event is of level TRACE, DEBUG or INFO false otherwise. + */ + protected boolean isDiscardable(ILoggingEvent event) { + Level level = event.getLevel(); + return level.toInt() <= Level.INFO_INT; + } + + protected void preprocess(ILoggingEvent eventObject) { + eventObject.prepareForDeferredProcessing(); + if (includeCallerData) + eventObject.getCallerData(); + } + + public boolean isIncludeCallerData() { + return includeCallerData; + } + + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/BasicConfigurator.java b/logback-classic/src/main/java/ch/qos/logback/classic/BasicConfigurator.java index fd1f46e7bf179c491c548d884a47cd89332e9e05..413703e4eae7cf864c40884fb585914ea9125be1 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/BasicConfigurator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/BasicConfigurator.java @@ -31,32 +31,32 @@ import ch.qos.logback.core.status.StatusManager; */ public class BasicConfigurator { - final static BasicConfigurator hiddenSingleton = new BasicConfigurator(); - - private BasicConfigurator() { - } - - public static void configure(LoggerContext lc) { - StatusManager sm = lc.getStatusManager(); - if(sm != null) { - sm.add(new InfoStatus("Setting up default configuration.", lc)); + final static BasicConfigurator hiddenSingleton = new BasicConfigurator(); + + private BasicConfigurator() { + } + + public static void configure(LoggerContext lc) { + StatusManager sm = lc.getStatusManager(); + if (sm != null) { + sm.add(new InfoStatus("Setting up default configuration.", lc)); + } + ConsoleAppender ca = new ConsoleAppender(); + ca.setContext(lc); + ca.setName("console"); + PatternLayoutEncoder pl = new PatternLayoutEncoder(); + pl.setContext(lc); + pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"); + pl.start(); + + ca.setEncoder(pl); + ca.start(); + Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + rootLogger.addAppender(ca); + } + + public static void configureDefaultContext() { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + configure(lc); } - ConsoleAppender ca = new ConsoleAppender(); - ca.setContext(lc); - ca.setName("console"); - PatternLayoutEncoder pl = new PatternLayoutEncoder(); - pl.setContext(lc); - pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"); - pl.start(); - - ca.setEncoder(pl); - ca.start(); - Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - rootLogger.addAppender(ca); - } - - public static void configureDefaultContext() { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - configure(lc); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/ClassicConstants.java b/logback-classic/src/main/java/ch/qos/logback/classic/ClassicConstants.java index a234d70496885faad9673d675bdfa3e225ab7776..21675b843d5920386bb7e5293fdc7c484813cb55 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/ClassicConstants.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/ClassicConstants.java @@ -17,35 +17,35 @@ import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class ClassicConstants { - public static final String USER_MDC_KEY = "user"; - - public static final String LOGBACK_CONTEXT_SELECTOR = "logback.ContextSelector"; - public static final String JNDI_CONFIGURATION_RESOURCE = "java:comp/env/logback/configuration-resource"; - public static final String JNDI_CONTEXT_NAME = "java:comp/env/logback/context-name"; - - /** - * The maximum number of package separators (dots) that abbreviation - * algorithms can handle. Class or logger names with more separators will have - * their first MAX_DOTS parts shortened. - * - */ - public static final int MAX_DOTS = 16; - - /** - * The default stack data depth computed during caller data extraction. - */ - public static final int DEFAULT_MAX_CALLEDER_DATA_DEPTH = 8; - - public static final String REQUEST_REMOTE_HOST_MDC_KEY = "req.remoteHost"; - public static final String REQUEST_USER_AGENT_MDC_KEY = "req.userAgent"; - public static final String REQUEST_REQUEST_URI = "req.requestURI"; - public static final String REQUEST_QUERY_STRING = "req.queryString"; - public static final String REQUEST_REQUEST_URL = "req.requestURL"; - public static final String REQUEST_METHOD = "req.method"; - public static final String REQUEST_X_FORWARDED_FOR = "req.xForwardedFor"; - - public static final String GAFFER_CONFIGURATOR_FQCN = "ch.qos.logback.classic.gaffer.GafferConfigurator"; - - public static final String FINALIZE_SESSION = "FINALIZE_SESSION"; - public static final Marker FINALIZE_SESSION_MARKER = MarkerFactory.getMarker(FINALIZE_SESSION); + public static final String USER_MDC_KEY = "user"; + + public static final String LOGBACK_CONTEXT_SELECTOR = "logback.ContextSelector"; + public static final String JNDI_CONFIGURATION_RESOURCE = "java:comp/env/logback/configuration-resource"; + public static final String JNDI_CONTEXT_NAME = "java:comp/env/logback/context-name"; + + /** + * The maximum number of package separators (dots) that abbreviation + * algorithms can handle. Class or logger names with more separators will have + * their first MAX_DOTS parts shortened. + * + */ + public static final int MAX_DOTS = 16; + + /** + * The default stack data depth computed during caller data extraction. + */ + public static final int DEFAULT_MAX_CALLEDER_DATA_DEPTH = 8; + + public static final String REQUEST_REMOTE_HOST_MDC_KEY = "req.remoteHost"; + public static final String REQUEST_USER_AGENT_MDC_KEY = "req.userAgent"; + public static final String REQUEST_REQUEST_URI = "req.requestURI"; + public static final String REQUEST_QUERY_STRING = "req.queryString"; + public static final String REQUEST_REQUEST_URL = "req.requestURL"; + public static final String REQUEST_METHOD = "req.method"; + public static final String REQUEST_X_FORWARDED_FOR = "req.xForwardedFor"; + + public static final String GAFFER_CONFIGURATOR_FQCN = "ch.qos.logback.classic.gaffer.GafferConfigurator"; + + public static final String FINALIZE_SESSION = "FINALIZE_SESSION"; + public static final Marker FINALIZE_SESSION_MARKER = MarkerFactory.getMarker(FINALIZE_SESSION); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/Level.java b/logback-classic/src/main/java/ch/qos/logback/classic/Level.java index 1b98529ab7e0ed87151d22afc7ff451a94417867..203c9b5de63cc1f976c24c354fb6cfd75ad84e9b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/Level.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/Level.java @@ -24,275 +24,272 @@ import org.slf4j.spi.LocationAwareLogger; */ public final class Level implements java.io.Serializable { - private static final long serialVersionUID = -814092767334282137L; + private static final long serialVersionUID = -814092767334282137L; - public static final int OFF_INT = Integer.MAX_VALUE; - public static final int ERROR_INT = 40000; - public static final int WARN_INT = 30000; - public static final int INFO_INT = 20000; - public static final int DEBUG_INT = 10000; - public static final int TRACE_INT = 5000; - public static final int ALL_INT = Integer.MIN_VALUE; + public static final int OFF_INT = Integer.MAX_VALUE; + public static final int ERROR_INT = 40000; + public static final int WARN_INT = 30000; + public static final int INFO_INT = 20000; + public static final int DEBUG_INT = 10000; + public static final int TRACE_INT = 5000; + public static final int ALL_INT = Integer.MIN_VALUE; - public static final Integer OFF_INTEGER = OFF_INT; - public static final Integer ERROR_INTEGER = ERROR_INT; - public static final Integer WARN_INTEGER = WARN_INT; - public static final Integer INFO_INTEGER = INFO_INT; - public static final Integer DEBUG_INTEGER = DEBUG_INT; - public static final Integer TRACE_INTEGER = TRACE_INT; - public static final Integer ALL_INTEGER = ALL_INT; + public static final Integer OFF_INTEGER = OFF_INT; + public static final Integer ERROR_INTEGER = ERROR_INT; + public static final Integer WARN_INTEGER = WARN_INT; + public static final Integer INFO_INTEGER = INFO_INT; + public static final Integer DEBUG_INTEGER = DEBUG_INT; + public static final Integer TRACE_INTEGER = TRACE_INT; + public static final Integer ALL_INTEGER = ALL_INT; - /** - * The OFF is used to turn off logging. - */ - public static final Level OFF = new Level(OFF_INT, "OFF"); + /** + * The OFF is used to turn off logging. + */ + public static final Level OFF = new Level(OFF_INT, "OFF"); - /** - * The ERROR level designates error events which may or not - * be fatal to the application. - */ - public static final Level ERROR = new Level(ERROR_INT, "ERROR"); + /** + * The ERROR level designates error events which may or not + * be fatal to the application. + */ + public static final Level ERROR = new Level(ERROR_INT, "ERROR"); - /** - * The WARN level designates potentially harmful situations. - */ - public static final Level WARN = new Level(WARN_INT, "WARN"); + /** + * The WARN level designates potentially harmful situations. + */ + public static final Level WARN = new Level(WARN_INT, "WARN"); - /** - * The INFO level designates informational messages - * highlighting overall progress of the application. - */ - public static final Level INFO = new Level(INFO_INT, "INFO"); + /** + * The INFO level designates informational messages + * highlighting overall progress of the application. + */ + public static final Level INFO = new Level(INFO_INT, "INFO"); - /** - * The DEBUG level designates informational events of lower - * importance. - */ - public static final Level DEBUG = new Level(DEBUG_INT, "DEBUG"); + /** + * The DEBUG level designates informational events of lower + * importance. + */ + public static final Level DEBUG = new Level(DEBUG_INT, "DEBUG"); - /** - * The TRACE level designates informational events of very low - * importance. - */ - public static final Level TRACE = new Level(TRACE_INT, "TRACE"); + /** + * The TRACE level designates informational events of very low + * importance. + */ + public static final Level TRACE = new Level(TRACE_INT, "TRACE"); - /** - * The ALL is used to turn on all logging. - */ - public static final Level ALL = new Level(ALL_INT, "ALL"); + /** + * The ALL is used to turn on all logging. + */ + public static final Level ALL = new Level(ALL_INT, "ALL"); - public final int levelInt; - public final String levelStr; + public final int levelInt; + public final String levelStr; - /** - * Instantiate a Level object. - */ - private Level(int levelInt, String levelStr) { - this.levelInt = levelInt; - this.levelStr = levelStr; - } + /** + * Instantiate a Level object. + */ + private Level(int levelInt, String levelStr) { + this.levelInt = levelInt; + this.levelStr = levelStr; + } - /** - * Returns the string representation of this Level. - */ - public String toString() { - return levelStr; - } + /** + * Returns the string representation of this Level. + */ + public String toString() { + return levelStr; + } - /** - * Returns the integer representation of this Level. - */ - public int toInt() { - return levelInt; - } + /** + * Returns the integer representation of this Level. + */ + public int toInt() { + return levelInt; + } - /** - * Convert a Level to an Integer object. - * - * @return This level's Integer mapping. - */ - public Integer toInteger() { - switch (levelInt) { - case ALL_INT: - return ALL_INTEGER; - case TRACE_INT: - return TRACE_INTEGER; - case DEBUG_INT: - return DEBUG_INTEGER; - case INFO_INT: - return INFO_INTEGER; - case WARN_INT: - return WARN_INTEGER; - case ERROR_INT: - return ERROR_INTEGER; - case OFF_INT: - return OFF_INTEGER; - default: - throw new IllegalStateException("Level " + levelStr + ", " + levelInt - + " is unknown."); + /** + * Convert a Level to an Integer object. + * + * @return This level's Integer mapping. + */ + public Integer toInteger() { + switch (levelInt) { + case ALL_INT: + return ALL_INTEGER; + case TRACE_INT: + return TRACE_INTEGER; + case DEBUG_INT: + return DEBUG_INTEGER; + case INFO_INT: + return INFO_INTEGER; + case WARN_INT: + return WARN_INTEGER; + case ERROR_INT: + return ERROR_INTEGER; + case OFF_INT: + return OFF_INTEGER; + default: + throw new IllegalStateException("Level " + levelStr + ", " + levelInt + " is unknown."); + } } - } - /** - * Returns true if this Level has a higher or equal Level than - * the Level passed as argument, false otherwise. - */ - public boolean isGreaterOrEqual(Level r) { - return levelInt >= r.levelInt; - } + /** + * Returns true if this Level has a higher or equal Level than + * the Level passed as argument, false otherwise. + */ + public boolean isGreaterOrEqual(Level r) { + return levelInt >= r.levelInt; + } - /** - * Convert the string passed as argument to a Level. If the conversion fails, - * then this method returns {@link #DEBUG}. - */ - public static Level toLevel(String sArg) { - return toLevel(sArg, Level.DEBUG); - } + /** + * Convert the string passed as argument to a Level. If the conversion fails, + * then this method returns {@link #DEBUG}. + */ + public static Level toLevel(String sArg) { + return toLevel(sArg, Level.DEBUG); + } + /** + * This method exists in order to comply with Joran's valueOf convention. + * + * @param sArg + * @return + */ + public static Level valueOf(String sArg) { + return toLevel(sArg, Level.DEBUG); + } - /** - * This method exists in order to comply with Joran's valueOf convention. - * - * @param sArg - * @return - */ - public static Level valueOf(String sArg) { - return toLevel(sArg, Level.DEBUG); - } + /** + * Convert an integer passed as argument to a Level. If the conversion fails, + * then this method returns {@link #DEBUG}. + */ + public static Level toLevel(int val) { + return toLevel(val, Level.DEBUG); + } + /** + * Convert an integer passed as argument to a Level. If the conversion fails, + * then this method returns the specified default. + */ + public static Level toLevel(int val, Level defaultLevel) { + switch (val) { + case ALL_INT: + return ALL; + case TRACE_INT: + return TRACE; + case DEBUG_INT: + return DEBUG; + case INFO_INT: + return INFO; + case WARN_INT: + return WARN; + case ERROR_INT: + return ERROR; + case OFF_INT: + return OFF; + default: + return defaultLevel; + } + } - /** - * Convert an integer passed as argument to a Level. If the conversion fails, - * then this method returns {@link #DEBUG}. - */ - public static Level toLevel(int val) { - return toLevel(val, Level.DEBUG); - } + /** + * Convert the string passed as argument to a Level. If the conversion fails, + * then this method returns the value of defaultLevel. + */ + public static Level toLevel(String sArg, Level defaultLevel) { + if (sArg == null) { + return defaultLevel; + } - /** - * Convert an integer passed as argument to a Level. If the conversion fails, - * then this method returns the specified default. - */ - public static Level toLevel(int val, Level defaultLevel) { - switch (val) { - case ALL_INT: - return ALL; - case TRACE_INT: - return TRACE; - case DEBUG_INT: - return DEBUG; - case INFO_INT: - return INFO; - case WARN_INT: - return WARN; - case ERROR_INT: - return ERROR; - case OFF_INT: - return OFF; - default: + if (sArg.equalsIgnoreCase("ALL")) { + return Level.ALL; + } + if (sArg.equalsIgnoreCase("TRACE")) { + return Level.TRACE; + } + if (sArg.equalsIgnoreCase("DEBUG")) { + return Level.DEBUG; + } + if (sArg.equalsIgnoreCase("INFO")) { + return Level.INFO; + } + if (sArg.equalsIgnoreCase("WARN")) { + return Level.WARN; + } + if (sArg.equalsIgnoreCase("ERROR")) { + return Level.ERROR; + } + if (sArg.equalsIgnoreCase("OFF")) { + return Level.OFF; + } return defaultLevel; } - } - /** - * Convert the string passed as argument to a Level. If the conversion fails, - * then this method returns the value of defaultLevel. - */ - public static Level toLevel(String sArg, Level defaultLevel) { - if (sArg == null) { - return defaultLevel; + /** + * Return the flyweight instance of the level received through serizalization, + * i.e. 'this'. + * + * @return The appropriate flyweight instance + */ + private Object readResolve() { + return toLevel(this.levelInt); } - if (sArg.equalsIgnoreCase("ALL")) { - return Level.ALL; - } - if (sArg.equalsIgnoreCase("TRACE")) { - return Level.TRACE; - } - if (sArg.equalsIgnoreCase("DEBUG")) { - return Level.DEBUG; - } - if (sArg.equalsIgnoreCase("INFO")) { - return Level.INFO; - } - if (sArg.equalsIgnoreCase("WARN")) { - return Level.WARN; - } - if (sArg.equalsIgnoreCase("ERROR")) { - return Level.ERROR; - } - if (sArg.equalsIgnoreCase("OFF")) { - return Level.OFF; - } - return defaultLevel; - } - - /** - * Return the flyweight instance of the level received through serizalization, - * i.e. 'this'. - * - * @return The appropriate flyweight instance - */ - private Object readResolve() { - return toLevel(this.levelInt); - } - - /** - * Convert one of the integer values defined in {@link LocationAwareLogger} - * interface to an instance of this class, i.e. a Level. - * - * @param levelInt An integer value representing a level as defined in LocationAwareLogger - * @return an instance of this class, i.e. a Level. - * @since 1.0.1 - */ - public static Level fromLocationAwareLoggerInteger(int levelInt) { - Level level; - switch (levelInt) { - case LocationAwareLogger.TRACE_INT: - level = TRACE; - break; - case LocationAwareLogger.DEBUG_INT: - level = DEBUG; - break; - case LocationAwareLogger.INFO_INT: - level = INFO; - break; - case LocationAwareLogger.WARN_INT: - level = WARN; - break; - case LocationAwareLogger.ERROR_INT: - level = ERROR; - break; - default: - throw new IllegalArgumentException(levelInt + " not a valid level value"); + /** + * Convert one of the integer values defined in {@link LocationAwareLogger} + * interface to an instance of this class, i.e. a Level. + * + * @param levelInt An integer value representing a level as defined in LocationAwareLogger + * @return an instance of this class, i.e. a Level. + * @since 1.0.1 + */ + public static Level fromLocationAwareLoggerInteger(int levelInt) { + Level level; + switch (levelInt) { + case LocationAwareLogger.TRACE_INT: + level = TRACE; + break; + case LocationAwareLogger.DEBUG_INT: + level = DEBUG; + break; + case LocationAwareLogger.INFO_INT: + level = INFO; + break; + case LocationAwareLogger.WARN_INT: + level = WARN; + break; + case LocationAwareLogger.ERROR_INT: + level = ERROR; + break; + default: + throw new IllegalArgumentException(levelInt + " not a valid level value"); + } + return level; } - return level; - } - /** - * Convert this level instance to an integer value defined in the - * {@link LocationAwareLogger} interface. - * - * @param level The level to convert to LocationAwareLogger integer - * @return int An integer corresponding to this level as defined in LocationAwareLogger - * @since 1.0.1 - */ - public static int toLocationAwareLoggerInteger(Level level) { - if (level == null) - throw new IllegalArgumentException("null level parameter is not admitted"); - switch (level.toInt()) { - case Level.TRACE_INT: - return LocationAwareLogger.TRACE_INT; - case Level.DEBUG_INT: - return LocationAwareLogger.DEBUG_INT; - case Level.INFO_INT: - return LocationAwareLogger.INFO_INT; - case Level.WARN_INT: - return LocationAwareLogger.WARN_INT; - case Level.ERROR_INT: - return LocationAwareLogger.ERROR_INT; - default: - throw new IllegalArgumentException(level + " not a valid level value"); + /** + * Convert this level instance to an integer value defined in the + * {@link LocationAwareLogger} interface. + * + * @param level The level to convert to LocationAwareLogger integer + * @return int An integer corresponding to this level as defined in LocationAwareLogger + * @since 1.0.1 + */ + public static int toLocationAwareLoggerInteger(Level level) { + if (level == null) + throw new IllegalArgumentException("null level parameter is not admitted"); + switch (level.toInt()) { + case Level.TRACE_INT: + return LocationAwareLogger.TRACE_INT; + case Level.DEBUG_INT: + return LocationAwareLogger.DEBUG_INT; + case Level.INFO_INT: + return LocationAwareLogger.INFO_INT; + case Level.WARN_INT: + return LocationAwareLogger.WARN_INT; + case Level.ERROR_INT: + return LocationAwareLogger.ERROR_INT; + default: + throw new IllegalArgumentException(level + " not a valid level value"); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/Logger.java b/logback-classic/src/main/java/ch/qos/logback/classic/Logger.java index 45424fbaa6cbb86de775e1985f97b2492aee172e..cea1cc845b306a797a9d952318e35c98d901cd72 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/Logger.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/Logger.java @@ -33,780 +33,758 @@ import ch.qos.logback.core.spi.AppenderAttachable; import ch.qos.logback.core.spi.AppenderAttachableImpl; import ch.qos.logback.core.spi.FilterReply; -public final class Logger implements org.slf4j.Logger, LocationAwareLogger, - AppenderAttachable, Serializable { - - private static final long serialVersionUID = 5454405123156820674L; //8745934908040027998L; - - /** - * The fully qualified name of this class. Used in gathering caller - * information. - */ - public static final String FQCN = ch.qos.logback.classic.Logger.class - .getName(); - - /** - * The name of this logger - */ - private String name; - - // The assigned levelInt of this logger. Can be null. - transient private Level level; - - // The effective levelInt is the assigned levelInt and if null, a levelInt is - // inherited form a parent. - transient private int effectiveLevelInt; - - /** - * The parent of this category. All categories have at least one ancestor - * which is the root category. - */ - transient private Logger parent; - - /** - * The children of this logger. A logger may have zero or more children. - */ - transient private List childrenList; - - /** - * It is assumed that once the 'aai' variable is set to a non-null value, it - * will never be reset to null. it is further assumed that only place where - * the 'aai'ariable is set is within the addAppender method. This method is - * synchronized on 'this' (Logger) protecting against simultaneous - * re-configuration of this logger (a very unlikely scenario). - * - *

- * It is further assumed that the AppenderAttachableImpl is responsible for - * its internal synchronization and thread safety. Thus, we can get away with - * *not* synchronizing on the 'aai' (check null/ read) because - *

- * 1) the 'aai' variable is immutable once set to non-null - *

- * 2) 'aai' is getAndSet only within addAppender which is synchronized - *

- * 3) all the other methods check whether 'aai' is null - *

- * 4) AppenderAttachableImpl is thread safe - */ - transient private AppenderAttachableImpl aai; - /** - * Additivity is set to true by default, that is children inherit the - * appenders of their ancestors by default. If this variable is set to - * false then the appenders located in the ancestors of this - * logger will not be used. However, the children of this logger will inherit - * its appenders, unless the children have their additivity flag set to - * false too. See the user manual for more details. - */ - transient private boolean additive = true; - - final transient LoggerContext loggerContext; - - Logger(String name, Logger parent, LoggerContext loggerContext) { - this.name = name; - this.parent = parent; - this.loggerContext = loggerContext; - } - - public Level getEffectiveLevel() { - return Level.toLevel(effectiveLevelInt); - } - - int getEffectiveLevelInt() { - return effectiveLevelInt; - } - - public Level getLevel() { - return level; - } - - public String getName() { - return name; - } - - private boolean isRootLogger() { - // only the root logger has a null parent - return parent == null; - } - - Logger getChildByName(final String childName) { - if (childrenList == null) { - return null; - } else { - int len = this.childrenList.size(); - for (int i = 0; i < len; i++) { - final Logger childLogger_i = (Logger) childrenList.get(i); - final String childName_i = childLogger_i.getName(); - - if (childName.equals(childName_i)) { - return childLogger_i; - } - } - // no child found - return null; - } - } - - public synchronized void setLevel(Level newLevel) { - if (level == newLevel) { - // nothing to do; - return; - } - if (newLevel == null && isRootLogger()) { - throw new IllegalArgumentException( - "The level of the root logger cannot be set to null"); - } - - level = newLevel; - if (newLevel == null) { - effectiveLevelInt = parent.effectiveLevelInt; - newLevel = parent.getEffectiveLevel(); - } else { - effectiveLevelInt = newLevel.levelInt; - } - - if (childrenList != null) { - int len = childrenList.size(); - for (int i = 0; i < len; i++) { - Logger child = (Logger) childrenList.get(i); - // tell child to handle parent levelInt change - child.handleParentLevelChange(effectiveLevelInt); - } - } - // inform listeners - loggerContext.fireOnLevelChange(this, newLevel); - } - - /** - * This method is invoked by parent logger to let this logger know that the - * prent's levelInt changed. - * - * @param newParentLevelInt - */ - private synchronized void handleParentLevelChange(int newParentLevelInt) { - // changes in the parent levelInt affect children only if their levelInt is - // null - if (level == null) { - effectiveLevelInt = newParentLevelInt; - - // propagate the parent levelInt change to this logger's children - if (childrenList != null) { - int len = childrenList.size(); - for (int i = 0; i < len; i++) { - Logger child = (Logger) childrenList.get(i); - child.handleParentLevelChange(newParentLevelInt); - } - } - } - } - - /** - * Remove all previously added appenders from this logger instance. - *

- * This is useful when re-reading configuration information. - */ - public void detachAndStopAllAppenders() { - if (aai != null) { - aai.detachAndStopAllAppenders(); - } - } - - public boolean detachAppender(String name) { - if (aai == null) { - return false; - } - return aai.detachAppender(name); - } - - // this method MUST be synchronized. See comments on 'aai' field for further - // details. - public synchronized void addAppender(Appender newAppender) { - if (aai == null) { - aai = new AppenderAttachableImpl(); - } - aai.addAppender(newAppender); - } - - public boolean isAttached(Appender appender) { - if (aai == null) { - return false; - } - return aai.isAttached(appender); - } - - @SuppressWarnings("unchecked") - public Iterator> iteratorForAppenders() { - if (aai == null) { - return Collections.EMPTY_LIST.iterator(); - } - return aai.iteratorForAppenders(); - } - - public Appender getAppender(String name) { - if (aai == null) { - return null; - } - return aai.getAppender(name); - } - - /** - * Invoke all the appenders of this logger. - * - * @param event - * The event to log - */ - public void callAppenders(ILoggingEvent event) { - int writes = 0; - for (Logger l = this; l != null; l = l.parent) { - writes += l.appendLoopOnAppenders(event); - if (!l.additive) { - break; - } - } - // No appenders in hierarchy - if (writes == 0) { - loggerContext.noAppenderDefinedWarning(this); - } - } - - private int appendLoopOnAppenders(ILoggingEvent event) { - if (aai != null) { - return aai.appendLoopOnAppenders(event); - } else { - return 0; - } - } - - /** - * Remove the appender passed as parameter form the list of appenders. - */ - public boolean detachAppender(Appender appender) { - if (aai == null) { - return false; - } - return aai.detachAppender(appender); - } - - - - /** - * Create a child of this logger by suffix, that is, the part of the name - * extending this logger. For example, if this logger is named "x.y" and the - * lastPart is "z", then the created child logger will be named "x.y.z". - * - *

- * IMPORTANT: Calls to this method must be within a synchronized block on this - * logger. - * - * @param lastPart - * the suffix (i.e. last part) of the child logger name. This - * parameter may not include dots, i.e. the logger separator - * character. - * @return - */ - Logger createChildByLastNamePart(final String lastPart) { - int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart); - if (i_index != -1) { - throw new IllegalArgumentException("Child name [" + lastPart - + " passed as parameter, may not include [" + CoreConstants.DOT + "]"); - } - - if (childrenList == null) { - childrenList = new ArrayList(); - } - Logger childLogger; - if (this.isRootLogger()) { - childLogger = new Logger(lastPart, this, this.loggerContext); - } else { - childLogger = new Logger(name + CoreConstants.DOT + lastPart, this, - this.loggerContext); - } - childrenList.add(childLogger); - childLogger.effectiveLevelInt = this.effectiveLevelInt; - return childLogger; - } - - private void localLevelReset() { - effectiveLevelInt = Level.DEBUG_INT; - if (isRootLogger()) { - level = Level.DEBUG; - } else { - level = null; - } - } - - void recursiveReset() { - detachAndStopAllAppenders(); - localLevelReset(); - additive = true; - if (childrenList == null) { - return; - } - for (Logger childLogger : childrenList) { - childLogger.recursiveReset(); - } - } - - /** - * The default size of child list arrays. The JDK 1.5 default is 10. We use a - * smaller value to save a little space. - */ - private static final int DEFAULT_CHILD_ARRAY_SIZE = 5; - - Logger createChildByName(final String childName) { - int i_index = LoggerNameUtil.getSeparatorIndexOf(childName, this.name.length() + 1); - if (i_index != -1) { - throw new IllegalArgumentException("For logger [" + this.name - + "] child name [" + childName - + " passed as parameter, may not include '.' after index" - + (this.name.length() + 1)); - } - - if (childrenList == null) { - childrenList = new ArrayList(DEFAULT_CHILD_ARRAY_SIZE); - } - Logger childLogger; - childLogger = new Logger(childName, this, this.loggerContext); - childrenList.add(childLogger); - childLogger.effectiveLevelInt = this.effectiveLevelInt; - return childLogger; - } - - /** - * The next methods are not merged into one because of the time we gain by not - * creating a new Object[] with the params. This reduces the cost of not - * logging by about 20 nanoseconds. - */ - - private void filterAndLog_0_Or3Plus(final String localFQCN, - final Marker marker, final Level level, final String msg, - final Object[] params, final Throwable t) { - - final FilterReply decision = loggerContext - .getTurboFilterChainDecision_0_3OrMore(marker, this, level, msg, - params, t); - - if (decision == FilterReply.NEUTRAL) { - if (effectiveLevelInt > level.levelInt) { - return; - } - } else if (decision == FilterReply.DENY) { - return; - } - - buildLoggingEventAndAppend(localFQCN, marker, level, msg, params, t); - } - - private void filterAndLog_1(final String localFQCN, - final Marker marker, final Level level, final String msg, - final Object param, final Throwable t) { - - final FilterReply decision = loggerContext.getTurboFilterChainDecision_1( - marker, this, level, msg, param, t); - - if (decision == FilterReply.NEUTRAL) { - if (effectiveLevelInt > level.levelInt) { - return; - } - } else if (decision == FilterReply.DENY) { - return; - } - - buildLoggingEventAndAppend(localFQCN, marker, level, msg, - new Object[] { param }, t); - } - - private void filterAndLog_2(final String localFQCN, - final Marker marker, final Level level, final String msg, - final Object param1, final Object param2, final Throwable t) { - - final FilterReply decision = loggerContext.getTurboFilterChainDecision_2( - marker, this, level, msg, param1, param2, t); - - if (decision == FilterReply.NEUTRAL) { - if (effectiveLevelInt > level.levelInt) { - return; - } - } else if (decision == FilterReply.DENY) { - return; - } - - buildLoggingEventAndAppend(localFQCN, marker, level, msg, new Object[] { - param1, param2 }, t); - } - - private void buildLoggingEventAndAppend(final String localFQCN, - final Marker marker, final Level level, final String msg, - final Object[] params, final Throwable t) { - LoggingEvent le = new LoggingEvent(localFQCN, this, level, msg, t, params); - le.setMarker(marker); - callAppenders(le); - } - - public void trace(String msg) { - filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, null); - } - - public void trace(String format, Object arg) { - filterAndLog_1(FQCN, null, Level.TRACE, format, arg, null); - } - - public void trace(String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, null, Level.TRACE, format, arg1, arg2, null); - } - - public void trace(String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, format, argArray, null); - } - - public void trace(String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, t); - } - - public void trace(Marker marker, String msg) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, null); - } - - public void trace(Marker marker, String format, Object arg) { - filterAndLog_1(FQCN, marker, Level.TRACE, format, arg, null); - } - - public void trace(Marker marker, String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, marker, Level.TRACE, format, arg1, arg2, null); - } - - public void trace(Marker marker, String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, format, argArray, null); - } - - public void trace(Marker marker, String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, t); - } - - public boolean isDebugEnabled() { - return isDebugEnabled(null); - } - - public boolean isDebugEnabled(Marker marker) { - final FilterReply decision = callTurboFilters(marker, Level.DEBUG); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= Level.DEBUG_INT; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - } - - public void debug(String msg) { - filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, null); - } - - public void debug(String format, Object arg) { - filterAndLog_1(FQCN, null, Level.DEBUG, format, arg, null); - } - - public void debug(String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, null, Level.DEBUG, format, arg1, arg2, null); - } - - public void debug(String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, format, argArray, null); - } - - public void debug(String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, t); - } - - public void debug(Marker marker, String msg) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, null); - } - - public void debug(Marker marker, String format, Object arg) { - filterAndLog_1(FQCN, marker, Level.DEBUG, format, arg, null); - } - - public void debug(Marker marker, String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, marker, Level.DEBUG, format, arg1, arg2, null); - } - - public void debug(Marker marker, String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, format, argArray, null); - } - - public void debug(Marker marker, String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, t); - } - - public void error(String msg) { - filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, null); - } - - public void error(String format, Object arg) { - filterAndLog_1(FQCN, null, Level.ERROR, format, arg, null); - } - - public void error(String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, null, Level.ERROR, format, arg1, arg2, null); - } - - public void error(String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, format, argArray, null); - } - - public void error(String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, t); - } - - public void error(Marker marker, String msg) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, null); - } - - public void error(Marker marker, String format, Object arg) { - filterAndLog_1(FQCN, marker, Level.ERROR, format, arg, null); - } - - public void error(Marker marker, String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, marker, Level.ERROR, format, arg1, arg2, null); - } - - public void error(Marker marker, String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, format, argArray, null); - } - - public void error(Marker marker, String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, t); - } - - public boolean isInfoEnabled() { - return isInfoEnabled(null); - } - - public boolean isInfoEnabled(Marker marker) { - FilterReply decision = callTurboFilters(marker, Level.INFO); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= Level.INFO_INT; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - } - - public void info(String msg) { - filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, null); - } - - public void info(String format, Object arg) { - filterAndLog_1(FQCN, null, Level.INFO, format, arg, null); - } - - public void info(String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, null, Level.INFO, format, arg1, arg2, null); - } - - public void info(String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, format, argArray, null); - } - - public void info(String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, t); - } - - public void info(Marker marker, String msg) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, null); - } - - public void info(Marker marker, String format, Object arg) { - filterAndLog_1(FQCN, marker, Level.INFO, format, arg, null); - } - - public void info(Marker marker, String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, marker, Level.INFO, format, arg1, arg2, null); - } - - public void info(Marker marker, String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, format, argArray, null); - } - - public void info(Marker marker, String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, t); - } - - public boolean isTraceEnabled() { - return isTraceEnabled(null); - } - - public boolean isTraceEnabled(Marker marker) { - final FilterReply decision = callTurboFilters(marker, Level.TRACE); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= Level.TRACE_INT; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - } - - public boolean isErrorEnabled() { - return isErrorEnabled(null); - } - - public boolean isErrorEnabled(Marker marker) { - FilterReply decision = callTurboFilters(marker, Level.ERROR); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= Level.ERROR_INT; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - } - - public boolean isWarnEnabled() { - return isWarnEnabled(null); - } - - public boolean isWarnEnabled(Marker marker) { - FilterReply decision = callTurboFilters(marker, Level.WARN); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= Level.WARN_INT; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - - } - - public boolean isEnabledFor(Marker marker, Level level) { - FilterReply decision = callTurboFilters(marker, level); - if (decision == FilterReply.NEUTRAL) { - return effectiveLevelInt <= level.levelInt; - } else if (decision == FilterReply.DENY) { - return false; - } else if (decision == FilterReply.ACCEPT) { - return true; - } else { - throw new IllegalStateException("Unknown FilterReply value: " + decision); - } - } - - public boolean isEnabledFor(Level level) { - return isEnabledFor(null, level); - } - - public void warn(String msg) { - filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, null); - } - - public void warn(String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, t); - } - - public void warn(String format, Object arg) { - filterAndLog_1(FQCN, null, Level.WARN, format, arg, null); - } - - public void warn(String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, null, Level.WARN, format, arg1, arg2, null); - } - - public void warn(String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, format, argArray, null); - } - - public void warn(Marker marker, String msg) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, null); - } - - public void warn(Marker marker, String format, Object arg) { - filterAndLog_1(FQCN, marker, Level.WARN, format, arg, null); - } - - public void warn(Marker marker, String format, Object... argArray) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, format, argArray, null); - } - - public void warn(Marker marker, String format, Object arg1, Object arg2) { - filterAndLog_2(FQCN, marker, Level.WARN, format, arg1, arg2, null); - } - - public void warn(Marker marker, String msg, Throwable t) { - filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, t); - } - - public boolean isAdditive() { - return additive; - } - - public void setAdditive(boolean additive) { - this.additive = additive; - } - - public String toString() { - return "Logger[" + name + "]"; - } - - /** - * Method that calls the attached TurboFilter objects based on the logger and - * the level. - * - * It is used by isYYYEnabled() methods. - * - * It returns the typical FilterReply values: ACCEPT, NEUTRAL or DENY. - * - * @param level - * @return the reply given by the TurboFilters - */ - private FilterReply callTurboFilters(Marker marker, Level level) { - return loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this, - level, null, null, null); - } - - /** - * Return the context for this logger. - * - * @return the context - */ - public LoggerContext getLoggerContext() { - return loggerContext; - } - - public void log(Marker marker, String fqcn, int levelInt, String message, - Object[] argArray, Throwable t) { - Level level = Level.fromLocationAwareLoggerInteger(levelInt); - filterAndLog_0_Or3Plus(fqcn, marker, level, message, argArray, t); - } - - /** - * Support SLF4J interception during initialization as introduced in SLF4J version 1.7.15 - * @since 1.1.4 - * @param slf4jEvent - */ - public void log(org.slf4j.event.LoggingEvent slf4jEvent) { - Level level = Level.fromLocationAwareLoggerInteger(slf4jEvent.getLevel().toInt()); - filterAndLog_0_Or3Plus(FQCN, slf4jEvent.getMarker(), level, slf4jEvent.getMessage(), slf4jEvent.getArgumentArray(), slf4jEvent.getThrowable()); - } - - /** - * After serialization, the logger instance does not know its LoggerContext. - * The best we can do here, is to return a logger with the same name - * returned by org.slf4j.LoggerFactory. - * - * @return Logger instance with the same name - * @throws ObjectStreamException - */ - protected Object readResolve() throws ObjectStreamException { - return LoggerFactory.getLogger(getName()); - } +public final class Logger implements org.slf4j.Logger, LocationAwareLogger, AppenderAttachable, Serializable { + + private static final long serialVersionUID = 5454405123156820674L; // 8745934908040027998L; + + /** + * The fully qualified name of this class. Used in gathering caller + * information. + */ + public static final String FQCN = ch.qos.logback.classic.Logger.class.getName(); + + /** + * The name of this logger + */ + private String name; + + // The assigned levelInt of this logger. Can be null. + transient private Level level; + + // The effective levelInt is the assigned levelInt and if null, a levelInt is + // inherited form a parent. + transient private int effectiveLevelInt; + + /** + * The parent of this category. All categories have at least one ancestor + * which is the root category. + */ + transient private Logger parent; + + /** + * The children of this logger. A logger may have zero or more children. + */ + transient private List childrenList; + + /** + * It is assumed that once the 'aai' variable is set to a non-null value, it + * will never be reset to null. it is further assumed that only place where + * the 'aai'ariable is set is within the addAppender method. This method is + * synchronized on 'this' (Logger) protecting against simultaneous + * re-configuration of this logger (a very unlikely scenario). + * + *

+ * It is further assumed that the AppenderAttachableImpl is responsible for + * its internal synchronization and thread safety. Thus, we can get away with + * *not* synchronizing on the 'aai' (check null/ read) because + *

+ * 1) the 'aai' variable is immutable once set to non-null + *

+ * 2) 'aai' is getAndSet only within addAppender which is synchronized + *

+ * 3) all the other methods check whether 'aai' is null + *

+ * 4) AppenderAttachableImpl is thread safe + */ + transient private AppenderAttachableImpl aai; + /** + * Additivity is set to true by default, that is children inherit the + * appenders of their ancestors by default. If this variable is set to + * false then the appenders located in the ancestors of this + * logger will not be used. However, the children of this logger will inherit + * its appenders, unless the children have their additivity flag set to + * false too. See the user manual for more details. + */ + transient private boolean additive = true; + + final transient LoggerContext loggerContext; + + Logger(String name, Logger parent, LoggerContext loggerContext) { + this.name = name; + this.parent = parent; + this.loggerContext = loggerContext; + } + + public Level getEffectiveLevel() { + return Level.toLevel(effectiveLevelInt); + } + + int getEffectiveLevelInt() { + return effectiveLevelInt; + } + + public Level getLevel() { + return level; + } + + public String getName() { + return name; + } + + private boolean isRootLogger() { + // only the root logger has a null parent + return parent == null; + } + + Logger getChildByName(final String childName) { + if (childrenList == null) { + return null; + } else { + int len = this.childrenList.size(); + for (int i = 0; i < len; i++) { + final Logger childLogger_i = (Logger) childrenList.get(i); + final String childName_i = childLogger_i.getName(); + + if (childName.equals(childName_i)) { + return childLogger_i; + } + } + // no child found + return null; + } + } + + public synchronized void setLevel(Level newLevel) { + if (level == newLevel) { + // nothing to do; + return; + } + if (newLevel == null && isRootLogger()) { + throw new IllegalArgumentException("The level of the root logger cannot be set to null"); + } + + level = newLevel; + if (newLevel == null) { + effectiveLevelInt = parent.effectiveLevelInt; + newLevel = parent.getEffectiveLevel(); + } else { + effectiveLevelInt = newLevel.levelInt; + } + + if (childrenList != null) { + int len = childrenList.size(); + for (int i = 0; i < len; i++) { + Logger child = (Logger) childrenList.get(i); + // tell child to handle parent levelInt change + child.handleParentLevelChange(effectiveLevelInt); + } + } + // inform listeners + loggerContext.fireOnLevelChange(this, newLevel); + } + + /** + * This method is invoked by parent logger to let this logger know that the + * prent's levelInt changed. + * + * @param newParentLevelInt + */ + private synchronized void handleParentLevelChange(int newParentLevelInt) { + // changes in the parent levelInt affect children only if their levelInt is + // null + if (level == null) { + effectiveLevelInt = newParentLevelInt; + + // propagate the parent levelInt change to this logger's children + if (childrenList != null) { + int len = childrenList.size(); + for (int i = 0; i < len; i++) { + Logger child = (Logger) childrenList.get(i); + child.handleParentLevelChange(newParentLevelInt); + } + } + } + } + + /** + * Remove all previously added appenders from this logger instance. + *

+ * This is useful when re-reading configuration information. + */ + public void detachAndStopAllAppenders() { + if (aai != null) { + aai.detachAndStopAllAppenders(); + } + } + + public boolean detachAppender(String name) { + if (aai == null) { + return false; + } + return aai.detachAppender(name); + } + + // this method MUST be synchronized. See comments on 'aai' field for further + // details. + public synchronized void addAppender(Appender newAppender) { + if (aai == null) { + aai = new AppenderAttachableImpl(); + } + aai.addAppender(newAppender); + } + + public boolean isAttached(Appender appender) { + if (aai == null) { + return false; + } + return aai.isAttached(appender); + } + + @SuppressWarnings("unchecked") + public Iterator> iteratorForAppenders() { + if (aai == null) { + return Collections.EMPTY_LIST.iterator(); + } + return aai.iteratorForAppenders(); + } + + public Appender getAppender(String name) { + if (aai == null) { + return null; + } + return aai.getAppender(name); + } + + /** + * Invoke all the appenders of this logger. + * + * @param event + * The event to log + */ + public void callAppenders(ILoggingEvent event) { + int writes = 0; + for (Logger l = this; l != null; l = l.parent) { + writes += l.appendLoopOnAppenders(event); + if (!l.additive) { + break; + } + } + // No appenders in hierarchy + if (writes == 0) { + loggerContext.noAppenderDefinedWarning(this); + } + } + + private int appendLoopOnAppenders(ILoggingEvent event) { + if (aai != null) { + return aai.appendLoopOnAppenders(event); + } else { + return 0; + } + } + + /** + * Remove the appender passed as parameter form the list of appenders. + */ + public boolean detachAppender(Appender appender) { + if (aai == null) { + return false; + } + return aai.detachAppender(appender); + } + + /** + * Create a child of this logger by suffix, that is, the part of the name + * extending this logger. For example, if this logger is named "x.y" and the + * lastPart is "z", then the created child logger will be named "x.y.z". + * + *

+ * IMPORTANT: Calls to this method must be within a synchronized block on this + * logger. + * + * @param lastPart + * the suffix (i.e. last part) of the child logger name. This + * parameter may not include dots, i.e. the logger separator + * character. + * @return + */ + Logger createChildByLastNamePart(final String lastPart) { + int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart); + if (i_index != -1) { + throw new IllegalArgumentException("Child name [" + lastPart + " passed as parameter, may not include [" + CoreConstants.DOT + "]"); + } + + if (childrenList == null) { + childrenList = new ArrayList(); + } + Logger childLogger; + if (this.isRootLogger()) { + childLogger = new Logger(lastPart, this, this.loggerContext); + } else { + childLogger = new Logger(name + CoreConstants.DOT + lastPart, this, this.loggerContext); + } + childrenList.add(childLogger); + childLogger.effectiveLevelInt = this.effectiveLevelInt; + return childLogger; + } + + private void localLevelReset() { + effectiveLevelInt = Level.DEBUG_INT; + if (isRootLogger()) { + level = Level.DEBUG; + } else { + level = null; + } + } + + void recursiveReset() { + detachAndStopAllAppenders(); + localLevelReset(); + additive = true; + if (childrenList == null) { + return; + } + for (Logger childLogger : childrenList) { + childLogger.recursiveReset(); + } + } + + /** + * The default size of child list arrays. The JDK 1.5 default is 10. We use a + * smaller value to save a little space. + */ + private static final int DEFAULT_CHILD_ARRAY_SIZE = 5; + + Logger createChildByName(final String childName) { + int i_index = LoggerNameUtil.getSeparatorIndexOf(childName, this.name.length() + 1); + if (i_index != -1) { + throw new IllegalArgumentException("For logger [" + this.name + "] child name [" + childName + + " passed as parameter, may not include '.' after index" + (this.name.length() + 1)); + } + + if (childrenList == null) { + childrenList = new ArrayList(DEFAULT_CHILD_ARRAY_SIZE); + } + Logger childLogger; + childLogger = new Logger(childName, this, this.loggerContext); + childrenList.add(childLogger); + childLogger.effectiveLevelInt = this.effectiveLevelInt; + return childLogger; + } + + /** + * The next methods are not merged into one because of the time we gain by not + * creating a new Object[] with the params. This reduces the cost of not + * logging by about 20 nanoseconds. + */ + + private void filterAndLog_0_Or3Plus(final String localFQCN, final Marker marker, final Level level, final String msg, final Object[] params, + final Throwable t) { + + final FilterReply decision = loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this, level, msg, params, t); + + if (decision == FilterReply.NEUTRAL) { + if (effectiveLevelInt > level.levelInt) { + return; + } + } else if (decision == FilterReply.DENY) { + return; + } + + buildLoggingEventAndAppend(localFQCN, marker, level, msg, params, t); + } + + private void filterAndLog_1(final String localFQCN, final Marker marker, final Level level, final String msg, final Object param, final Throwable t) { + + final FilterReply decision = loggerContext.getTurboFilterChainDecision_1(marker, this, level, msg, param, t); + + if (decision == FilterReply.NEUTRAL) { + if (effectiveLevelInt > level.levelInt) { + return; + } + } else if (decision == FilterReply.DENY) { + return; + } + + buildLoggingEventAndAppend(localFQCN, marker, level, msg, new Object[] { param }, t); + } + + private void filterAndLog_2(final String localFQCN, final Marker marker, final Level level, final String msg, final Object param1, final Object param2, + final Throwable t) { + + final FilterReply decision = loggerContext.getTurboFilterChainDecision_2(marker, this, level, msg, param1, param2, t); + + if (decision == FilterReply.NEUTRAL) { + if (effectiveLevelInt > level.levelInt) { + return; + } + } else if (decision == FilterReply.DENY) { + return; + } + + buildLoggingEventAndAppend(localFQCN, marker, level, msg, new Object[] { param1, param2 }, t); + } + + private void buildLoggingEventAndAppend(final String localFQCN, final Marker marker, final Level level, final String msg, final Object[] params, + final Throwable t) { + LoggingEvent le = new LoggingEvent(localFQCN, this, level, msg, t, params); + le.setMarker(marker); + callAppenders(le); + } + + public void trace(String msg) { + filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, null); + } + + public void trace(String format, Object arg) { + filterAndLog_1(FQCN, null, Level.TRACE, format, arg, null); + } + + public void trace(String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, null, Level.TRACE, format, arg1, arg2, null); + } + + public void trace(String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, format, argArray, null); + } + + public void trace(String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, null, Level.TRACE, msg, null, t); + } + + public void trace(Marker marker, String msg) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, null); + } + + public void trace(Marker marker, String format, Object arg) { + filterAndLog_1(FQCN, marker, Level.TRACE, format, arg, null); + } + + public void trace(Marker marker, String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, marker, Level.TRACE, format, arg1, arg2, null); + } + + public void trace(Marker marker, String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, format, argArray, null); + } + + public void trace(Marker marker, String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.TRACE, msg, null, t); + } + + public boolean isDebugEnabled() { + return isDebugEnabled(null); + } + + public boolean isDebugEnabled(Marker marker) { + final FilterReply decision = callTurboFilters(marker, Level.DEBUG); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= Level.DEBUG_INT; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + } + + public void debug(String msg) { + filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, null); + } + + public void debug(String format, Object arg) { + filterAndLog_1(FQCN, null, Level.DEBUG, format, arg, null); + } + + public void debug(String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, null, Level.DEBUG, format, arg1, arg2, null); + } + + public void debug(String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, format, argArray, null); + } + + public void debug(String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, null, Level.DEBUG, msg, null, t); + } + + public void debug(Marker marker, String msg) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, null); + } + + public void debug(Marker marker, String format, Object arg) { + filterAndLog_1(FQCN, marker, Level.DEBUG, format, arg, null); + } + + public void debug(Marker marker, String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, marker, Level.DEBUG, format, arg1, arg2, null); + } + + public void debug(Marker marker, String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, format, argArray, null); + } + + public void debug(Marker marker, String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.DEBUG, msg, null, t); + } + + public void error(String msg) { + filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, null); + } + + public void error(String format, Object arg) { + filterAndLog_1(FQCN, null, Level.ERROR, format, arg, null); + } + + public void error(String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, null, Level.ERROR, format, arg1, arg2, null); + } + + public void error(String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, format, argArray, null); + } + + public void error(String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, null, Level.ERROR, msg, null, t); + } + + public void error(Marker marker, String msg) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, null); + } + + public void error(Marker marker, String format, Object arg) { + filterAndLog_1(FQCN, marker, Level.ERROR, format, arg, null); + } + + public void error(Marker marker, String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, marker, Level.ERROR, format, arg1, arg2, null); + } + + public void error(Marker marker, String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, format, argArray, null); + } + + public void error(Marker marker, String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.ERROR, msg, null, t); + } + + public boolean isInfoEnabled() { + return isInfoEnabled(null); + } + + public boolean isInfoEnabled(Marker marker) { + FilterReply decision = callTurboFilters(marker, Level.INFO); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= Level.INFO_INT; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + } + + public void info(String msg) { + filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, null); + } + + public void info(String format, Object arg) { + filterAndLog_1(FQCN, null, Level.INFO, format, arg, null); + } + + public void info(String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, null, Level.INFO, format, arg1, arg2, null); + } + + public void info(String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, format, argArray, null); + } + + public void info(String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, null, Level.INFO, msg, null, t); + } + + public void info(Marker marker, String msg) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, null); + } + + public void info(Marker marker, String format, Object arg) { + filterAndLog_1(FQCN, marker, Level.INFO, format, arg, null); + } + + public void info(Marker marker, String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, marker, Level.INFO, format, arg1, arg2, null); + } + + public void info(Marker marker, String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, format, argArray, null); + } + + public void info(Marker marker, String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.INFO, msg, null, t); + } + + public boolean isTraceEnabled() { + return isTraceEnabled(null); + } + + public boolean isTraceEnabled(Marker marker) { + final FilterReply decision = callTurboFilters(marker, Level.TRACE); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= Level.TRACE_INT; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + } + + public boolean isErrorEnabled() { + return isErrorEnabled(null); + } + + public boolean isErrorEnabled(Marker marker) { + FilterReply decision = callTurboFilters(marker, Level.ERROR); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= Level.ERROR_INT; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + } + + public boolean isWarnEnabled() { + return isWarnEnabled(null); + } + + public boolean isWarnEnabled(Marker marker) { + FilterReply decision = callTurboFilters(marker, Level.WARN); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= Level.WARN_INT; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + + } + + public boolean isEnabledFor(Marker marker, Level level) { + FilterReply decision = callTurboFilters(marker, level); + if (decision == FilterReply.NEUTRAL) { + return effectiveLevelInt <= level.levelInt; + } else if (decision == FilterReply.DENY) { + return false; + } else if (decision == FilterReply.ACCEPT) { + return true; + } else { + throw new IllegalStateException("Unknown FilterReply value: " + decision); + } + } + + public boolean isEnabledFor(Level level) { + return isEnabledFor(null, level); + } + + public void warn(String msg) { + filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, null); + } + + public void warn(String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, msg, null, t); + } + + public void warn(String format, Object arg) { + filterAndLog_1(FQCN, null, Level.WARN, format, arg, null); + } + + public void warn(String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, null, Level.WARN, format, arg1, arg2, null); + } + + public void warn(String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, null, Level.WARN, format, argArray, null); + } + + public void warn(Marker marker, String msg) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, null); + } + + public void warn(Marker marker, String format, Object arg) { + filterAndLog_1(FQCN, marker, Level.WARN, format, arg, null); + } + + public void warn(Marker marker, String format, Object... argArray) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, format, argArray, null); + } + + public void warn(Marker marker, String format, Object arg1, Object arg2) { + filterAndLog_2(FQCN, marker, Level.WARN, format, arg1, arg2, null); + } + + public void warn(Marker marker, String msg, Throwable t) { + filterAndLog_0_Or3Plus(FQCN, marker, Level.WARN, msg, null, t); + } + + public boolean isAdditive() { + return additive; + } + + public void setAdditive(boolean additive) { + this.additive = additive; + } + + public String toString() { + return "Logger[" + name + "]"; + } + + /** + * Method that calls the attached TurboFilter objects based on the logger and + * the level. + * + * It is used by isYYYEnabled() methods. + * + * It returns the typical FilterReply values: ACCEPT, NEUTRAL or DENY. + * + * @param level + * @return the reply given by the TurboFilters + */ + private FilterReply callTurboFilters(Marker marker, Level level) { + return loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this, level, null, null, null); + } + + /** + * Return the context for this logger. + * + * @return the context + */ + public LoggerContext getLoggerContext() { + return loggerContext; + } + + public void log(Marker marker, String fqcn, int levelInt, String message, Object[] argArray, Throwable t) { + Level level = Level.fromLocationAwareLoggerInteger(levelInt); + filterAndLog_0_Or3Plus(fqcn, marker, level, message, argArray, t); + } + + /** + * Support SLF4J interception during initialization as introduced in SLF4J version 1.7.15 + * @since 1.1.4 + * @param slf4jEvent + */ + public void log(org.slf4j.event.LoggingEvent slf4jEvent) { + Level level = Level.fromLocationAwareLoggerInteger(slf4jEvent.getLevel().toInt()); + filterAndLog_0_Or3Plus(FQCN, slf4jEvent.getMarker(), level, slf4jEvent.getMessage(), slf4jEvent.getArgumentArray(), slf4jEvent.getThrowable()); + } + + /** + * After serialization, the logger instance does not know its LoggerContext. + * The best we can do here, is to return a logger with the same name + * returned by org.slf4j.LoggerFactory. + * + * @return Logger instance with the same name + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + return LoggerFactory.getLogger(getName()); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/LoggerContext.java b/logback-classic/src/main/java/ch/qos/logback/classic/LoggerContext.java index fdb60b969496133a6565b514195c4cf0a5cf3d51..aa60bf8ebd57afb9909e22331a07e4bd22c41f7a 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/LoggerContext.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/LoggerContext.java @@ -49,332 +49,322 @@ import ch.qos.logback.core.status.WarnStatus; * * @author Ceki Gulcu */ -public class LoggerContext extends ContextBase implements ILoggerFactory, - LifeCycle { - - /** Default setting of packaging data in stack traces */ - public static final boolean DEFAULT_PACKAGING_DATA = false; - - final Logger root; - private int size; - private int noAppenderWarning = 0; - final private List loggerContextListenerList = new ArrayList(); - - private Map loggerCache; - - private LoggerContextVO loggerContextRemoteView; - private final TurboFilterList turboFilterList = new TurboFilterList(); - private boolean packagingDataEnabled = DEFAULT_PACKAGING_DATA; - - private int maxCallerDataDepth = ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH; - - int resetCount = 0; - private List frameworkPackages; - - public LoggerContext() { - super(); - this.loggerCache = new ConcurrentHashMap(); - - this.loggerContextRemoteView = new LoggerContextVO(this); - this.root = new Logger(Logger.ROOT_LOGGER_NAME, null, this); - this.root.setLevel(Level.DEBUG); - loggerCache.put(Logger.ROOT_LOGGER_NAME, root); - initEvaluatorMap(); - size = 1; - this.frameworkPackages = new ArrayList(); - } - - void initEvaluatorMap() { - putObject(EVALUATOR_MAP, new HashMap>()); - } - - - /** - * A new instance of LoggerContextRemoteView needs to be created each time the - * name or propertyMap (including keys or values) changes. - */ - private void updateLoggerContextVO() { - loggerContextRemoteView = new LoggerContextVO(this); - } - - @Override - public void putProperty(String key, String val) { - super.putProperty(key, val); - updateLoggerContextVO(); - } - - @Override - public void setName(String name) { - super.setName(name); - updateLoggerContextVO(); - } - - public final Logger getLogger(final Class clazz) { - return getLogger(clazz.getName()); - } - - @Override - public final Logger getLogger(final String name) { - - if (name == null) { - throw new IllegalArgumentException("name argument cannot be null"); - } - - // if we are asking for the root logger, then let us return it without - // wasting time - if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) { - return root; - } - - int i = 0; - Logger logger = root; - - // check if the desired logger exists, if it does, return it - // without further ado. - Logger childLogger = (Logger) loggerCache.get(name); - // if we have the child, then let us return it without wasting time - if (childLogger != null) { - return childLogger; - } - - // if the desired logger does not exist, them create all the loggers - // in between as well (if they don't already exist) - String childName; - while (true) { - int h = LoggerNameUtil.getSeparatorIndexOf(name, i); - if (h == -1) { - childName = name; - } else { - childName = name.substring(0, h); - } - // move i left of the last point - i = h + 1; - synchronized (logger) { - childLogger = logger.getChildByName(childName); - if (childLogger == null) { - childLogger = logger.createChildByName(childName); - loggerCache.put(childName, childLogger); - incSize(); +public class LoggerContext extends ContextBase implements ILoggerFactory, LifeCycle { + + /** Default setting of packaging data in stack traces */ + public static final boolean DEFAULT_PACKAGING_DATA = false; + + final Logger root; + private int size; + private int noAppenderWarning = 0; + final private List loggerContextListenerList = new ArrayList(); + + private Map loggerCache; + + private LoggerContextVO loggerContextRemoteView; + private final TurboFilterList turboFilterList = new TurboFilterList(); + private boolean packagingDataEnabled = DEFAULT_PACKAGING_DATA; + + private int maxCallerDataDepth = ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH; + + int resetCount = 0; + private List frameworkPackages; + + public LoggerContext() { + super(); + this.loggerCache = new ConcurrentHashMap(); + + this.loggerContextRemoteView = new LoggerContextVO(this); + this.root = new Logger(Logger.ROOT_LOGGER_NAME, null, this); + this.root.setLevel(Level.DEBUG); + loggerCache.put(Logger.ROOT_LOGGER_NAME, root); + initEvaluatorMap(); + size = 1; + this.frameworkPackages = new ArrayList(); + } + + void initEvaluatorMap() { + putObject(EVALUATOR_MAP, new HashMap>()); + } + + /** + * A new instance of LoggerContextRemoteView needs to be created each time the + * name or propertyMap (including keys or values) changes. + */ + private void updateLoggerContextVO() { + loggerContextRemoteView = new LoggerContextVO(this); + } + + @Override + public void putProperty(String key, String val) { + super.putProperty(key, val); + updateLoggerContextVO(); + } + + @Override + public void setName(String name) { + super.setName(name); + updateLoggerContextVO(); + } + + public final Logger getLogger(final Class clazz) { + return getLogger(clazz.getName()); + } + + @Override + public final Logger getLogger(final String name) { + + if (name == null) { + throw new IllegalArgumentException("name argument cannot be null"); + } + + // if we are asking for the root logger, then let us return it without + // wasting time + if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) { + return root; + } + + int i = 0; + Logger logger = root; + + // check if the desired logger exists, if it does, return it + // without further ado. + Logger childLogger = (Logger) loggerCache.get(name); + // if we have the child, then let us return it without wasting time + if (childLogger != null) { + return childLogger; + } + + // if the desired logger does not exist, them create all the loggers + // in between as well (if they don't already exist) + String childName; + while (true) { + int h = LoggerNameUtil.getSeparatorIndexOf(name, i); + if (h == -1) { + childName = name; + } else { + childName = name.substring(0, h); + } + // move i left of the last point + i = h + 1; + synchronized (logger) { + childLogger = logger.getChildByName(childName); + if (childLogger == null) { + childLogger = logger.createChildByName(childName); + loggerCache.put(childName, childLogger); + incSize(); + } + } + logger = childLogger; + if (h == -1) { + return childLogger; + } + } + } + + private void incSize() { + size++; + } + + int size() { + return size; + } + + /** + * Check if the named logger exists in the hierarchy. If so return its + * reference, otherwise returns null. + * + * @param name the name of the logger to search for. + */ + public Logger exists(String name) { + return (Logger) loggerCache.get(name); + } + + final void noAppenderDefinedWarning(final Logger logger) { + if (noAppenderWarning++ == 0) { + getStatusManager().add(new WarnStatus("No appenders present in context [" + getName() + "] for logger [" + logger.getName() + "].", logger)); + } + } + + public List getLoggerList() { + Collection collection = loggerCache.values(); + List loggerList = new ArrayList(collection); + Collections.sort(loggerList, new LoggerComparator()); + return loggerList; + } + + public LoggerContextVO getLoggerContextRemoteView() { + return loggerContextRemoteView; + } + + public void setPackagingDataEnabled(boolean packagingDataEnabled) { + this.packagingDataEnabled = packagingDataEnabled; + } + + public boolean isPackagingDataEnabled() { + return packagingDataEnabled; + } + + /** + * This method clears all internal properties, except internal status messages, + * closes all appenders, removes any turboFilters, fires an OnReset event, + * removes all status listeners, removes all context listeners + * (except those which are reset resistant). + *

+ * As mentioned above, internal status messages survive resets. + */ + @Override + public void reset() { + resetCount++; + super.reset(); + initEvaluatorMap(); + initCollisionMaps(); + root.recursiveReset(); + resetTurboFilterList(); + fireOnReset(); + resetListenersExceptResetResistant(); + resetStatusListeners(); + } + + private void resetStatusListeners() { + StatusManager sm = getStatusManager(); + for (StatusListener sl : sm.getCopyOfStatusListenerList()) { + sm.remove(sl); + } + } + + public TurboFilterList getTurboFilterList() { + return turboFilterList; + } + + public void addTurboFilter(TurboFilter newFilter) { + turboFilterList.add(newFilter); + } + + /** + * First processPriorToRemoval all registered turbo filters and then clear the registration + * list. + */ + public void resetTurboFilterList() { + for (TurboFilter tf : turboFilterList) { + tf.stop(); + } + turboFilterList.clear(); + } + + final FilterReply getTurboFilterChainDecision_0_3OrMore(final Marker marker, final Logger logger, final Level level, final String format, + final Object[] params, final Throwable t) { + if (turboFilterList.size() == 0) { + return FilterReply.NEUTRAL; + } + return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, params, t); + } + + final FilterReply getTurboFilterChainDecision_1(final Marker marker, final Logger logger, final Level level, final String format, final Object param, + final Throwable t) { + if (turboFilterList.size() == 0) { + return FilterReply.NEUTRAL; + } + return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param }, t); + } + + final FilterReply getTurboFilterChainDecision_2(final Marker marker, final Logger logger, final Level level, final String format, final Object param1, + final Object param2, final Throwable t) { + if (turboFilterList.size() == 0) { + return FilterReply.NEUTRAL; + } + return turboFilterList.getTurboFilterChainDecision(marker, logger, level, format, new Object[] { param1, param2 }, t); + } + + // === start listeners ============================================== + public void addListener(LoggerContextListener listener) { + loggerContextListenerList.add(listener); + } + + public void removeListener(LoggerContextListener listener) { + loggerContextListenerList.remove(listener); + } + + private void resetListenersExceptResetResistant() { + List toRetain = new ArrayList(); + + for (LoggerContextListener lcl : loggerContextListenerList) { + if (lcl.isResetResistant()) { + toRetain.add(lcl); + } + } + loggerContextListenerList.retainAll(toRetain); + } + + private void resetAllListeners() { + loggerContextListenerList.clear(); + } + + public List getCopyOfListenerList() { + return new ArrayList(loggerContextListenerList); + } + + void fireOnLevelChange(Logger logger, Level level) { + for (LoggerContextListener listener : loggerContextListenerList) { + listener.onLevelChange(logger, level); } - } - logger = childLogger; - if (h == -1) { - return childLogger; - } - } - } - - private void incSize() { - size++; - } - - int size() { - return size; - } - - /** - * Check if the named logger exists in the hierarchy. If so return its - * reference, otherwise returns null. - * - * @param name the name of the logger to search for. - */ - public Logger exists(String name) { - return (Logger) loggerCache.get(name); - } - - final void noAppenderDefinedWarning(final Logger logger) { - if (noAppenderWarning++ == 0) { - getStatusManager().add( - new WarnStatus("No appenders present in context [" + getName() - + "] for logger [" + logger.getName() + "].", logger)); - } - } - - public List getLoggerList() { - Collection collection = loggerCache.values(); - List loggerList = new ArrayList(collection); - Collections.sort(loggerList, new LoggerComparator()); - return loggerList; - } - - public LoggerContextVO getLoggerContextRemoteView() { - return loggerContextRemoteView; - } - - public void setPackagingDataEnabled(boolean packagingDataEnabled) { - this.packagingDataEnabled = packagingDataEnabled; - } - - public boolean isPackagingDataEnabled() { - return packagingDataEnabled; - } - - /** - * This method clears all internal properties, except internal status messages, - * closes all appenders, removes any turboFilters, fires an OnReset event, - * removes all status listeners, removes all context listeners - * (except those which are reset resistant). - *

- * As mentioned above, internal status messages survive resets. - */ - @Override - public void reset() { - resetCount++; - super.reset(); - initEvaluatorMap(); - initCollisionMaps(); - root.recursiveReset(); - resetTurboFilterList(); - fireOnReset(); - resetListenersExceptResetResistant(); - resetStatusListeners(); - } - - private void resetStatusListeners() { - StatusManager sm = getStatusManager(); - for (StatusListener sl : sm.getCopyOfStatusListenerList()) { - sm.remove(sl); - } - } - - public TurboFilterList getTurboFilterList() { - return turboFilterList; - } - - public void addTurboFilter(TurboFilter newFilter) { - turboFilterList.add(newFilter); - } - - /** - * First processPriorToRemoval all registered turbo filters and then clear the registration - * list. - */ - public void resetTurboFilterList() { - for (TurboFilter tf : turboFilterList) { - tf.stop(); - } - turboFilterList.clear(); - } - - final FilterReply getTurboFilterChainDecision_0_3OrMore(final Marker marker, - final Logger logger, final Level level, final String format, - final Object[] params, final Throwable t) { - if (turboFilterList.size() == 0) { - return FilterReply.NEUTRAL; - } - return turboFilterList.getTurboFilterChainDecision(marker, logger, level, - format, params, t); - } - - final FilterReply getTurboFilterChainDecision_1(final Marker marker, - final Logger logger, final Level level, final String format, - final Object param, final Throwable t) { - if (turboFilterList.size() == 0) { - return FilterReply.NEUTRAL; - } - return turboFilterList.getTurboFilterChainDecision(marker, logger, level, - format, new Object[]{param}, t); - } - - final FilterReply getTurboFilterChainDecision_2(final Marker marker, - final Logger logger, final Level level, final String format, - final Object param1, final Object param2, final Throwable t) { - if (turboFilterList.size() == 0) { - return FilterReply.NEUTRAL; - } - return turboFilterList.getTurboFilterChainDecision(marker, logger, level, - format, new Object[]{param1, param2}, t); - } - - // === start listeners ============================================== - public void addListener(LoggerContextListener listener) { - loggerContextListenerList.add(listener); - } - - public void removeListener(LoggerContextListener listener) { - loggerContextListenerList.remove(listener); - } - - private void resetListenersExceptResetResistant() { - List toRetain = new ArrayList(); - - for (LoggerContextListener lcl : loggerContextListenerList) { - if (lcl.isResetResistant()) { - toRetain.add(lcl); - } - } - loggerContextListenerList.retainAll(toRetain); - } - - private void resetAllListeners() { - loggerContextListenerList.clear(); - } - - public List getCopyOfListenerList() { - return new ArrayList(loggerContextListenerList); - } - - void fireOnLevelChange(Logger logger, Level level) { - for (LoggerContextListener listener : loggerContextListenerList) { - listener.onLevelChange(logger, level); - } - } - - private void fireOnReset() { - for (LoggerContextListener listener : loggerContextListenerList) { - listener.onReset(this); - } - } - - private void fireOnStart() { - for (LoggerContextListener listener : loggerContextListenerList) { - listener.onStart(this); - } - } - - private void fireOnStop() { - for (LoggerContextListener listener : loggerContextListenerList) { - listener.onStop(this); - } - } - - // === end listeners ============================================== - - public void start() { - super.start(); - fireOnStart(); - } - - public void stop() { - reset(); - fireOnStop(); - resetAllListeners(); - super.stop(); - } - - @Override - public String toString() { - return this.getClass().getName() + "[" + getName() + "]"; - } - - public int getMaxCallerDataDepth() { - return maxCallerDataDepth; - } - - public void setMaxCallerDataDepth(int maxCallerDataDepth) { - this.maxCallerDataDepth = maxCallerDataDepth; - } - - /** - * List of packages considered part of the logging framework such that they are never considered - * as callers of the logging framework. This list used to compute the caller for logging events. - *

- * To designate package "com.foo" as well as all its subpackages as being part of the logging framework, simply add - * "com.foo" to this list. - * - * @return list of framework packages - */ - public List getFrameworkPackages() { - return frameworkPackages; - } + } + + private void fireOnReset() { + for (LoggerContextListener listener : loggerContextListenerList) { + listener.onReset(this); + } + } + + private void fireOnStart() { + for (LoggerContextListener listener : loggerContextListenerList) { + listener.onStart(this); + } + } + + private void fireOnStop() { + for (LoggerContextListener listener : loggerContextListenerList) { + listener.onStop(this); + } + } + + // === end listeners ============================================== + + public void start() { + super.start(); + fireOnStart(); + } + + public void stop() { + reset(); + fireOnStop(); + resetAllListeners(); + super.stop(); + } + + @Override + public String toString() { + return this.getClass().getName() + "[" + getName() + "]"; + } + + public int getMaxCallerDataDepth() { + return maxCallerDataDepth; + } + + public void setMaxCallerDataDepth(int maxCallerDataDepth) { + this.maxCallerDataDepth = maxCallerDataDepth; + } + + /** + * List of packages considered part of the logging framework such that they are never considered + * as callers of the logging framework. This list used to compute the caller for logging events. + *

+ * To designate package "com.foo" as well as all its subpackages as being part of the logging framework, simply add + * "com.foo" to this list. + * + * @return list of framework packages + */ + public List getFrameworkPackages() { + return frameworkPackages; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/PatternLayout.java b/logback-classic/src/main/java/ch/qos/logback/classic/PatternLayout.java index 0d621960c6c25e7ddc30a6e94bff6a34681cf8d7..186c316acdcf152473f3f155c566f79991d52652 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/PatternLayout.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/PatternLayout.java @@ -38,119 +38,111 @@ import ch.qos.logback.core.pattern.parser.Parser; public class PatternLayout extends PatternLayoutBase { - public static final Map defaultConverterMap = new HashMap(); - public static final String HEADER_PREFIX = "#logback.classic pattern: "; - - static { - defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); - - defaultConverterMap.put("d", DateConverter.class.getName()); - defaultConverterMap.put("date", DateConverter.class.getName()); - - defaultConverterMap.put("r", RelativeTimeConverter.class.getName()); - defaultConverterMap.put("relative", RelativeTimeConverter.class.getName()); - - defaultConverterMap.put("level", LevelConverter.class.getName()); - defaultConverterMap.put("le", LevelConverter.class.getName()); - defaultConverterMap.put("p", LevelConverter.class.getName()); - - defaultConverterMap.put("t", ThreadConverter.class.getName()); - defaultConverterMap.put("thread", ThreadConverter.class.getName()); - - defaultConverterMap.put("lo", LoggerConverter.class.getName()); - defaultConverterMap.put("logger", LoggerConverter.class.getName()); - defaultConverterMap.put("c", LoggerConverter.class.getName()); - - defaultConverterMap.put("m", MessageConverter.class.getName()); - defaultConverterMap.put("msg", MessageConverter.class.getName()); - defaultConverterMap.put("message", MessageConverter.class.getName()); - - defaultConverterMap.put("C", ClassOfCallerConverter.class.getName()); - defaultConverterMap.put("class", ClassOfCallerConverter.class.getName()); - - defaultConverterMap.put("M", MethodOfCallerConverter.class.getName()); - defaultConverterMap.put("method", MethodOfCallerConverter.class.getName()); - - defaultConverterMap.put("L", LineOfCallerConverter.class.getName()); - defaultConverterMap.put("line", LineOfCallerConverter.class.getName()); - - defaultConverterMap.put("F", FileOfCallerConverter.class.getName()); - defaultConverterMap.put("file", FileOfCallerConverter.class.getName()); - - defaultConverterMap.put("X", MDCConverter.class.getName()); - defaultConverterMap.put("mdc", MDCConverter.class.getName()); - - defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName()); - defaultConverterMap.put("exception", ThrowableProxyConverter.class - .getName()); - defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName()); - defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class - .getName()); - defaultConverterMap.put("throwable", ThrowableProxyConverter.class - .getName()); - - defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName()); - defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class - .getName()); - defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class - .getName()); - - defaultConverterMap.put("nopex", NopThrowableInformationConverter.class - .getName()); - defaultConverterMap.put("nopexception", - NopThrowableInformationConverter.class.getName()); - - defaultConverterMap.put("cn", ContextNameConverter.class.getName()); - defaultConverterMap.put("contextName", ContextNameConverter.class.getName()); - - defaultConverterMap.put("caller", CallerDataConverter.class.getName()); - - defaultConverterMap.put("marker", MarkerConverter.class.getName()); - - defaultConverterMap.put("property", PropertyConverter.class.getName()); - - defaultConverterMap.put("n", LineSeparatorConverter.class.getName()); - - defaultConverterMap.put("black", BlackCompositeConverter.class.getName()); - defaultConverterMap.put("red", RedCompositeConverter.class.getName()); - defaultConverterMap.put("green", GreenCompositeConverter.class.getName()); - defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName()); - defaultConverterMap.put("blue", BlueCompositeConverter.class.getName()); - defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName()); - defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName()); - defaultConverterMap.put("white", WhiteCompositeConverter.class.getName()); - defaultConverterMap.put("gray", GrayCompositeConverter.class.getName()); - defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName()); - defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName()); - defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName()); - defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName()); - defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName()); - defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName()); - defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName()); - defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName()); - - defaultConverterMap.put("lsn", LocalSequenceNumberConverter.class.getName()); - - - } - - public PatternLayout() { - this.postCompileProcessor = new EnsureExceptionHandling(); - } - - public Map getDefaultConverterMap() { - return defaultConverterMap; - } - - public String doLayout(ILoggingEvent event) { - if (!isStarted()) { - return CoreConstants.EMPTY_STRING; + public static final Map defaultConverterMap = new HashMap(); + public static final String HEADER_PREFIX = "#logback.classic pattern: "; + + static { + defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); + + defaultConverterMap.put("d", DateConverter.class.getName()); + defaultConverterMap.put("date", DateConverter.class.getName()); + + defaultConverterMap.put("r", RelativeTimeConverter.class.getName()); + defaultConverterMap.put("relative", RelativeTimeConverter.class.getName()); + + defaultConverterMap.put("level", LevelConverter.class.getName()); + defaultConverterMap.put("le", LevelConverter.class.getName()); + defaultConverterMap.put("p", LevelConverter.class.getName()); + + defaultConverterMap.put("t", ThreadConverter.class.getName()); + defaultConverterMap.put("thread", ThreadConverter.class.getName()); + + defaultConverterMap.put("lo", LoggerConverter.class.getName()); + defaultConverterMap.put("logger", LoggerConverter.class.getName()); + defaultConverterMap.put("c", LoggerConverter.class.getName()); + + defaultConverterMap.put("m", MessageConverter.class.getName()); + defaultConverterMap.put("msg", MessageConverter.class.getName()); + defaultConverterMap.put("message", MessageConverter.class.getName()); + + defaultConverterMap.put("C", ClassOfCallerConverter.class.getName()); + defaultConverterMap.put("class", ClassOfCallerConverter.class.getName()); + + defaultConverterMap.put("M", MethodOfCallerConverter.class.getName()); + defaultConverterMap.put("method", MethodOfCallerConverter.class.getName()); + + defaultConverterMap.put("L", LineOfCallerConverter.class.getName()); + defaultConverterMap.put("line", LineOfCallerConverter.class.getName()); + + defaultConverterMap.put("F", FileOfCallerConverter.class.getName()); + defaultConverterMap.put("file", FileOfCallerConverter.class.getName()); + + defaultConverterMap.put("X", MDCConverter.class.getName()); + defaultConverterMap.put("mdc", MDCConverter.class.getName()); + + defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName()); + defaultConverterMap.put("exception", ThrowableProxyConverter.class.getName()); + defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName()); + defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class.getName()); + defaultConverterMap.put("throwable", ThrowableProxyConverter.class.getName()); + + defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName()); + defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class.getName()); + defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class.getName()); + + defaultConverterMap.put("nopex", NopThrowableInformationConverter.class.getName()); + defaultConverterMap.put("nopexception", NopThrowableInformationConverter.class.getName()); + + defaultConverterMap.put("cn", ContextNameConverter.class.getName()); + defaultConverterMap.put("contextName", ContextNameConverter.class.getName()); + + defaultConverterMap.put("caller", CallerDataConverter.class.getName()); + + defaultConverterMap.put("marker", MarkerConverter.class.getName()); + + defaultConverterMap.put("property", PropertyConverter.class.getName()); + + defaultConverterMap.put("n", LineSeparatorConverter.class.getName()); + + defaultConverterMap.put("black", BlackCompositeConverter.class.getName()); + defaultConverterMap.put("red", RedCompositeConverter.class.getName()); + defaultConverterMap.put("green", GreenCompositeConverter.class.getName()); + defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName()); + defaultConverterMap.put("blue", BlueCompositeConverter.class.getName()); + defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName()); + defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName()); + defaultConverterMap.put("white", WhiteCompositeConverter.class.getName()); + defaultConverterMap.put("gray", GrayCompositeConverter.class.getName()); + defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName()); + defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName()); + defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName()); + defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName()); + defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName()); + defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName()); + defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName()); + defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName()); + + defaultConverterMap.put("lsn", LocalSequenceNumberConverter.class.getName()); + } - return writeLoopOnConverters(event); - } - @Override - protected String getPresentationHeaderPrefix() { - return HEADER_PREFIX; - } + public PatternLayout() { + this.postCompileProcessor = new EnsureExceptionHandling(); + } + + public Map getDefaultConverterMap() { + return defaultConverterMap; + } + + public String doLayout(ILoggingEvent event) { + if (!isStarted()) { + return CoreConstants.EMPTY_STRING; + } + return writeLoopOnConverters(event); + } + + @Override + protected String getPresentationHeaderPrefix() { + return HEADER_PREFIX; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/ViewStatusMessagesServlet.java b/logback-classic/src/main/java/ch/qos/logback/classic/ViewStatusMessagesServlet.java index 9016a2f5f682c77e24d676d6004fe40fb1c43521..113aacabb3c15846ff589ccea4e845a6b2ddbc05 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/ViewStatusMessagesServlet.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/ViewStatusMessagesServlet.java @@ -23,20 +23,18 @@ import ch.qos.logback.core.status.ViewStatusMessagesServletBase; public class ViewStatusMessagesServlet extends ViewStatusMessagesServletBase { - private static final long serialVersionUID = 443878494348593337L; - - - @Override - protected StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - return lc.getStatusManager(); - } - - @Override - protected String getPageTitle(HttpServletRequest req, HttpServletResponse resp) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - return "

Status messages for LoggerContext named [" - + lc.getName() + "]

\r\n"; - } + private static final long serialVersionUID = 443878494348593337L; + + @Override + protected StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + return lc.getStatusManager(); + } + + @Override + protected String getPageTitle(HttpServletRequest req, HttpServletResponse resp) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + return "

Status messages for LoggerContext named [" + lc.getName() + "]

\r\n"; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/GEventEvaluator.java b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/GEventEvaluator.java index c7061cf0fe164f9554d5e1273c809338b279ae96..a09e0e7eaf09fac4f0214acc2e62b95aa126fc35 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/GEventEvaluator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/GEventEvaluator.java @@ -25,66 +25,64 @@ import org.codehaus.groovy.control.CompilationFailedException; */ public class GEventEvaluator extends EventEvaluatorBase { - String expression; + String expression; - IEvaluator delegateEvaluator; - Script script; + IEvaluator delegateEvaluator; + Script script; - public String getExpression() { - return expression; - } - - public void setExpression(String expression) { - this.expression = expression; - } - - public void start() { - int errors = 0; - if (expression == null || expression.length() == 0) { - addError("Empty expression"); - return; - } else { - addInfo("Expression to evaluate [" + expression + "]"); + public String getExpression() { + return expression; } - - ClassLoader classLoader = getClass().getClassLoader(); - String currentPackageName = this.getClass().getPackage().getName(); - currentPackageName = currentPackageName.replace('.', '/'); - - FileUtil fileUtil = new FileUtil(getContext()); - String scriptText = fileUtil.resourceAsString(classLoader, currentPackageName + "/EvaluatorTemplate.groovy"); - if (scriptText == null) { - return; + public void setExpression(String expression) { + this.expression = expression; } - // insert the expression into script text - scriptText = scriptText.replace("//EXPRESSION", expression); - - GroovyClassLoader gLoader = new GroovyClassLoader(classLoader); - try { - Class scriptClass = gLoader.parseClass(scriptText); - - GroovyObject goo = (GroovyObject) scriptClass.newInstance(); - delegateEvaluator = (IEvaluator) goo; - - } catch (CompilationFailedException cfe) { - addError("Failed to compile expression [" + expression + "]", cfe); - errors++; - } catch (Exception e) { - addError("Failed to compile expression [" + expression + "]", e); - errors++; + public void start() { + int errors = 0; + if (expression == null || expression.length() == 0) { + addError("Empty expression"); + return; + } else { + addInfo("Expression to evaluate [" + expression + "]"); + } + + ClassLoader classLoader = getClass().getClassLoader(); + String currentPackageName = this.getClass().getPackage().getName(); + currentPackageName = currentPackageName.replace('.', '/'); + + FileUtil fileUtil = new FileUtil(getContext()); + String scriptText = fileUtil.resourceAsString(classLoader, currentPackageName + "/EvaluatorTemplate.groovy"); + if (scriptText == null) { + return; + } + + // insert the expression into script text + scriptText = scriptText.replace("//EXPRESSION", expression); + + GroovyClassLoader gLoader = new GroovyClassLoader(classLoader); + try { + Class scriptClass = gLoader.parseClass(scriptText); + + GroovyObject goo = (GroovyObject) scriptClass.newInstance(); + delegateEvaluator = (IEvaluator) goo; + + } catch (CompilationFailedException cfe) { + addError("Failed to compile expression [" + expression + "]", cfe); + errors++; + } catch (Exception e) { + addError("Failed to compile expression [" + expression + "]", e); + errors++; + } + if (errors == 0) + super.start(); } - if (errors == 0) - super.start(); - } - public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException { - if (delegateEvaluator == null) { - return false; + public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException { + if (delegateEvaluator == null) { + return false; + } + return delegateEvaluator.doEvaluate(event); } - return delegateEvaluator.doEvaluate(event); - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/IEvaluator.java b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/IEvaluator.java index 64c2bc37c2f5dbc2baf152118514d58efc5921bd..9f0f9f534cfaf5696795eff40ec1d2435d282c0e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/IEvaluator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/IEvaluator.java @@ -21,6 +21,5 @@ import ch.qos.logback.classic.spi.ILoggingEvent; * @author Ceki Gücü */ public interface IEvaluator { - boolean doEvaluate(ILoggingEvent event); + boolean doEvaluate(ILoggingEvent event); } - \ No newline at end of file diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/JaninoEventEvaluator.java b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/JaninoEventEvaluator.java index c039dfadecb522871f847a41f74bb20a49b87415..a23672120ac0a86bc21f60e47023ac90c5a0578e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/JaninoEventEvaluator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/JaninoEventEvaluator.java @@ -28,127 +28,125 @@ import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.boolex.JaninoEventEvaluatorBase; import ch.qos.logback.core.boolex.Matcher; -public class JaninoEventEvaluator extends - JaninoEventEvaluatorBase { - - public final static String IMPORT_LEVEL = "import ch.qos.logback.classic.Level;\r\n"; - - public final static List DEFAULT_PARAM_NAME_LIST = new ArrayList(); - public final static List DEFAULT_PARAM_TYPE_LIST = new ArrayList(); - - static { - DEFAULT_PARAM_NAME_LIST.add("DEBUG"); - DEFAULT_PARAM_NAME_LIST.add("INFO"); - DEFAULT_PARAM_NAME_LIST.add("WARN"); - DEFAULT_PARAM_NAME_LIST.add("ERROR"); - - DEFAULT_PARAM_NAME_LIST.add("event"); - DEFAULT_PARAM_NAME_LIST.add("message"); - - DEFAULT_PARAM_NAME_LIST.add("formattedMessage"); - DEFAULT_PARAM_NAME_LIST.add("logger"); - DEFAULT_PARAM_NAME_LIST.add("loggerContext"); - DEFAULT_PARAM_NAME_LIST.add("level"); - DEFAULT_PARAM_NAME_LIST.add("timeStamp"); - DEFAULT_PARAM_NAME_LIST.add("marker"); - DEFAULT_PARAM_NAME_LIST.add("mdc"); - DEFAULT_PARAM_NAME_LIST.add("throwableProxy"); - DEFAULT_PARAM_NAME_LIST.add("throwable"); - - DEFAULT_PARAM_TYPE_LIST.add(int.class); - DEFAULT_PARAM_TYPE_LIST.add(int.class); - DEFAULT_PARAM_TYPE_LIST.add(int.class); - DEFAULT_PARAM_TYPE_LIST.add(int.class); - - DEFAULT_PARAM_TYPE_LIST.add(ILoggingEvent.class); - DEFAULT_PARAM_TYPE_LIST.add(String.class); - DEFAULT_PARAM_TYPE_LIST.add(String.class); - DEFAULT_PARAM_TYPE_LIST.add(String.class); - DEFAULT_PARAM_TYPE_LIST.add(LoggerContextVO.class); - DEFAULT_PARAM_TYPE_LIST.add(int.class); - DEFAULT_PARAM_TYPE_LIST.add(long.class); - DEFAULT_PARAM_TYPE_LIST.add(Marker.class); - DEFAULT_PARAM_TYPE_LIST.add(Map.class); - DEFAULT_PARAM_TYPE_LIST.add(IThrowableProxy.class); - DEFAULT_PARAM_TYPE_LIST.add(Throwable.class); - } - - protected String getDecoratedExpression() { - String expression = getExpression(); - if(!expression.contains("return")) { - expression = "return "+expression +";"; - addInfo("Adding [return] prefix and a semicolon suffix. Expression becomes ["+expression+"]"); - addInfo("See also "+CoreConstants.CODES_URL+"#block"); - +public class JaninoEventEvaluator extends JaninoEventEvaluatorBase { + + public final static String IMPORT_LEVEL = "import ch.qos.logback.classic.Level;\r\n"; + + public final static List DEFAULT_PARAM_NAME_LIST = new ArrayList(); + public final static List DEFAULT_PARAM_TYPE_LIST = new ArrayList(); + + static { + DEFAULT_PARAM_NAME_LIST.add("DEBUG"); + DEFAULT_PARAM_NAME_LIST.add("INFO"); + DEFAULT_PARAM_NAME_LIST.add("WARN"); + DEFAULT_PARAM_NAME_LIST.add("ERROR"); + + DEFAULT_PARAM_NAME_LIST.add("event"); + DEFAULT_PARAM_NAME_LIST.add("message"); + + DEFAULT_PARAM_NAME_LIST.add("formattedMessage"); + DEFAULT_PARAM_NAME_LIST.add("logger"); + DEFAULT_PARAM_NAME_LIST.add("loggerContext"); + DEFAULT_PARAM_NAME_LIST.add("level"); + DEFAULT_PARAM_NAME_LIST.add("timeStamp"); + DEFAULT_PARAM_NAME_LIST.add("marker"); + DEFAULT_PARAM_NAME_LIST.add("mdc"); + DEFAULT_PARAM_NAME_LIST.add("throwableProxy"); + DEFAULT_PARAM_NAME_LIST.add("throwable"); + + DEFAULT_PARAM_TYPE_LIST.add(int.class); + DEFAULT_PARAM_TYPE_LIST.add(int.class); + DEFAULT_PARAM_TYPE_LIST.add(int.class); + DEFAULT_PARAM_TYPE_LIST.add(int.class); + + DEFAULT_PARAM_TYPE_LIST.add(ILoggingEvent.class); + DEFAULT_PARAM_TYPE_LIST.add(String.class); + DEFAULT_PARAM_TYPE_LIST.add(String.class); + DEFAULT_PARAM_TYPE_LIST.add(String.class); + DEFAULT_PARAM_TYPE_LIST.add(LoggerContextVO.class); + DEFAULT_PARAM_TYPE_LIST.add(int.class); + DEFAULT_PARAM_TYPE_LIST.add(long.class); + DEFAULT_PARAM_TYPE_LIST.add(Marker.class); + DEFAULT_PARAM_TYPE_LIST.add(Map.class); + DEFAULT_PARAM_TYPE_LIST.add(IThrowableProxy.class); + DEFAULT_PARAM_TYPE_LIST.add(Throwable.class); } - return IMPORT_LEVEL + expression; - } - protected String[] getParameterNames() { - List fullNameList = new ArrayList(); - fullNameList.addAll(DEFAULT_PARAM_NAME_LIST); + protected String getDecoratedExpression() { + String expression = getExpression(); + if (!expression.contains("return")) { + expression = "return " + expression + ";"; + addInfo("Adding [return] prefix and a semicolon suffix. Expression becomes [" + expression + "]"); + addInfo("See also " + CoreConstants.CODES_URL + "#block"); - for (int i = 0; i < matcherList.size(); i++) { - Matcher m = (Matcher) matcherList.get(i); - fullNameList.add(m.getName()); + } + return IMPORT_LEVEL + expression; } - return (String[]) fullNameList.toArray(CoreConstants.EMPTY_STRING_ARRAY); - } + protected String[] getParameterNames() { + List fullNameList = new ArrayList(); + fullNameList.addAll(DEFAULT_PARAM_NAME_LIST); - protected Class[] getParameterTypes() { - List fullTypeList = new ArrayList(); - fullTypeList.addAll(DEFAULT_PARAM_TYPE_LIST); - for (int i = 0; i < matcherList.size(); i++) { - fullTypeList.add(Matcher.class); - } - return (Class[]) fullTypeList.toArray(CoreConstants.EMPTY_CLASS_ARRAY); - } - - protected Object[] getParameterValues(ILoggingEvent loggingEvent) { - final int matcherListSize = matcherList.size(); - - int i = 0; - Object[] values = new Object[DEFAULT_PARAM_NAME_LIST.size() - + matcherListSize]; - - values[i++] = Level.DEBUG_INTEGER; - values[i++] = Level.INFO_INTEGER; - values[i++] = Level.WARN_INTEGER; - values[i++] = Level.ERROR_INTEGER; - - values[i++] = loggingEvent; - values[i++] = loggingEvent.getMessage(); - values[i++] = loggingEvent.getFormattedMessage(); - values[i++] = loggingEvent.getLoggerName(); - values[i++] = loggingEvent.getLoggerContextVO(); - values[i++] = loggingEvent.getLevel().toInteger(); - values[i++] = loggingEvent.getTimeStamp(); - // In order to avoid NullPointerException, we could push a dummy marker if - // the event's marker is null. However, this would surprise user who - // expect to see a null marker instead of a dummy one. - values[i++] = loggingEvent.getMarker(); - values[i++] = loggingEvent.getMDCPropertyMap(); - - IThrowableProxy iThrowableProxy = loggingEvent.getThrowableProxy(); - - if (iThrowableProxy != null) { - values[i++] = iThrowableProxy; - if (iThrowableProxy instanceof ThrowableProxy) { - values[i++] = ((ThrowableProxy) iThrowableProxy).getThrowable(); - } else { - values[i++] = null; - } - } else { - values[i++] = null; - values[i++] = null; + for (int i = 0; i < matcherList.size(); i++) { + Matcher m = (Matcher) matcherList.get(i); + fullNameList.add(m.getName()); + } + + return (String[]) fullNameList.toArray(CoreConstants.EMPTY_STRING_ARRAY); } - for (int j = 0; j < matcherListSize; j++) { - values[i++] = (Matcher) matcherList.get(j); + protected Class[] getParameterTypes() { + List fullTypeList = new ArrayList(); + fullTypeList.addAll(DEFAULT_PARAM_TYPE_LIST); + for (int i = 0; i < matcherList.size(); i++) { + fullTypeList.add(Matcher.class); + } + return (Class[]) fullTypeList.toArray(CoreConstants.EMPTY_CLASS_ARRAY); } - return values; - } + protected Object[] getParameterValues(ILoggingEvent loggingEvent) { + final int matcherListSize = matcherList.size(); + + int i = 0; + Object[] values = new Object[DEFAULT_PARAM_NAME_LIST.size() + matcherListSize]; + + values[i++] = Level.DEBUG_INTEGER; + values[i++] = Level.INFO_INTEGER; + values[i++] = Level.WARN_INTEGER; + values[i++] = Level.ERROR_INTEGER; + + values[i++] = loggingEvent; + values[i++] = loggingEvent.getMessage(); + values[i++] = loggingEvent.getFormattedMessage(); + values[i++] = loggingEvent.getLoggerName(); + values[i++] = loggingEvent.getLoggerContextVO(); + values[i++] = loggingEvent.getLevel().toInteger(); + values[i++] = loggingEvent.getTimeStamp(); + // In order to avoid NullPointerException, we could push a dummy marker if + // the event's marker is null. However, this would surprise user who + // expect to see a null marker instead of a dummy one. + values[i++] = loggingEvent.getMarker(); + values[i++] = loggingEvent.getMDCPropertyMap(); + + IThrowableProxy iThrowableProxy = loggingEvent.getThrowableProxy(); + + if (iThrowableProxy != null) { + values[i++] = iThrowableProxy; + if (iThrowableProxy instanceof ThrowableProxy) { + values[i++] = ((ThrowableProxy) iThrowableProxy).getThrowable(); + } else { + values[i++] = null; + } + } else { + values[i++] = null; + values[i++] = null; + } + + for (int j = 0; j < matcherListSize; j++) { + values[i++] = (Matcher) matcherList.get(j); + } + + return values; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnErrorEvaluator.java b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnErrorEvaluator.java index ae49cb694c140645fd91ef25d24f792ca5b7e1e1..e25917a2dbb2daa92a0c31dd57bb4fd07630337d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnErrorEvaluator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnErrorEvaluator.java @@ -27,12 +27,11 @@ import ch.qos.logback.core.boolex.EventEvaluatorBase; */ public class OnErrorEvaluator extends EventEvaluatorBase { - /** - * Return true if event passed as parameter has level ERROR or higher, returns - * false otherwise. - */ - public boolean evaluate(ILoggingEvent event) throws NullPointerException, - EvaluationException { - return event.getLevel().levelInt >= Level.ERROR_INT; - } + /** + * Return true if event passed as parameter has level ERROR or higher, returns + * false otherwise. + */ + public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException { + return event.getLevel().levelInt >= Level.ERROR_INT; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnMarkerEvaluator.java b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnMarkerEvaluator.java index 6f7589a5db58d2b2114c848cde9d3d874a3ff398..bca84143e44c5ca8b1de3d1f601b7b96d0fc7b0a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnMarkerEvaluator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/boolex/OnMarkerEvaluator.java @@ -30,29 +30,28 @@ import ch.qos.logback.core.boolex.EventEvaluatorBase; */ public class OnMarkerEvaluator extends EventEvaluatorBase { - List markerList = new ArrayList(); - - public void addMarker(String markerStr) { - markerList.add(markerStr); - } - - /** - * Return true if event passed as parameter contains one of the specified - * user-markers. - */ - public boolean evaluate(ILoggingEvent event) throws NullPointerException, - EvaluationException { - - Marker eventsMarker = event.getMarker(); - if (eventsMarker == null) { - return false; + List markerList = new ArrayList(); + + public void addMarker(String markerStr) { + markerList.add(markerStr); } - for (String markerStr : markerList) { - if (eventsMarker.contains(markerStr)) { - return true; - } + /** + * Return true if event passed as parameter contains one of the specified + * user-markers. + */ + public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException { + + Marker eventsMarker = event.getMarker(); + if (eventsMarker == null) { + return false; + } + + for (String markerStr : markerList) { + if (eventsMarker.contains(markerStr)) { + return true; + } + } + return false; } - return false; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/DBAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/DBAppender.java index 676414555945e8090ef23b5c960e5888ab0c1a70..defd2b98c34a95671d2d6a06aa7c9e52ac617069 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/DBAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/DBAppender.java @@ -41,273 +41,255 @@ import ch.qos.logback.core.db.DBAppenderBase; * @author Sébastien Pennec */ public class DBAppender extends DBAppenderBase { - protected String insertPropertiesSQL; - protected String insertExceptionSQL; - protected String insertSQL; - protected static final Method GET_GENERATED_KEYS_METHOD; - - private DBNameResolver dbNameResolver; - - static final int TIMESTMP_INDEX = 1; - static final int FORMATTED_MESSAGE_INDEX = 2; - static final int LOGGER_NAME_INDEX = 3; - static final int LEVEL_STRING_INDEX = 4; - static final int THREAD_NAME_INDEX = 5; - static final int REFERENCE_FLAG_INDEX = 6; - static final int ARG0_INDEX = 7; - static final int ARG1_INDEX = 8; - static final int ARG2_INDEX = 9; - static final int ARG3_INDEX = 10; - static final int CALLER_FILENAME_INDEX = 11; - static final int CALLER_CLASS_INDEX = 12; - static final int CALLER_METHOD_INDEX = 13; - static final int CALLER_LINE_INDEX = 14; - static final int EVENT_ID_INDEX = 15; - - static final StackTraceElement EMPTY_CALLER_DATA = CallerData.naInstance(); - - static { - // PreparedStatement.getGeneratedKeys() method was added in JDK 1.4 - Method getGeneratedKeysMethod; - try { - // the - getGeneratedKeysMethod = PreparedStatement.class.getMethod( - "getGeneratedKeys", (Class[]) null); - } catch (Exception ex) { - getGeneratedKeysMethod = null; - } - GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; - } - - public void setDbNameResolver(DBNameResolver dbNameResolver) { - this.dbNameResolver = dbNameResolver; - } - - @Override - public void start() { - if (dbNameResolver == null) - dbNameResolver = new DefaultDBNameResolver(); - insertExceptionSQL = SQLBuilder.buildInsertExceptionSQL(dbNameResolver); - insertPropertiesSQL = SQLBuilder.buildInsertPropertiesSQL(dbNameResolver); - insertSQL = SQLBuilder.buildInsertSQL(dbNameResolver); - super.start(); - } - - @Override - protected void subAppend(ILoggingEvent event, Connection connection, - PreparedStatement insertStatement) throws Throwable { - - bindLoggingEventWithInsertStatement(insertStatement, event); - bindLoggingEventArgumentsWithPreparedStatement(insertStatement, event.getArgumentArray()); - - // This is expensive... should we do it every time? - bindCallerDataWithPreparedStatement(insertStatement, event.getCallerData()); - - int updateCount = insertStatement.executeUpdate(); - if (updateCount != 1) { - addWarn("Failed to insert loggingEvent"); + protected String insertPropertiesSQL; + protected String insertExceptionSQL; + protected String insertSQL; + protected static final Method GET_GENERATED_KEYS_METHOD; + + private DBNameResolver dbNameResolver; + + static final int TIMESTMP_INDEX = 1; + static final int FORMATTED_MESSAGE_INDEX = 2; + static final int LOGGER_NAME_INDEX = 3; + static final int LEVEL_STRING_INDEX = 4; + static final int THREAD_NAME_INDEX = 5; + static final int REFERENCE_FLAG_INDEX = 6; + static final int ARG0_INDEX = 7; + static final int ARG1_INDEX = 8; + static final int ARG2_INDEX = 9; + static final int ARG3_INDEX = 10; + static final int CALLER_FILENAME_INDEX = 11; + static final int CALLER_CLASS_INDEX = 12; + static final int CALLER_METHOD_INDEX = 13; + static final int CALLER_LINE_INDEX = 14; + static final int EVENT_ID_INDEX = 15; + + static final StackTraceElement EMPTY_CALLER_DATA = CallerData.naInstance(); + + static { + // PreparedStatement.getGeneratedKeys() method was added in JDK 1.4 + Method getGeneratedKeysMethod; + try { + // the + getGeneratedKeysMethod = PreparedStatement.class.getMethod("getGeneratedKeys", (Class[]) null); + } catch (Exception ex) { + getGeneratedKeysMethod = null; + } + GET_GENERATED_KEYS_METHOD = getGeneratedKeysMethod; } - } - protected void secondarySubAppend(ILoggingEvent event, Connection connection, - long eventId) throws Throwable { - Map mergedMap = mergePropertyMaps(event); - insertProperties(mergedMap, connection, eventId); + public void setDbNameResolver(DBNameResolver dbNameResolver) { + this.dbNameResolver = dbNameResolver; + } - if (event.getThrowableProxy() != null) { - insertThrowable(event.getThrowableProxy(), connection, eventId); + @Override + public void start() { + if (dbNameResolver == null) + dbNameResolver = new DefaultDBNameResolver(); + insertExceptionSQL = SQLBuilder.buildInsertExceptionSQL(dbNameResolver); + insertPropertiesSQL = SQLBuilder.buildInsertPropertiesSQL(dbNameResolver); + insertSQL = SQLBuilder.buildInsertSQL(dbNameResolver); + super.start(); } - } - void bindLoggingEventWithInsertStatement(PreparedStatement stmt, - ILoggingEvent event) throws SQLException { - stmt.setLong(TIMESTMP_INDEX, event.getTimeStamp()); - stmt.setString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage()); - stmt.setString(LOGGER_NAME_INDEX, event.getLoggerName()); - stmt.setString(LEVEL_STRING_INDEX, event.getLevel().toString()); - stmt.setString(THREAD_NAME_INDEX, event.getThreadName()); - stmt.setShort(REFERENCE_FLAG_INDEX, DBHelper.computeReferenceMask(event)); - } + @Override + protected void subAppend(ILoggingEvent event, Connection connection, PreparedStatement insertStatement) throws Throwable { - void bindLoggingEventArgumentsWithPreparedStatement(PreparedStatement stmt, - Object[] argArray) throws SQLException { + bindLoggingEventWithInsertStatement(insertStatement, event); + bindLoggingEventArgumentsWithPreparedStatement(insertStatement, event.getArgumentArray()); - int arrayLen = argArray != null ? argArray.length : 0; + // This is expensive... should we do it every time? + bindCallerDataWithPreparedStatement(insertStatement, event.getCallerData()); - for(int i = 0; i < arrayLen && i < 4; i++) { - stmt.setString(ARG0_INDEX+i, asStringTruncatedTo254(argArray[i])); + int updateCount = insertStatement.executeUpdate(); + if (updateCount != 1) { + addWarn("Failed to insert loggingEvent"); + } } - if(arrayLen < 4) { - for(int i = arrayLen; i < 4; i++) { - stmt.setString(ARG0_INDEX+i, null); - } + + protected void secondarySubAppend(ILoggingEvent event, Connection connection, long eventId) throws Throwable { + Map mergedMap = mergePropertyMaps(event); + insertProperties(mergedMap, connection, eventId); + + if (event.getThrowableProxy() != null) { + insertThrowable(event.getThrowableProxy(), connection, eventId); + } + } + + void bindLoggingEventWithInsertStatement(PreparedStatement stmt, ILoggingEvent event) throws SQLException { + stmt.setLong(TIMESTMP_INDEX, event.getTimeStamp()); + stmt.setString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage()); + stmt.setString(LOGGER_NAME_INDEX, event.getLoggerName()); + stmt.setString(LEVEL_STRING_INDEX, event.getLevel().toString()); + stmt.setString(THREAD_NAME_INDEX, event.getThreadName()); + stmt.setShort(REFERENCE_FLAG_INDEX, DBHelper.computeReferenceMask(event)); } - } - String asStringTruncatedTo254(Object o) { - String s = null; - if(o != null) { - s= o.toString(); - } + void bindLoggingEventArgumentsWithPreparedStatement(PreparedStatement stmt, Object[] argArray) throws SQLException { - if(s == null) { - return null; + int arrayLen = argArray != null ? argArray.length : 0; + + for (int i = 0; i < arrayLen && i < 4; i++) { + stmt.setString(ARG0_INDEX + i, asStringTruncatedTo254(argArray[i])); + } + if (arrayLen < 4) { + for (int i = arrayLen; i < 4; i++) { + stmt.setString(ARG0_INDEX + i, null); + } + } } - if(s.length() <= 254) { - return s; - } else { - return s.substring(0, 254); + + String asStringTruncatedTo254(Object o) { + String s = null; + if (o != null) { + s = o.toString(); + } + + if (s == null) { + return null; + } + if (s.length() <= 254) { + return s; + } else { + return s.substring(0, 254); + } } - } - - void bindCallerDataWithPreparedStatement(PreparedStatement stmt, - StackTraceElement[] callerDataArray) throws SQLException { - - StackTraceElement caller = extractFirstCaller(callerDataArray); - - stmt.setString(CALLER_FILENAME_INDEX, caller.getFileName()); - stmt.setString(CALLER_CLASS_INDEX, caller.getClassName()); - stmt.setString(CALLER_METHOD_INDEX, caller.getMethodName()); - stmt.setString(CALLER_LINE_INDEX, Integer.toString(caller.getLineNumber())); - } - - private StackTraceElement extractFirstCaller(StackTraceElement[] callerDataArray) { - StackTraceElement caller = EMPTY_CALLER_DATA; - if(hasAtLeastOneNonNullElement(callerDataArray)) - caller = callerDataArray[0]; - return caller; - } - - private boolean hasAtLeastOneNonNullElement(StackTraceElement[] callerDataArray) { - return callerDataArray != null && callerDataArray.length > 0 && callerDataArray[0] != null; - } - - Map mergePropertyMaps(ILoggingEvent event) { - Map mergedMap = new HashMap(); - // we add the context properties first, then the event properties, since - // we consider that event-specific properties should have priority over - // context-wide properties. - Map loggerContextMap = event.getLoggerContextVO() - .getPropertyMap(); - Map mdcMap = event.getMDCPropertyMap(); - if (loggerContextMap != null) { - mergedMap.putAll(loggerContextMap); + + void bindCallerDataWithPreparedStatement(PreparedStatement stmt, StackTraceElement[] callerDataArray) throws SQLException { + + StackTraceElement caller = extractFirstCaller(callerDataArray); + + stmt.setString(CALLER_FILENAME_INDEX, caller.getFileName()); + stmt.setString(CALLER_CLASS_INDEX, caller.getClassName()); + stmt.setString(CALLER_METHOD_INDEX, caller.getMethodName()); + stmt.setString(CALLER_LINE_INDEX, Integer.toString(caller.getLineNumber())); } - if (mdcMap != null) { - mergedMap.putAll(mdcMap); + + private StackTraceElement extractFirstCaller(StackTraceElement[] callerDataArray) { + StackTraceElement caller = EMPTY_CALLER_DATA; + if (hasAtLeastOneNonNullElement(callerDataArray)) + caller = callerDataArray[0]; + return caller; } - return mergedMap; - } - - @Override - protected Method getGeneratedKeysMethod() { - return GET_GENERATED_KEYS_METHOD; - } - - @Override - protected String getInsertSQL() { - return insertSQL; - } - - protected void insertProperties(Map mergedMap, - Connection connection, long eventId) throws SQLException { - Set propertiesKeys = mergedMap.keySet(); - if (propertiesKeys.size() > 0) { - PreparedStatement insertPropertiesStatement = null; - try { - insertPropertiesStatement = connection - .prepareStatement(insertPropertiesSQL); - - for (String key : propertiesKeys) { - String value = mergedMap.get(key); - - insertPropertiesStatement.setLong(1, eventId); - insertPropertiesStatement.setString(2, key); - insertPropertiesStatement.setString(3, value); - - if (cnxSupportsBatchUpdates) { - insertPropertiesStatement.addBatch(); - } else { - insertPropertiesStatement.execute(); - } - } + private boolean hasAtLeastOneNonNullElement(StackTraceElement[] callerDataArray) { + return callerDataArray != null && callerDataArray.length > 0 && callerDataArray[0] != null; + } - if (cnxSupportsBatchUpdates) { - insertPropertiesStatement.executeBatch(); + Map mergePropertyMaps(ILoggingEvent event) { + Map mergedMap = new HashMap(); + // we add the context properties first, then the event properties, since + // we consider that event-specific properties should have priority over + // context-wide properties. + Map loggerContextMap = event.getLoggerContextVO().getPropertyMap(); + Map mdcMap = event.getMDCPropertyMap(); + if (loggerContextMap != null) { + mergedMap.putAll(loggerContextMap); } - } finally { - closeStatement(insertPropertiesStatement); - } + if (mdcMap != null) { + mergedMap.putAll(mdcMap); + } + + return mergedMap; } - } - - /** - * Add an exception statement either as a batch or execute immediately if - * batch updates are not supported. - */ - void updateExceptionStatement(PreparedStatement exceptionStatement, - String txt, short i, long eventId) throws SQLException { - exceptionStatement.setLong(1, eventId); - exceptionStatement.setShort(2, i); - exceptionStatement.setString(3, txt); - if (cnxSupportsBatchUpdates) { - exceptionStatement.addBatch(); - } else { - exceptionStatement.execute(); + + @Override + protected Method getGeneratedKeysMethod() { + return GET_GENERATED_KEYS_METHOD; + } + + @Override + protected String getInsertSQL() { + return insertSQL; } - } - - short buildExceptionStatement(IThrowableProxy tp, short baseIndex, - PreparedStatement insertExceptionStatement, long eventId) - throws SQLException { - - StringBuilder buf = new StringBuilder(); - ThrowableProxyUtil.subjoinFirstLine(buf, tp); - updateExceptionStatement(insertExceptionStatement, buf.toString(), - baseIndex++, eventId); - - int commonFrames = tp.getCommonFrames(); - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - for (int i = 0; i < stepArray.length - commonFrames; i++) { - StringBuilder sb = new StringBuilder(); - sb.append(CoreConstants.TAB); - ThrowableProxyUtil.subjoinSTEP(sb, stepArray[i]); - updateExceptionStatement(insertExceptionStatement, sb.toString(), - baseIndex++, eventId); + + protected void insertProperties(Map mergedMap, Connection connection, long eventId) throws SQLException { + Set propertiesKeys = mergedMap.keySet(); + if (propertiesKeys.size() > 0) { + PreparedStatement insertPropertiesStatement = null; + try { + insertPropertiesStatement = connection.prepareStatement(insertPropertiesSQL); + + for (String key : propertiesKeys) { + String value = mergedMap.get(key); + + insertPropertiesStatement.setLong(1, eventId); + insertPropertiesStatement.setString(2, key); + insertPropertiesStatement.setString(3, value); + + if (cnxSupportsBatchUpdates) { + insertPropertiesStatement.addBatch(); + } else { + insertPropertiesStatement.execute(); + } + } + + if (cnxSupportsBatchUpdates) { + insertPropertiesStatement.executeBatch(); + } + } finally { + closeStatement(insertPropertiesStatement); + } + } } - if (commonFrames > 0) { - StringBuilder sb = new StringBuilder(); - sb.append(CoreConstants.TAB).append("... ").append(commonFrames).append( - " common frames omitted"); - updateExceptionStatement(insertExceptionStatement, sb.toString(), - baseIndex++, eventId); + /** + * Add an exception statement either as a batch or execute immediately if + * batch updates are not supported. + */ + void updateExceptionStatement(PreparedStatement exceptionStatement, String txt, short i, long eventId) throws SQLException { + exceptionStatement.setLong(1, eventId); + exceptionStatement.setShort(2, i); + exceptionStatement.setString(3, txt); + if (cnxSupportsBatchUpdates) { + exceptionStatement.addBatch(); + } else { + exceptionStatement.execute(); + } } - return baseIndex; - } + short buildExceptionStatement(IThrowableProxy tp, short baseIndex, PreparedStatement insertExceptionStatement, long eventId) throws SQLException { - protected void insertThrowable(IThrowableProxy tp, Connection connection, - long eventId) throws SQLException { + StringBuilder buf = new StringBuilder(); + ThrowableProxyUtil.subjoinFirstLine(buf, tp); + updateExceptionStatement(insertExceptionStatement, buf.toString(), baseIndex++, eventId); - PreparedStatement exceptionStatement = null; - try { - exceptionStatement = connection.prepareStatement(insertExceptionSQL); + int commonFrames = tp.getCommonFrames(); + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + for (int i = 0; i < stepArray.length - commonFrames; i++) { + StringBuilder sb = new StringBuilder(); + sb.append(CoreConstants.TAB); + ThrowableProxyUtil.subjoinSTEP(sb, stepArray[i]); + updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex++, eventId); + } - short baseIndex = 0; - while (tp != null) { - baseIndex = buildExceptionStatement(tp, baseIndex, exceptionStatement, - eventId); - tp = tp.getCause(); - } + if (commonFrames > 0) { + StringBuilder sb = new StringBuilder(); + sb.append(CoreConstants.TAB).append("... ").append(commonFrames).append(" common frames omitted"); + updateExceptionStatement(insertExceptionStatement, sb.toString(), baseIndex++, eventId); + } - if (cnxSupportsBatchUpdates) { - exceptionStatement.executeBatch(); - } - } finally { - closeStatement(exceptionStatement); + return baseIndex; } - } + protected void insertThrowable(IThrowableProxy tp, Connection connection, long eventId) throws SQLException { + + PreparedStatement exceptionStatement = null; + try { + exceptionStatement = connection.prepareStatement(insertExceptionSQL); + + short baseIndex = 0; + while (tp != null) { + baseIndex = buildExceptionStatement(tp, baseIndex, exceptionStatement, eventId); + tp = tp.getCause(); + } + + if (cnxSupportsBatchUpdates) { + exceptionStatement.executeBatch(); + } + } finally { + closeStatement(exceptionStatement); + } + + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/DBHelper.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/DBHelper.java index 6bc1fb051942296013bc3a2ab31ba77a3a5b84c7..852a44a2a03c757e7cfda1d5957958e88ba66c41 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/DBHelper.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/DBHelper.java @@ -21,27 +21,27 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class DBHelper { - public static final short PROPERTIES_EXIST = 0x01; - public static final short EXCEPTION_EXISTS = 0x02; + public static final short PROPERTIES_EXIST = 0x01; + public static final short EXCEPTION_EXISTS = 0x02; - public static short computeReferenceMask(ILoggingEvent event) { - short mask = 0; + public static short computeReferenceMask(ILoggingEvent event) { + short mask = 0; - int mdcPropSize = 0; - if (event.getMDCPropertyMap() != null) { - mdcPropSize = event.getMDCPropertyMap().keySet().size(); - } - int contextPropSize = 0; - if (event.getLoggerContextVO().getPropertyMap() != null) { - contextPropSize = event.getLoggerContextVO().getPropertyMap().size(); - } + int mdcPropSize = 0; + if (event.getMDCPropertyMap() != null) { + mdcPropSize = event.getMDCPropertyMap().keySet().size(); + } + int contextPropSize = 0; + if (event.getLoggerContextVO().getPropertyMap() != null) { + contextPropSize = event.getLoggerContextVO().getPropertyMap().size(); + } - if (mdcPropSize > 0 || contextPropSize > 0) { - mask = PROPERTIES_EXIST; - } - if (event.getThrowableProxy() != null) { - mask |= EXCEPTION_EXISTS; + if (mdcPropSize > 0 || contextPropSize > 0) { + mask = PROPERTIES_EXIST; + } + if (event.getThrowableProxy() != null) { + mask |= EXCEPTION_EXISTS; + } + return mask; } - return mask; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/SQLBuilder.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/SQLBuilder.java index 201d47afac74c176c4c26a905175a9d7acf3cdab..7c950784f286882ef482c8e83293d673532c437a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/SQLBuilder.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/SQLBuilder.java @@ -21,44 +21,44 @@ import ch.qos.logback.classic.db.names.*; */ public class SQLBuilder { - static String buildInsertPropertiesSQL(DBNameResolver dbNameResolver) { - StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); - sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_PROPERTY)).append(" ("); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_KEY)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_VALUE)).append(") "); - sqlBuilder.append("VALUES (?, ?, ?)"); - return sqlBuilder.toString(); - } + static String buildInsertPropertiesSQL(DBNameResolver dbNameResolver) { + StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); + sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_PROPERTY)).append(" ("); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_KEY)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.MAPPED_VALUE)).append(") "); + sqlBuilder.append("VALUES (?, ?, ?)"); + return sqlBuilder.toString(); + } - static String buildInsertExceptionSQL(DBNameResolver dbNameResolver) { - StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); - sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_EXCEPTION)).append(" ("); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.I)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TRACE_LINE)).append(") "); - sqlBuilder.append("VALUES (?, ?, ?)"); - return sqlBuilder.toString(); - } + static String buildInsertExceptionSQL(DBNameResolver dbNameResolver) { + StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); + sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT_EXCEPTION)).append(" ("); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.EVENT_ID)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.I)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TRACE_LINE)).append(") "); + sqlBuilder.append("VALUES (?, ?, ?)"); + return sqlBuilder.toString(); + } - static String buildInsertSQL(DBNameResolver dbNameResolver) { - StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); - sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT)).append(" ("); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TIMESTMP)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.FORMATTED_MESSAGE)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LOGGER_NAME)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LEVEL_STRING)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.THREAD_NAME)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.REFERENCE_FLAG)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG0)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG1)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG2)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG3)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_FILENAME)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_CLASS)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_METHOD)).append(", "); - sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_LINE)).append(") "); - sqlBuilder.append("VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); - return sqlBuilder.toString(); - } + static String buildInsertSQL(DBNameResolver dbNameResolver) { + StringBuilder sqlBuilder = new StringBuilder("INSERT INTO "); + sqlBuilder.append(dbNameResolver.getTableName(TableName.LOGGING_EVENT)).append(" ("); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.TIMESTMP)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.FORMATTED_MESSAGE)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LOGGER_NAME)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.LEVEL_STRING)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.THREAD_NAME)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.REFERENCE_FLAG)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG0)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG1)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG2)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.ARG3)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_FILENAME)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_CLASS)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_METHOD)).append(", "); + sqlBuilder.append(dbNameResolver.getColumnName(ColumnName.CALLER_LINE)).append(") "); + sqlBuilder.append("VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + return sqlBuilder.toString(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/ColumnName.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/ColumnName.java index 9c88f8f443d3eca1356d2296396c7d37d81e5dfb..2ab9f419ad4aaabb5c30e4856650aaf886b35a13 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/ColumnName.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/ColumnName.java @@ -15,27 +15,12 @@ package ch.qos.logback.classic.db.names; public enum ColumnName { - EVENT_ID, - - TIMESTMP, - FORMATTED_MESSAGE, - LOGGER_NAME, - LEVEL_STRING, - THREAD_NAME, - REFERENCE_FLAG, - ARG0, - ARG1, - ARG2, - ARG3, - CALLER_FILENAME, - CALLER_CLASS, - CALLER_METHOD, - CALLER_LINE, - - // MDC - MAPPED_KEY, - MAPPED_VALUE, + EVENT_ID, - I, - TRACE_LINE; + TIMESTMP, FORMATTED_MESSAGE, LOGGER_NAME, LEVEL_STRING, THREAD_NAME, REFERENCE_FLAG, ARG0, ARG1, ARG2, ARG3, CALLER_FILENAME, CALLER_CLASS, CALLER_METHOD, CALLER_LINE, + + // MDC + MAPPED_KEY, MAPPED_VALUE, + + I, TRACE_LINE; } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DBNameResolver.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DBNameResolver.java index 496e9d4224e37ea8e90c3de1ca7bee0c021bc78f..af4e75d244c94b0f0ff15c11f49b73fd3e77a7d7 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DBNameResolver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DBNameResolver.java @@ -26,7 +26,7 @@ package ch.qos.logback.classic.db.names; */ public interface DBNameResolver { - > String getTableName(N tableName); + > String getTableName(N tableName); - > String getColumnName(N columnName); + > String getColumnName(N columnName); } \ No newline at end of file diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DefaultDBNameResolver.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DefaultDBNameResolver.java index 565d2a5ae8e6875053f777002661b4381113a63c..d604a4461ac54bad176410b08b26c4d6b7c47b96 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DefaultDBNameResolver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/DefaultDBNameResolver.java @@ -23,12 +23,12 @@ package ch.qos.logback.classic.db.names; */ public class DefaultDBNameResolver implements DBNameResolver { - public > String getTableName(N tableName) { - return tableName.toString().toLowerCase(); - } + public > String getTableName(N tableName) { + return tableName.toString().toLowerCase(); + } - public > String getColumnName(N columnName) { - return columnName.toString().toLowerCase(); - } + public > String getColumnName(N columnName) { + return columnName.toString().toLowerCase(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/SimpleDBNameResolver.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/SimpleDBNameResolver.java index e291a9abfb9c24cf89e15f50f7aed7a6588a2056..5bb9609c1e97e511a773311ee970a05028079fcf 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/SimpleDBNameResolver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/SimpleDBNameResolver.java @@ -21,35 +21,35 @@ package ch.qos.logback.classic.db.names; */ public class SimpleDBNameResolver implements DBNameResolver { - private String tableNamePrefix = ""; + private String tableNamePrefix = ""; - private String tableNameSuffix = ""; + private String tableNameSuffix = ""; - private String columnNamePrefix = ""; + private String columnNamePrefix = ""; - private String columnNameSuffix = ""; + private String columnNameSuffix = ""; - public > String getTableName(N tableName) { - return tableNamePrefix + tableName.name().toLowerCase() + tableNameSuffix; - } + public > String getTableName(N tableName) { + return tableNamePrefix + tableName.name().toLowerCase() + tableNameSuffix; + } - public > String getColumnName(N columnName) { - return columnNamePrefix + columnName.name().toLowerCase() + columnNameSuffix; - } + public > String getColumnName(N columnName) { + return columnNamePrefix + columnName.name().toLowerCase() + columnNameSuffix; + } - public void setTableNamePrefix(String tableNamePrefix) { - this.tableNamePrefix = tableNamePrefix != null? tableNamePrefix : ""; - } + public void setTableNamePrefix(String tableNamePrefix) { + this.tableNamePrefix = tableNamePrefix != null ? tableNamePrefix : ""; + } - public void setTableNameSuffix(String tableNameSuffix) { - this.tableNameSuffix = tableNameSuffix != null? tableNameSuffix : ""; - } + public void setTableNameSuffix(String tableNameSuffix) { + this.tableNameSuffix = tableNameSuffix != null ? tableNameSuffix : ""; + } - public void setColumnNamePrefix(String columnNamePrefix) { - this.columnNamePrefix = columnNamePrefix != null? columnNamePrefix : ""; - } + public void setColumnNamePrefix(String columnNamePrefix) { + this.columnNamePrefix = columnNamePrefix != null ? columnNamePrefix : ""; + } - public void setColumnNameSuffix(String columnNameSuffix) { - this.columnNameSuffix = columnNameSuffix != null? columnNameSuffix : ""; - } + public void setColumnNameSuffix(String columnNameSuffix) { + this.columnNameSuffix = columnNameSuffix != null ? columnNameSuffix : ""; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/TableName.java b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/TableName.java index efaa195a877efaf8fb1a8efa7551575f41133d24..b2c33cfdf13c3192283a971428c7804ed9374f75 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/db/names/TableName.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/db/names/TableName.java @@ -19,8 +19,6 @@ package ch.qos.logback.classic.db.names; */ public enum TableName { - LOGGING_EVENT, - LOGGING_EVENT_PROPERTY, - LOGGING_EVENT_EXCEPTION + LOGGING_EVENT, LOGGING_EVENT_PROPERTY, LOGGING_EVENT_EXCEPTION } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/encoder/PatternLayoutEncoder.java b/logback-classic/src/main/java/ch/qos/logback/classic/encoder/PatternLayoutEncoder.java index a88074edb86c7ee0aeb043a109852747c6a7689d..2f08202897885095153d07e0fe0d6555e224879a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/encoder/PatternLayoutEncoder.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/encoder/PatternLayoutEncoder.java @@ -19,15 +19,15 @@ import ch.qos.logback.core.pattern.PatternLayoutEncoderBase; public class PatternLayoutEncoder extends PatternLayoutEncoderBase { - @Override - public void start() { - PatternLayout patternLayout = new PatternLayout(); - patternLayout.setContext(context); - patternLayout.setPattern(getPattern()); - patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); - patternLayout.start(); - this.layout = patternLayout; - super.start(); - } - + @Override + public void start() { + PatternLayout patternLayout = new PatternLayout(); + patternLayout.setContext(context); + patternLayout.setPattern(getPattern()); + patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); + patternLayout.start(); + this.layout = patternLayout; + super.start(); + } + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/filter/LevelFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/filter/LevelFilter.java index 4e2f04ff849ece192ee781c7b7812a44e80dd04b..ae2f84a1ae68676914f5c758f57fa49b9d73ac09 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/filter/LevelFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/filter/LevelFilter.java @@ -30,28 +30,28 @@ import ch.qos.logback.core.spi.FilterReply; */ public class LevelFilter extends AbstractMatcherFilter { - Level level; - - @Override - public FilterReply decide(ILoggingEvent event) { - if (!isStarted()) { - return FilterReply.NEUTRAL; + Level level; + + @Override + public FilterReply decide(ILoggingEvent event) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + + if (event.getLevel().equals(level)) { + return onMatch; + } else { + return onMismatch; + } } - if (event.getLevel().equals(level)) { - return onMatch; - } else { - return onMismatch; + public void setLevel(Level level) { + this.level = level; } - } - - public void setLevel(Level level) { - this.level = level; - } - public void start() { - if (this.level != null) { - super.start(); + public void start() { + if (this.level != null) { + super.start(); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/filter/ThresholdFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/filter/ThresholdFilter.java index 128ad07d9b376048cc6d270c8831eb2096ede3ac..6c38ad96b8ca185e36ce29e8a9359a8dee13dc94 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/filter/ThresholdFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/filter/ThresholdFilter.java @@ -34,28 +34,28 @@ import ch.qos.logback.core.spi.FilterReply; */ public class ThresholdFilter extends Filter { - Level level; - - @Override - public FilterReply decide(ILoggingEvent event) { - if (!isStarted()) { - return FilterReply.NEUTRAL; + Level level; + + @Override + public FilterReply decide(ILoggingEvent event) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + + if (event.getLevel().isGreaterOrEqual(level)) { + return FilterReply.NEUTRAL; + } else { + return FilterReply.DENY; + } } - - if (event.getLevel().isGreaterOrEqual(level)) { - return FilterReply.NEUTRAL; - } else { - return FilterReply.DENY; + + public void setLevel(String level) { + this.level = Level.toLevel(level); } - } - - public void setLevel(String level) { - this.level = Level.toLevel(level); - } - - public void start() { - if (this.level != null) { - super.start(); + + public void start() { + if (this.level != null) { + super.start(); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/gaffer/GafferUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/gaffer/GafferUtil.java index 749a23a631274d7b30afd4561706c4c44174cf5a..4d2fd5da1abcf7a10b24643f0a6bdb6f18db056f 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/gaffer/GafferUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/gaffer/GafferUtil.java @@ -28,53 +28,52 @@ import java.net.URL; */ public class GafferUtil { - private static String ERROR_MSG = "Failed to instantiate " + ClassicConstants.GAFFER_CONFIGURATOR_FQCN; + private static String ERROR_MSG = "Failed to instantiate " + ClassicConstants.GAFFER_CONFIGURATOR_FQCN; - public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, File configFile) { - GafferConfigurator gafferConfigurator = GafferUtil.newGafferConfiguratorInstance(loggerContext, origin); - if (gafferConfigurator != null) { - gafferConfigurator.run(configFile); + public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, File configFile) { + GafferConfigurator gafferConfigurator = GafferUtil.newGafferConfiguratorInstance(loggerContext, origin); + if (gafferConfigurator != null) { + gafferConfigurator.run(configFile); + } } - } - public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, URL configFile) { - GafferConfigurator gafferConfigurator = GafferUtil.newGafferConfiguratorInstance(loggerContext, origin); - if (gafferConfigurator != null) { - gafferConfigurator.run(configFile); + public static void runGafferConfiguratorOn(LoggerContext loggerContext, Object origin, URL configFile) { + GafferConfigurator gafferConfigurator = GafferUtil.newGafferConfiguratorInstance(loggerContext, origin); + if (gafferConfigurator != null) { + gafferConfigurator.run(configFile); + } } - } - private static GafferConfigurator newGafferConfiguratorInstance(LoggerContext loggerContext, Object origin) { + private static GafferConfigurator newGafferConfiguratorInstance(LoggerContext loggerContext, Object origin) { - try { - Class gcClass = Class.forName(ClassicConstants.GAFFER_CONFIGURATOR_FQCN); - Constructor c = gcClass.getConstructor(LoggerContext.class); - return (GafferConfigurator) c.newInstance(loggerContext); - } catch (ClassNotFoundException e) { - addError(loggerContext, origin, ERROR_MSG, e); - } catch (NoSuchMethodException e) { - addError(loggerContext, origin, ERROR_MSG, e); - } catch (InvocationTargetException e) { - addError(loggerContext, origin, ERROR_MSG, e); - } catch (InstantiationException e) { - addError(loggerContext, origin, ERROR_MSG, e); - } catch (IllegalAccessException e) { - addError(loggerContext, origin, ERROR_MSG, e); + try { + Class gcClass = Class.forName(ClassicConstants.GAFFER_CONFIGURATOR_FQCN); + Constructor c = gcClass.getConstructor(LoggerContext.class); + return (GafferConfigurator) c.newInstance(loggerContext); + } catch (ClassNotFoundException e) { + addError(loggerContext, origin, ERROR_MSG, e); + } catch (NoSuchMethodException e) { + addError(loggerContext, origin, ERROR_MSG, e); + } catch (InvocationTargetException e) { + addError(loggerContext, origin, ERROR_MSG, e); + } catch (InstantiationException e) { + addError(loggerContext, origin, ERROR_MSG, e); + } catch (IllegalAccessException e) { + addError(loggerContext, origin, ERROR_MSG, e); + } + return null; } - return null; - } - private static void addError(LoggerContext context, Object origin, String msg) { - addError(context, origin, msg, null); - } - - private static void addError(LoggerContext context, Object origin, String msg, Throwable t) { - StatusManager sm = context.getStatusManager(); - if (sm == null) { - return; + private static void addError(LoggerContext context, Object origin, String msg) { + addError(context, origin, msg, null); } - sm.add(new ErrorStatus(msg, origin, t)); - } + private static void addError(LoggerContext context, Object origin, String msg, Throwable t) { + StatusManager sm = context.getStatusManager(); + if (sm == null) { + return; + } + sm.add(new ErrorStatus(msg, origin, t)); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.java index f5cb67c7b592730d7cd6e1de6ad374a7296ee90a..4b1e7aa8e72e158515dcb51d1ae6a0c51d67439a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/helpers/MDCInsertingServletFilter.java @@ -38,57 +38,51 @@ import ch.qos.logback.classic.ClassicConstants; */ public class MDCInsertingServletFilter implements Filter { - public void destroy() { - // do nothing - } - - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void destroy() { + // do nothing + } + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - insertIntoMDC(request); - try { - chain.doFilter(request, response); - } finally { - clearMDC(); + insertIntoMDC(request); + try { + chain.doFilter(request, response); + } finally { + clearMDC(); + } } - } - void insertIntoMDC(ServletRequest request) { + void insertIntoMDC(ServletRequest request) { - MDC.put(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY, request - .getRemoteHost()); + MDC.put(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY, request.getRemoteHost()); - if (request instanceof HttpServletRequest) { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - MDC.put(ClassicConstants.REQUEST_REQUEST_URI, httpServletRequest - .getRequestURI()); - StringBuffer requestURL = httpServletRequest.getRequestURL(); - if (requestURL != null) { - MDC.put(ClassicConstants.REQUEST_REQUEST_URL, requestURL.toString()); - } - MDC.put(ClassicConstants.REQUEST_METHOD, httpServletRequest.getMethod()); - MDC.put(ClassicConstants.REQUEST_QUERY_STRING, httpServletRequest.getQueryString()); - MDC.put(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY, httpServletRequest - .getHeader("User-Agent")); - MDC.put(ClassicConstants.REQUEST_X_FORWARDED_FOR, httpServletRequest - .getHeader("X-Forwarded-For")); - } + if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + MDC.put(ClassicConstants.REQUEST_REQUEST_URI, httpServletRequest.getRequestURI()); + StringBuffer requestURL = httpServletRequest.getRequestURL(); + if (requestURL != null) { + MDC.put(ClassicConstants.REQUEST_REQUEST_URL, requestURL.toString()); + } + MDC.put(ClassicConstants.REQUEST_METHOD, httpServletRequest.getMethod()); + MDC.put(ClassicConstants.REQUEST_QUERY_STRING, httpServletRequest.getQueryString()); + MDC.put(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY, httpServletRequest.getHeader("User-Agent")); + MDC.put(ClassicConstants.REQUEST_X_FORWARDED_FOR, httpServletRequest.getHeader("X-Forwarded-For")); + } - } + } - void clearMDC() { - MDC.remove(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY); - MDC.remove(ClassicConstants.REQUEST_REQUEST_URI); - MDC.remove(ClassicConstants.REQUEST_QUERY_STRING); - // removing possibly inexistent item is OK - MDC.remove(ClassicConstants.REQUEST_REQUEST_URL); - MDC.remove(ClassicConstants.REQUEST_METHOD); - MDC.remove(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY); - MDC.remove(ClassicConstants.REQUEST_X_FORWARDED_FOR); - } + void clearMDC() { + MDC.remove(ClassicConstants.REQUEST_REMOTE_HOST_MDC_KEY); + MDC.remove(ClassicConstants.REQUEST_REQUEST_URI); + MDC.remove(ClassicConstants.REQUEST_QUERY_STRING); + // removing possibly inexistent item is OK + MDC.remove(ClassicConstants.REQUEST_REQUEST_URL); + MDC.remove(ClassicConstants.REQUEST_METHOD); + MDC.remove(ClassicConstants.REQUEST_USER_AGENT_MDC_KEY); + MDC.remove(ClassicConstants.REQUEST_X_FORWARDED_FOR); + } - public void init(FilterConfig arg0) throws ServletException { - // do nothing - } + public void init(FilterConfig arg0) throws ServletException { + // do nothing + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultCssBuilder.java b/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultCssBuilder.java index 200d1da1b0536c2e71086529a5486b31b3531ff1..7cadbe823c31196ffdd1631d8e2691b70be71b4f 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultCssBuilder.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultCssBuilder.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.html; - import ch.qos.logback.core.CoreConstants; import static ch.qos.logback.core.CoreConstants.LINE_SEPARATOR; import ch.qos.logback.core.html.CssBuilder; @@ -27,49 +26,43 @@ import ch.qos.logback.core.html.CssBuilder; */ public class DefaultCssBuilder implements CssBuilder { - public void addCss(StringBuilder sbuf) { - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - } + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultThrowableRenderer.java b/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultThrowableRenderer.java index 47a39ca0b3c3ad353577cf16e59434724433ecb3..05520b3a8493658a4cfd2420c73fd6b73b9271d3 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultThrowableRenderer.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/html/DefaultThrowableRenderer.java @@ -20,49 +20,46 @@ import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.helpers.Transform; import ch.qos.logback.core.html.IThrowableRenderer; -public class DefaultThrowableRenderer implements - IThrowableRenderer { +public class DefaultThrowableRenderer implements IThrowableRenderer { - static final String TRACE_PREFIX = "
    "; + static final String TRACE_PREFIX = "
    "; - public void render(StringBuilder sbuf, ILoggingEvent event) { - IThrowableProxy tp = event.getThrowableProxy(); - sbuf.append(""); - while (tp != null) { - render(sbuf, tp); - tp = tp.getCause(); + public void render(StringBuilder sbuf, ILoggingEvent event) { + IThrowableProxy tp = event.getThrowableProxy(); + sbuf.append(""); + while (tp != null) { + render(sbuf, tp); + tp = tp.getCause(); + } + sbuf.append(""); } - sbuf.append(""); - } - void render(StringBuilder sbuf, IThrowableProxy tp) { - printFirstLine(sbuf, tp); - - int commonFrames = tp.getCommonFrames(); - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - - for (int i = 0; i < stepArray.length - commonFrames; i++) { - StackTraceElementProxy step = stepArray[i]; - sbuf.append(TRACE_PREFIX); - sbuf.append(Transform.escapeTags(step.toString())); - sbuf.append(CoreConstants.LINE_SEPARATOR); - } - - if (commonFrames > 0) { - sbuf.append(TRACE_PREFIX); - sbuf.append("\t... ").append(commonFrames).append(" common frames omitted") - .append(CoreConstants.LINE_SEPARATOR); + void render(StringBuilder sbuf, IThrowableProxy tp) { + printFirstLine(sbuf, tp); + + int commonFrames = tp.getCommonFrames(); + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + + for (int i = 0; i < stepArray.length - commonFrames; i++) { + StackTraceElementProxy step = stepArray[i]; + sbuf.append(TRACE_PREFIX); + sbuf.append(Transform.escapeTags(step.toString())); + sbuf.append(CoreConstants.LINE_SEPARATOR); + } + + if (commonFrames > 0) { + sbuf.append(TRACE_PREFIX); + sbuf.append("\t... ").append(commonFrames).append(" common frames omitted").append(CoreConstants.LINE_SEPARATOR); + } } - } - public void printFirstLine(StringBuilder sb, IThrowableProxy tp) { - int commonFrames = tp.getCommonFrames(); - if (commonFrames > 0) { - sb.append("
").append(CoreConstants.CAUSED_BY); + public void printFirstLine(StringBuilder sb, IThrowableProxy tp) { + int commonFrames = tp.getCommonFrames(); + if (commonFrames > 0) { + sb.append("
").append(CoreConstants.CAUSED_BY); + } + sb.append(tp.getClassName()).append(": ").append(Transform.escapeTags(tp.getMessage())); + sb.append(CoreConstants.LINE_SEPARATOR); } - sb.append(tp.getClassName()).append(": ").append( - Transform.escapeTags(tp.getMessage())); - sb.append(CoreConstants.LINE_SEPARATOR); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/html/HTMLLayout.java b/logback-classic/src/main/java/ch/qos/logback/classic/html/HTMLLayout.java index eecc2a113297de51f52dfa32db203003ee44a57f..904b2311df7114b1841ee3a0cc4d7fbc553b0f61 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/html/HTMLLayout.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/html/HTMLLayout.java @@ -39,105 +39,104 @@ import static ch.qos.logback.core.CoreConstants.LINE_SEPARATOR; */ public class HTMLLayout extends HTMLLayoutBase { - /** - * Default pattern string for log output. - */ - static final String DEFAULT_CONVERSION_PATTERN = "%date%thread%level%logger%mdc%msg"; - - IThrowableRenderer throwableRenderer; - - /** - * Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. - * - * The default pattern just produces the application supplied message. - */ - public HTMLLayout() { - pattern = DEFAULT_CONVERSION_PATTERN; - throwableRenderer = new DefaultThrowableRenderer(); - cssBuilder = new DefaultCssBuilder(); - } - - @Override - public void start() { - int errorCount = 0; - if (throwableRenderer == null) { - addError("ThrowableRender cannot be null."); - errorCount++; + /** + * Default pattern string for log output. + */ + static final String DEFAULT_CONVERSION_PATTERN = "%date%thread%level%logger%mdc%msg"; + + IThrowableRenderer throwableRenderer; + + /** + * Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. + * + * The default pattern just produces the application supplied message. + */ + public HTMLLayout() { + pattern = DEFAULT_CONVERSION_PATTERN; + throwableRenderer = new DefaultThrowableRenderer(); + cssBuilder = new DefaultCssBuilder(); } - if (errorCount == 0) { - super.start(); - } - } - - protected Map getDefaultConverterMap() { - return PatternLayout.defaultConverterMap; - } - public String doLayout(ILoggingEvent event) { - StringBuilder buf = new StringBuilder(); - startNewTableIfLimitReached(buf); + @Override + public void start() { + int errorCount = 0; + if (throwableRenderer == null) { + addError("ThrowableRender cannot be null."); + errorCount++; + } + if (errorCount == 0) { + super.start(); + } + } - boolean odd = true; - if (((counter++) & 1) == 0) { - odd = false; + protected Map getDefaultConverterMap() { + return PatternLayout.defaultConverterMap; } - String level = event.getLevel().toString().toLowerCase(); + public String doLayout(ILoggingEvent event) { + StringBuilder buf = new StringBuilder(); + startNewTableIfLimitReached(buf); + + boolean odd = true; + if (((counter++) & 1) == 0) { + odd = false; + } + + String level = event.getLevel().toString().toLowerCase(); + + buf.append(LINE_SEPARATOR); + buf.append(""); + } else { + buf.append(" even\">"); + } + buf.append(LINE_SEPARATOR); + + Converter c = head; + while (c != null) { + appendEventToBuffer(buf, c, event); + c = c.getNext(); + } + buf.append(""); + buf.append(LINE_SEPARATOR); + + if (event.getThrowableProxy() != null) { + throwableRenderer.render(buf, event); + } + return buf.toString(); + } - buf.append(LINE_SEPARATOR); - buf.append(""); - } else { - buf.append(" even\">"); + private void appendEventToBuffer(StringBuilder buf, Converter c, ILoggingEvent event) { + buf.append(""); + buf.append(Transform.escapeTags(c.convert(event))); + buf.append(""); + buf.append(LINE_SEPARATOR); } - buf.append(LINE_SEPARATOR); - Converter c = head; - while (c != null) { - appendEventToBuffer(buf, c, event); - c = c.getNext(); + public IThrowableRenderer getThrowableRenderer() { + return throwableRenderer; } - buf.append(""); - buf.append(LINE_SEPARATOR); - if (event.getThrowableProxy() != null) { - throwableRenderer.render(buf, event); + public void setThrowableRenderer(IThrowableRenderer throwableRenderer) { + this.throwableRenderer = throwableRenderer; } - return buf.toString(); - } - - private void appendEventToBuffer(StringBuilder buf, - Converter c, ILoggingEvent event) { - buf.append(""); - buf.append(Transform.escapeTags(c.convert(event))); - buf.append(""); - buf.append(LINE_SEPARATOR); - } - - public IThrowableRenderer getThrowableRenderer() { - return throwableRenderer; - } - - public void setThrowableRenderer(IThrowableRenderer throwableRenderer) { - this.throwableRenderer = throwableRenderer; - } - - @Override - protected String computeConverterName(Converter c) { - if(c instanceof MDCConverter) { - MDCConverter mc = (MDCConverter) c; - String key = mc.getFirstOption(); - if(key != null) { - return key; - } else { - return "MDC"; - } - } else { - return super.computeConverterName(c); + + @Override + protected String computeConverterName(Converter c) { + if (c instanceof MDCConverter) { + MDCConverter mc = (MDCConverter) c; + String key = mc.getFirstOption(); + if (key != null) { + return key; + } else { + return "MDC"; + } + } else { + return super.computeConverterName(c); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/html/UrlCssBuilder.java b/logback-classic/src/main/java/ch/qos/logback/classic/html/UrlCssBuilder.java index 2fd3373ab8aefdded9ec8c8f5e830dbd5278cfdd..d4216f42f05244a4a3ccb2b1f9a0ec24771c4288 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/html/UrlCssBuilder.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/html/UrlCssBuilder.java @@ -15,7 +15,6 @@ package ch.qos.logback.classic.html; import ch.qos.logback.core.html.CssBuilder; - /** * This class helps the HTMLLayout build the CSS link. * It either provides the HTMLLayout with a default css file, @@ -25,19 +24,19 @@ import ch.qos.logback.core.html.CssBuilder; */ public class UrlCssBuilder implements CssBuilder { - String url = "http://logback.qos.ch/css/classic.css"; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public void addCss(StringBuilder sbuf) { - sbuf.append(""); - } + String url = "http://logback.qos.ch/css/classic.css"; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public void addCss(StringBuilder sbuf) { + sbuf.append(""); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfiguratorMBean.java b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfiguratorMBean.java index 68e1cd80d3be42c10b8bf075a1a5ec876442aa30..8700cd266e65751ef8841520b86a33bb753d933e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfiguratorMBean.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfiguratorMBean.java @@ -20,20 +20,20 @@ import java.util.List; import ch.qos.logback.core.joran.spi.JoranException; public interface JMXConfiguratorMBean { - - void reloadDefaultConfiguration() throws JoranException; - - void reloadByFileName(String fileName) throws JoranException, FileNotFoundException; - - void reloadByURL(URL url) throws JoranException; - - void setLoggerLevel(String loggerName, String levelStr); - - String getLoggerLevel(String loggerName); - - String getLoggerEffectiveLevel(String loggerName); - - List getLoggerList(); - - List getStatuses(); + + void reloadDefaultConfiguration() throws JoranException; + + void reloadByFileName(String fileName) throws JoranException, FileNotFoundException; + + void reloadByURL(URL url) throws JoranException; + + void setLoggerLevel(String loggerName, String levelStr); + + String getLoggerLevel(String loggerName); + + String getLoggerEffectiveLevel(String loggerName); + + List getLoggerList(); + + List getStatuses(); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/MBeanUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/MBeanUtil.java index 1e049a5cef3edacc1c8087094dddb6560942ba1d..14ad2a803690e3f00d5494d475c605bc745bf7ec 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/MBeanUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/MBeanUtil.java @@ -25,66 +25,58 @@ import ch.qos.logback.core.status.StatusUtil; public class MBeanUtil { - static final String DOMAIN = "ch.qos.logback.classic"; + static final String DOMAIN = "ch.qos.logback.classic"; - static public String getObjectNameFor(String contextName, Class type) { - return DOMAIN + ":Name=" + contextName + ",Type=" - + type.getName(); - } + static public String getObjectNameFor(String contextName, Class type) { + return DOMAIN + ":Name=" + contextName + ",Type=" + type.getName(); + } - public static ObjectName string2ObjectName(Context context, Object caller, - String objectNameAsStr) { - String msg = "Failed to convert [" + objectNameAsStr + "] to ObjectName"; + public static ObjectName string2ObjectName(Context context, Object caller, String objectNameAsStr) { + String msg = "Failed to convert [" + objectNameAsStr + "] to ObjectName"; - StatusUtil statusUtil = new StatusUtil(context); - try { - return new ObjectName(objectNameAsStr); - } catch (MalformedObjectNameException e) { - statusUtil.addError(caller, msg, e); - return null; - } catch (NullPointerException e) { - statusUtil.addError(caller, msg, e); - return null; + StatusUtil statusUtil = new StatusUtil(context); + try { + return new ObjectName(objectNameAsStr); + } catch (MalformedObjectNameException e) { + statusUtil.addError(caller, msg, e); + return null; + } catch (NullPointerException e) { + statusUtil.addError(caller, msg, e); + return null; + } } - } - public static boolean isRegistered(MBeanServer mbs, ObjectName objectName) { - return mbs.isRegistered(objectName); - } + public static boolean isRegistered(MBeanServer mbs, ObjectName objectName) { + return mbs.isRegistered(objectName); + } - public static void createAndRegisterJMXConfigurator( - MBeanServer mbs, LoggerContext loggerContext, - JMXConfigurator jmxConfigurator, ObjectName objectName, Object caller) { - try { - mbs.registerMBean(jmxConfigurator, objectName); - } catch (Exception e) { - StatusUtil statusUtil = new StatusUtil(loggerContext); - statusUtil.addError(caller, "Failed to create mbean", e); + public static void createAndRegisterJMXConfigurator(MBeanServer mbs, LoggerContext loggerContext, JMXConfigurator jmxConfigurator, ObjectName objectName, + Object caller) { + try { + mbs.registerMBean(jmxConfigurator, objectName); + } catch (Exception e) { + StatusUtil statusUtil = new StatusUtil(loggerContext); + statusUtil.addError(caller, "Failed to create mbean", e); + } } - } - public static void unregister(LoggerContext loggerContext, MBeanServer mbs, - ObjectName objectName, Object caller) { + public static void unregister(LoggerContext loggerContext, MBeanServer mbs, ObjectName objectName, Object caller) { - StatusUtil statusUtil = new StatusUtil(loggerContext); - if (mbs.isRegistered(objectName)) { - try { - statusUtil.addInfo(caller, "Unregistering mbean [" - + objectName + "]"); - mbs.unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { - // this is theoretically impossible - statusUtil.addError(caller, "Failed to unregister mbean" - + objectName, e); - } catch (MBeanRegistrationException e) { - // this is theoretically impossible - statusUtil.addError(caller, "Failed to unregister mbean" - + objectName, e); - } - } else { - statusUtil.addInfo(caller, "mbean [" + objectName - + "] does not seem to be registered"); + StatusUtil statusUtil = new StatusUtil(loggerContext); + if (mbs.isRegistered(objectName)) { + try { + statusUtil.addInfo(caller, "Unregistering mbean [" + objectName + "]"); + mbs.unregisterMBean(objectName); + } catch (InstanceNotFoundException e) { + // this is theoretically impossible + statusUtil.addError(caller, "Failed to unregister mbean" + objectName, e); + } catch (MBeanRegistrationException e) { + // this is theoretically impossible + statusUtil.addError(caller, "Failed to unregister mbean" + objectName, e); + } + } else { + statusUtil.addInfo(caller, "mbean [" + objectName + "] does not seem to be registered"); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/JoranConfigurator.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/JoranConfigurator.java index 94a66fa579e37053186adb38aacc0d339018d331..2328c8b4172ffa47e36a147c73e31abf64b55955 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/JoranConfigurator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/JoranConfigurator.java @@ -36,62 +36,53 @@ import ch.qos.logback.core.joran.spi.RuleStore; */ public class JoranConfigurator extends JoranConfiguratorBase { - @Override - public void addInstanceRules(RuleStore rs) { - // parent rules already added - super.addInstanceRules(rs); + @Override + public void addInstanceRules(RuleStore rs) { + // parent rules already added + super.addInstanceRules(rs); - rs.addRule(new ElementSelector("configuration"), new ConfigurationAction()); + rs.addRule(new ElementSelector("configuration"), new ConfigurationAction()); - rs.addRule(new ElementSelector("configuration/contextName"), - new ContextNameAction()); - rs.addRule(new ElementSelector("configuration/contextListener"), - new LoggerContextListenerAction()); - rs.addRule(new ElementSelector("configuration/insertFromJNDI"), - new InsertFromJNDIAction()); - rs.addRule(new ElementSelector("configuration/evaluator"), new EvaluatorAction()); + rs.addRule(new ElementSelector("configuration/contextName"), new ContextNameAction()); + rs.addRule(new ElementSelector("configuration/contextListener"), new LoggerContextListenerAction()); + rs.addRule(new ElementSelector("configuration/insertFromJNDI"), new InsertFromJNDIAction()); + rs.addRule(new ElementSelector("configuration/evaluator"), new EvaluatorAction()); - rs.addRule(new ElementSelector("configuration/appender/sift"), new SiftAction()); - rs.addRule(new ElementSelector("configuration/appender/sift/*"), new NOPAction()); + rs.addRule(new ElementSelector("configuration/appender/sift"), new SiftAction()); + rs.addRule(new ElementSelector("configuration/appender/sift/*"), new NOPAction()); - rs.addRule(new ElementSelector("configuration/logger"), new LoggerAction()); - rs.addRule(new ElementSelector("configuration/logger/level"), new LevelAction()); + rs.addRule(new ElementSelector("configuration/logger"), new LoggerAction()); + rs.addRule(new ElementSelector("configuration/logger/level"), new LevelAction()); - rs.addRule(new ElementSelector("configuration/root"), new RootLoggerAction()); - rs.addRule(new ElementSelector("configuration/root/level"), new LevelAction()); - rs.addRule(new ElementSelector("configuration/logger/appender-ref"), - new AppenderRefAction()); - rs.addRule(new ElementSelector("configuration/root/appender-ref"), - new AppenderRefAction()); - - // add if-then-else support - rs.addRule(new ElementSelector("*/if"), new IfAction()); - rs.addRule(new ElementSelector("*/if/then"), new ThenAction()); - rs.addRule(new ElementSelector("*/if/then/*"), new NOPAction()); - rs.addRule(new ElementSelector("*/if/else"), new ElseAction()); - rs.addRule(new ElementSelector("*/if/else/*"), new NOPAction()); - - // add jmxConfigurator only if we have JMX available. - // If running under JDK 1.4 (retrotranslateed logback) then we - // might not have JMX. - if (PlatformInfo.hasJMXObjectName()) { - rs.addRule(new ElementSelector("configuration/jmxConfigurator"), - new JMXConfiguratorAction()); - } - rs.addRule(new ElementSelector("configuration/include"), new IncludeAction()); + rs.addRule(new ElementSelector("configuration/root"), new RootLoggerAction()); + rs.addRule(new ElementSelector("configuration/root/level"), new LevelAction()); + rs.addRule(new ElementSelector("configuration/logger/appender-ref"), new AppenderRefAction()); + rs.addRule(new ElementSelector("configuration/root/appender-ref"), new AppenderRefAction()); + + // add if-then-else support + rs.addRule(new ElementSelector("*/if"), new IfAction()); + rs.addRule(new ElementSelector("*/if/then"), new ThenAction()); + rs.addRule(new ElementSelector("*/if/then/*"), new NOPAction()); + rs.addRule(new ElementSelector("*/if/else"), new ElseAction()); + rs.addRule(new ElementSelector("*/if/else/*"), new NOPAction()); + + // add jmxConfigurator only if we have JMX available. + // If running under JDK 1.4 (retrotranslateed logback) then we + // might not have JMX. + if (PlatformInfo.hasJMXObjectName()) { + rs.addRule(new ElementSelector("configuration/jmxConfigurator"), new JMXConfiguratorAction()); + } + rs.addRule(new ElementSelector("configuration/include"), new IncludeAction()); + + rs.addRule(new ElementSelector("configuration/consolePlugin"), new ConsolePluginAction()); - rs.addRule(new ElementSelector("configuration/consolePlugin"), - new ConsolePluginAction()); - - rs.addRule(new ElementSelector("configuration/receiver"), - new ReceiverAction()); - - } + rs.addRule(new ElementSelector("configuration/receiver"), new ReceiverAction()); - @Override - protected void addDefaultNestedComponentRegistryRules( - DefaultNestedComponentRegistry registry) { - DefaultNestedComponentRules.addDefaultNestedComponentRegistryRules(registry); - } + } + + @Override + protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + DefaultNestedComponentRules.addDefaultNestedComponentRegistryRules(registry); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConfigurationAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConfigurationAction.java index a3df544865e5ef24a9416218d964c144944fa338..77849d4020e4913c97dfb13147f56ba06de5760a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConfigurationAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConfigurationAction.java @@ -28,90 +28,85 @@ import ch.qos.logback.core.util.OptionHelper; import ch.qos.logback.core.util.StatusListenerConfigHelper; public class ConfigurationAction extends Action { - static final String INTERNAL_DEBUG_ATTR = "debug"; - static final String PACKAGING_DATA_ATTR = "packagingData"; - static final String SCAN_ATTR = "scan"; - static final String SCAN_PERIOD_ATTR = "scanPeriod"; - static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback.debug"; - - long threshold = 0; - - public void begin(InterpretationContext ic, String name, Attributes attributes) { - threshold = System.currentTimeMillis(); - - // See LOGBACK-527 (the system property is looked up first. Thus, it overrides - // the equivalent property in the config file. This reversal of scope priority is justified - // by the use case: the admin trying to chase rogue config file - String debugAttrib = getSystemProperty(DEBUG_SYSTEM_PROPERTY_KEY); - if (debugAttrib == null) { - debugAttrib = ic.subst(attributes.getValue(INTERNAL_DEBUG_ATTR)); - } + static final String INTERNAL_DEBUG_ATTR = "debug"; + static final String PACKAGING_DATA_ATTR = "packagingData"; + static final String SCAN_ATTR = "scan"; + static final String SCAN_PERIOD_ATTR = "scanPeriod"; + static final String DEBUG_SYSTEM_PROPERTY_KEY = "logback.debug"; + + long threshold = 0; + + public void begin(InterpretationContext ic, String name, Attributes attributes) { + threshold = System.currentTimeMillis(); + + // See LOGBACK-527 (the system property is looked up first. Thus, it overrides + // the equivalent property in the config file. This reversal of scope priority is justified + // by the use case: the admin trying to chase rogue config file + String debugAttrib = getSystemProperty(DEBUG_SYSTEM_PROPERTY_KEY); + if (debugAttrib == null) { + debugAttrib = ic.subst(attributes.getValue(INTERNAL_DEBUG_ATTR)); + } - if (OptionHelper.isEmpty(debugAttrib) || debugAttrib.equalsIgnoreCase("false") - || debugAttrib.equalsIgnoreCase("null")) { - addInfo(INTERNAL_DEBUG_ATTR + " attribute not set"); - } else { - StatusListenerConfigHelper.addOnConsoleListenerInstance(context, new OnConsoleStatusListener()); - } + if (OptionHelper.isEmpty(debugAttrib) || debugAttrib.equalsIgnoreCase("false") || debugAttrib.equalsIgnoreCase("null")) { + addInfo(INTERNAL_DEBUG_ATTR + " attribute not set"); + } else { + StatusListenerConfigHelper.addOnConsoleListenerInstance(context, new OnConsoleStatusListener()); + } - processScanAttrib(ic, attributes); + processScanAttrib(ic, attributes); - ContextUtil contextUtil = new ContextUtil(context); - contextUtil.addHostNameAsProperty(); + ContextUtil contextUtil = new ContextUtil(context); + contextUtil.addHostNameAsProperty(); - LoggerContext lc = (LoggerContext) context; - boolean packagingData = OptionHelper.toBoolean( - ic.subst(attributes.getValue(PACKAGING_DATA_ATTR)), - LoggerContext.DEFAULT_PACKAGING_DATA); - lc.setPackagingDataEnabled(packagingData); + LoggerContext lc = (LoggerContext) context; + boolean packagingData = OptionHelper.toBoolean(ic.subst(attributes.getValue(PACKAGING_DATA_ATTR)), LoggerContext.DEFAULT_PACKAGING_DATA); + lc.setPackagingDataEnabled(packagingData); - if (EnvUtil.isGroovyAvailable()) { - contextUtil.addGroovyPackages(lc.getFrameworkPackages()); - } + if (EnvUtil.isGroovyAvailable()) { + contextUtil.addGroovyPackages(lc.getFrameworkPackages()); + } - // the context is turbo filter attachable, so it is pushed on top of the - // stack - ic.pushObject(getContext()); - } - - String getSystemProperty(String name) { - /* - * LOGBACK-743: accessing a system property in the presence of a - * SecurityManager (e.g. applet sandbox) can result in a SecurityException. - */ - try { - return System.getProperty(name); - } catch (SecurityException ex) { - return null; + // the context is turbo filter attachable, so it is pushed on top of the + // stack + ic.pushObject(getContext()); } - } - - void processScanAttrib(InterpretationContext ic, Attributes attributes) { - String scanAttrib = ic.subst(attributes.getValue(SCAN_ATTR)); - if (!OptionHelper.isEmpty(scanAttrib) - && !"false".equalsIgnoreCase(scanAttrib)) { - ReconfigureOnChangeFilter rocf = new ReconfigureOnChangeFilter(); - rocf.setContext(context); - String scanPeriodAttrib = ic.subst(attributes.getValue(SCAN_PERIOD_ATTR)); - if (!OptionHelper.isEmpty(scanPeriodAttrib)) { + + String getSystemProperty(String name) { + /* + * LOGBACK-743: accessing a system property in the presence of a SecurityManager (e.g. applet sandbox) can + * result in a SecurityException. + */ try { - Duration duration = Duration.valueOf(scanPeriodAttrib); - rocf.setRefreshPeriod(duration.getMilliseconds()); - addInfo("Setting ReconfigureOnChangeFilter scanning period to " - + duration); - } catch (NumberFormatException nfe) { - addError("Error while converting [" + scanAttrib + "] to long", nfe); + return System.getProperty(name); + } catch (SecurityException ex) { + return null; } - } - rocf.start(); - LoggerContext lc = (LoggerContext) context; - addInfo("Adding ReconfigureOnChangeFilter as a turbo filter"); - lc.addTurboFilter(rocf); } - } - public void end(InterpretationContext ec, String name) { - addInfo("End of configuration."); - ec.popObject(); - } + void processScanAttrib(InterpretationContext ic, Attributes attributes) { + String scanAttrib = ic.subst(attributes.getValue(SCAN_ATTR)); + if (!OptionHelper.isEmpty(scanAttrib) && !"false".equalsIgnoreCase(scanAttrib)) { + ReconfigureOnChangeFilter rocf = new ReconfigureOnChangeFilter(); + rocf.setContext(context); + String scanPeriodAttrib = ic.subst(attributes.getValue(SCAN_PERIOD_ATTR)); + if (!OptionHelper.isEmpty(scanPeriodAttrib)) { + try { + Duration duration = Duration.valueOf(scanPeriodAttrib); + rocf.setRefreshPeriod(duration.getMilliseconds()); + addInfo("Setting ReconfigureOnChangeFilter scanning period to " + duration); + } catch (NumberFormatException nfe) { + addError("Error while converting [" + scanAttrib + "] to long", nfe); + } + } + rocf.start(); + LoggerContext lc = (LoggerContext) context; + addInfo("Adding ReconfigureOnChangeFilter as a turbo filter"); + lc.addTurboFilter(rocf); + } + } + + public void end(InterpretationContext ec, String name) { + addInfo("End of configuration."); + ec.popObject(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConsolePluginAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConsolePluginAction.java index 76d329aa7cbabe78b7254ac7d82093356ed7d389..d4df5dd92e056739635a8fae4b5266a00ef251bb 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConsolePluginAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ConsolePluginAction.java @@ -24,41 +24,39 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; public class ConsolePluginAction extends Action { - private static final String PORT_ATTR = "port"; - private static final Integer DEFAULT_PORT = 4321; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - String portStr = attributes.getValue(PORT_ATTR); - Integer port = null; - - if (portStr == null) { - port = DEFAULT_PORT; - } else { - try { - port = Integer.valueOf(portStr); - } catch (NumberFormatException ex) { - addError("Port " + portStr - + " in ConsolePlugin config is not a correct number"); - } + private static final String PORT_ATTR = "port"; + private static final Integer DEFAULT_PORT = 4321; + + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + String portStr = attributes.getValue(PORT_ATTR); + Integer port = null; + + if (portStr == null) { + port = DEFAULT_PORT; + } else { + try { + port = Integer.valueOf(portStr); + } catch (NumberFormatException ex) { + addError("Port " + portStr + " in ConsolePlugin config is not a correct number"); + } + } + + LoggerContext lc = (LoggerContext) ec.getContext(); + SocketAppender appender = new SocketAppender(); + appender.setContext(lc); + appender.setIncludeCallerData(true); + appender.setRemoteHost("localhost"); + appender.setPort(port.intValue()); + appender.start(); + Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + root.addAppender(appender); + + addInfo("Sending LoggingEvents to the plugin using port " + port); } - LoggerContext lc = (LoggerContext)ec.getContext(); - SocketAppender appender = new SocketAppender(); - appender.setContext(lc); - appender.setIncludeCallerData(true); - appender.setRemoteHost("localhost"); - appender.setPort(port.intValue()); - appender.start(); - Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - root.addAppender(appender); - - addInfo("Sending LoggingEvents to the plugin using port " + port); - } - - @Override - public void end(InterpretationContext ec, String name) throws ActionException { + @Override + public void end(InterpretationContext ec, String name) throws ActionException { - } + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ContextNameAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ContextNameAction.java index b05c3e8772558e4af3e6a32aeacdf14ed3930c95..537a7064359d025d0e1808d1da77dd462064f8aa 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ContextNameAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ContextNameAction.java @@ -20,21 +20,20 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; public class ContextNameAction extends Action { - public void begin(InterpretationContext ec, String name, Attributes attributes) { - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } - public void body(InterpretationContext ec, String body) { + public void body(InterpretationContext ec, String body) { - String finalBody = ec.subst(body); - addInfo("Setting logger context name as [" + finalBody + "]"); - try { - context.setName(finalBody); - } catch (IllegalStateException e) { - addError("Failed to rename context [" + context.getName() + "] as [" - + finalBody + "]", e); + String finalBody = ec.subst(body); + addInfo("Setting logger context name as [" + finalBody + "]"); + try { + context.setName(finalBody); + } catch (IllegalStateException e) { + addError("Failed to rename context [" + context.getName() + "] as [" + finalBody + "]", e); + } } - } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/EvaluatorAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/EvaluatorAction.java index 47abbeceffc73d95ee4c22404b3237dcb6febfc0..219d235e1fc4da836ecca69436fd79f257dc246f 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/EvaluatorAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/EvaluatorAction.java @@ -17,7 +17,7 @@ import ch.qos.logback.classic.boolex.JaninoEventEvaluator; import ch.qos.logback.core.joran.action.AbstractEventEvaluatorAction; public class EvaluatorAction extends AbstractEventEvaluatorAction { - protected String defaultClassName() { - return JaninoEventEvaluator.class.getName(); - } + protected String defaultClassName() { + return JaninoEventEvaluator.class.getName(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/InsertFromJNDIAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/InsertFromJNDIAction.java index 94fb884340d1adfab03bc75685b202ce7804a004..d1fcb7915078b925b32243966c557528dd142ed8 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/InsertFromJNDIAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/InsertFromJNDIAction.java @@ -33,52 +33,51 @@ import ch.qos.logback.core.util.OptionHelper; */ public class InsertFromJNDIAction extends Action { - public static final String ENV_ENTRY_NAME_ATTR="env-entry-name"; - public static final String AS_ATTR="as"; - - public void begin(InterpretationContext ec, String name, Attributes attributes) { - - int errorCount = 0; - String envEntryName = ec.subst(attributes.getValue(ENV_ENTRY_NAME_ATTR)); - String asKey = ec.subst(attributes.getValue(AS_ATTR)); - - String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); - Scope scope = ActionUtil.stringToScope(scopeStr); - - String envEntryValue; - - if(OptionHelper.isEmpty(envEntryName)) { - String lineColStr = getLineColStr(ec); - addError("["+ENV_ENTRY_NAME_ATTR+"] missing, around "+lineColStr); - errorCount++; - } - - if(OptionHelper.isEmpty(asKey)) { - String lineColStr = getLineColStr(ec); - addError("["+AS_ATTR+"] missing, around "+lineColStr); - errorCount++; - } - - if(errorCount != 0) { - return; - } - - try { - Context ctx = JNDIUtil.getInitialContext(); - envEntryValue = JNDIUtil.lookup(ctx, envEntryName); - if(OptionHelper.isEmpty(envEntryValue)) { - addError("["+envEntryName+"] has null or empty value"); - } else { - addInfo("Setting variable ["+asKey+"] to ["+envEntryValue+"] in ["+scope+"] scope"); - ActionUtil.setProperty(ec, asKey, envEntryValue, scope); - } - } catch (NamingException e) { - addError("Failed to lookup JNDI env-entry ["+envEntryName+"]"); + public static final String ENV_ENTRY_NAME_ATTR = "env-entry-name"; + public static final String AS_ATTR = "as"; + + public void begin(InterpretationContext ec, String name, Attributes attributes) { + + int errorCount = 0; + String envEntryName = ec.subst(attributes.getValue(ENV_ENTRY_NAME_ATTR)); + String asKey = ec.subst(attributes.getValue(AS_ATTR)); + + String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); + Scope scope = ActionUtil.stringToScope(scopeStr); + + String envEntryValue; + + if (OptionHelper.isEmpty(envEntryName)) { + String lineColStr = getLineColStr(ec); + addError("[" + ENV_ENTRY_NAME_ATTR + "] missing, around " + lineColStr); + errorCount++; + } + + if (OptionHelper.isEmpty(asKey)) { + String lineColStr = getLineColStr(ec); + addError("[" + AS_ATTR + "] missing, around " + lineColStr); + errorCount++; + } + + if (errorCount != 0) { + return; + } + + try { + Context ctx = JNDIUtil.getInitialContext(); + envEntryValue = JNDIUtil.lookup(ctx, envEntryName); + if (OptionHelper.isEmpty(envEntryValue)) { + addError("[" + envEntryName + "] has null or empty value"); + } else { + addInfo("Setting variable [" + asKey + "] to [" + envEntryValue + "] in [" + scope + "] scope"); + ActionUtil.setProperty(ec, asKey, envEntryValue, scope); + } + } catch (NamingException e) { + addError("Failed to lookup JNDI env-entry [" + envEntryName + "]"); + } + } - - - } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/JMXConfiguratorAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/JMXConfiguratorAction.java index b37c2f24205bd83d51071e8c892ef54543b4b5ca..700f4ab5659fa3b2ab57f57b104864bbb76d5e83 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/JMXConfiguratorAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/JMXConfiguratorAction.java @@ -30,60 +30,53 @@ import ch.qos.logback.core.util.OptionHelper; public class JMXConfiguratorAction extends Action { - static final String OBJECT_NAME_ATTRIBUTE_NAME = "objectName"; - static final String CONTEXT_NAME_ATTRIBUTE_NAME = "contextName"; - static final char JMX_NAME_SEPARATOR = ','; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - addInfo("begin"); + static final String OBJECT_NAME_ATTRIBUTE_NAME = "objectName"; + static final String CONTEXT_NAME_ATTRIBUTE_NAME = "contextName"; + static final char JMX_NAME_SEPARATOR = ','; + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + addInfo("begin"); - String contextName = context.getName(); - String contextNameAttributeVal = attributes - .getValue(CONTEXT_NAME_ATTRIBUTE_NAME); - if(!OptionHelper.isEmpty(contextNameAttributeVal)) { - contextName = contextNameAttributeVal; - } + String contextName = context.getName(); + String contextNameAttributeVal = attributes.getValue(CONTEXT_NAME_ATTRIBUTE_NAME); + if (!OptionHelper.isEmpty(contextNameAttributeVal)) { + contextName = contextNameAttributeVal; + } - String objectNameAsStr; - String objectNameAttributeVal = attributes - .getValue(OBJECT_NAME_ATTRIBUTE_NAME); - if (OptionHelper.isEmpty(objectNameAttributeVal)) { - objectNameAsStr = MBeanUtil.getObjectNameFor(contextName, - JMXConfigurator.class); - } else { - objectNameAsStr = objectNameAttributeVal; - } + String objectNameAsStr; + String objectNameAttributeVal = attributes.getValue(OBJECT_NAME_ATTRIBUTE_NAME); + if (OptionHelper.isEmpty(objectNameAttributeVal)) { + objectNameAsStr = MBeanUtil.getObjectNameFor(contextName, JMXConfigurator.class); + } else { + objectNameAsStr = objectNameAttributeVal; + } - ObjectName objectName = MBeanUtil.string2ObjectName(context, this, - objectNameAsStr); - if (objectName == null) { - addError("Failed construct ObjectName for ["+objectNameAsStr+"]"); - return; - } - - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - if(!MBeanUtil.isRegistered(mbs, objectName)) { - // register only of the named JMXConfigurator has not been previously - // registered. Unregistering an MBean within invocation of itself - // caused jconsole to throw an NPE. (This occurs when the reload* method - // unregisters the - JMXConfigurator jmxConfigurator = new JMXConfigurator((LoggerContext) context, mbs, - objectName); - try { - mbs.registerMBean(jmxConfigurator, objectName); - } catch (Exception e) { - addError("Failed to create mbean", e); - } - } + ObjectName objectName = MBeanUtil.string2ObjectName(context, this, objectNameAsStr); + if (objectName == null) { + addError("Failed construct ObjectName for [" + objectNameAsStr + "]"); + return; + } - } + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + if (!MBeanUtil.isRegistered(mbs, objectName)) { + // register only of the named JMXConfigurator has not been previously + // registered. Unregistering an MBean within invocation of itself + // caused jconsole to throw an NPE. (This occurs when the reload* method + // unregisters the + JMXConfigurator jmxConfigurator = new JMXConfigurator((LoggerContext) context, mbs, objectName); + try { + mbs.registerMBean(jmxConfigurator, objectName); + } catch (Exception e) { + addError("Failed to create mbean", e); + } + } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { + } + + @Override + public void end(InterpretationContext ec, String name) throws ActionException { - } + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LevelAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LevelAction.java index 2ede7ea8ce435664d5473680eb689fa2e36e3e58..b86f8e38ac6b60c77f6c4cb682d39a459bdc2007 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LevelAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LevelAction.java @@ -31,37 +31,37 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; */ public class LevelAction extends Action { - boolean inError = false; + boolean inError = false; - public void begin(InterpretationContext ec, String name, Attributes attributes) { - Object o = ec.peekObject(); + public void begin(InterpretationContext ec, String name, Attributes attributes) { + Object o = ec.peekObject(); - if (!(o instanceof Logger)) { - inError = true; - addError("For element , could not find a logger at the top of execution stack."); - return; - } + if (!(o instanceof Logger)) { + inError = true; + addError("For element , could not find a logger at the top of execution stack."); + return; + } - Logger l = (Logger) o; + Logger l = (Logger) o; - String loggerName = l.getName(); + String loggerName = l.getName(); - String levelStr = ec.subst(attributes.getValue(ActionConst.VALUE_ATTR)); - //addInfo("Encapsulating logger name is [" + loggerName - // + "], level value is [" + levelStr + "]."); + String levelStr = ec.subst(attributes.getValue(ActionConst.VALUE_ATTR)); + // addInfo("Encapsulating logger name is [" + loggerName + // + "], level value is [" + levelStr + "]."); - if (ActionConst.INHERITED.equalsIgnoreCase(levelStr) || ActionConst.NULL.equalsIgnoreCase(levelStr)) { - l.setLevel(null); - } else { - l.setLevel(Level.toLevel(levelStr, Level.DEBUG)); - } + if (ActionConst.INHERITED.equalsIgnoreCase(levelStr) || ActionConst.NULL.equalsIgnoreCase(levelStr)) { + l.setLevel(null); + } else { + l.setLevel(Level.toLevel(levelStr, Level.DEBUG)); + } - addInfo(loggerName + " level set to " + l.getLevel()); - } + addInfo(loggerName + " level set to " + l.getLevel()); + } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } - public void end(InterpretationContext ec, String e) { - } + public void end(InterpretationContext ec, String e) { + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerAction.java index a93e89581e4153c1eae33a4d44da300fa2880672..76873e38039d0a5b29f3db3cb7f1f1b37aca85de 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerAction.java @@ -29,67 +29,65 @@ import ch.qos.logback.core.util.OptionHelper; * @author Ceki Gulcu */ public class LoggerAction extends Action { - public static final String LEVEL_ATTRIBUTE = "level"; + public static final String LEVEL_ATTRIBUTE = "level"; - boolean inError = false; - Logger logger; - public void begin(InterpretationContext ec, String name, Attributes attributes) { - // Let us forget about previous errors (in this object) - inError = false; - logger = null; - - LoggerContext loggerContext = (LoggerContext) this.context; + boolean inError = false; + Logger logger; - String loggerName = ec.subst(attributes.getValue(NAME_ATTRIBUTE)); + public void begin(InterpretationContext ec, String name, Attributes attributes) { + // Let us forget about previous errors (in this object) + inError = false; + logger = null; - if (OptionHelper.isEmpty(loggerName)) { - inError = true; - String aroundLine = getLineColStr(ec); - String errorMsg = "No 'name' attribute in element " + name + ", around " +aroundLine; - addError(errorMsg); - return; - } + LoggerContext loggerContext = (LoggerContext) this.context; - logger = loggerContext.getLogger(loggerName); + String loggerName = ec.subst(attributes.getValue(NAME_ATTRIBUTE)); - String levelStr = ec.subst(attributes.getValue(LEVEL_ATTRIBUTE)); - - if (!OptionHelper.isEmpty(levelStr)) { - if (ActionConst.INHERITED.equalsIgnoreCase(levelStr) - || ActionConst.NULL.equalsIgnoreCase(levelStr)) { - addInfo("Setting level of logger [" + loggerName - + "] to null, i.e. INHERITED"); - logger.setLevel(null); - } else { - Level level = Level.toLevel(levelStr); - addInfo("Setting level of logger [" + loggerName + "] to " + level); - logger.setLevel(level); - } - } + if (OptionHelper.isEmpty(loggerName)) { + inError = true; + String aroundLine = getLineColStr(ec); + String errorMsg = "No 'name' attribute in element " + name + ", around " + aroundLine; + addError(errorMsg); + return; + } - String additivityStr = ec.subst(attributes.getValue(ActionConst.ADDITIVITY_ATTRIBUTE)); - if (!OptionHelper.isEmpty(additivityStr)) { - boolean additive = OptionHelper.toBoolean(additivityStr, true); - addInfo("Setting additivity of logger [" + loggerName + "] to " - + additive); - logger.setAdditive(additive); - } - ec.pushObject(logger); - } + logger = loggerContext.getLogger(loggerName); + + String levelStr = ec.subst(attributes.getValue(LEVEL_ATTRIBUTE)); - public void end(InterpretationContext ec, String e) { - if (inError) { - return; + if (!OptionHelper.isEmpty(levelStr)) { + if (ActionConst.INHERITED.equalsIgnoreCase(levelStr) || ActionConst.NULL.equalsIgnoreCase(levelStr)) { + addInfo("Setting level of logger [" + loggerName + "] to null, i.e. INHERITED"); + logger.setLevel(null); + } else { + Level level = Level.toLevel(levelStr); + addInfo("Setting level of logger [" + loggerName + "] to " + level); + logger.setLevel(level); + } + } + + String additivityStr = ec.subst(attributes.getValue(ActionConst.ADDITIVITY_ATTRIBUTE)); + if (!OptionHelper.isEmpty(additivityStr)) { + boolean additive = OptionHelper.toBoolean(additivityStr, true); + addInfo("Setting additivity of logger [" + loggerName + "] to " + additive); + logger.setAdditive(additive); + } + ec.pushObject(logger); } - Object o = ec.peekObject(); - if (o != logger) { - addWarn("The object on the top the of the stack is not "+logger+" pushed earlier"); - addWarn("It is: " + o); - } else { - ec.popObject(); + + public void end(InterpretationContext ec, String e) { + if (inError) { + return; + } + Object o = ec.peekObject(); + if (o != logger) { + addWarn("The object on the top the of the stack is not " + logger + " pushed earlier"); + addWarn("It is: " + o); + } else { + ec.popObject(); + } } - } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerContextListenerAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerContextListenerAction.java index 19eca3477dc2839bd3c605502c4e4041753dd0f7..691e8873fc3c038f1c382c478c66cf34584c7f76 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerContextListenerAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/LoggerContextListenerAction.java @@ -25,58 +25,54 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.OptionHelper; public class LoggerContextListenerAction extends Action { - boolean inError = false; - LoggerContextListener lcl; + boolean inError = false; + LoggerContextListener lcl; - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - inError = false; + inError = false; - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Mandatory \"" + CLASS_ATTRIBUTE - + "\" attribute not set for element"); - inError = true; - return; - } + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Mandatory \"" + CLASS_ATTRIBUTE + "\" attribute not set for element"); + inError = true; + return; + } - try { - lcl = (LoggerContextListener) OptionHelper.instantiateByClassName( - className, LoggerContextListener.class, context); + try { + lcl = (LoggerContextListener) OptionHelper.instantiateByClassName(className, LoggerContextListener.class, context); - if(lcl instanceof ContextAware) { - ((ContextAware) lcl).setContext(context); - } + if (lcl instanceof ContextAware) { + ((ContextAware) lcl).setContext(context); + } - ec.pushObject(lcl); - addInfo("Adding LoggerContextListener of type [" + className - + "] to the object stack"); + ec.pushObject(lcl); + addInfo("Adding LoggerContextListener of type [" + className + "] to the object stack"); - } catch (Exception oops) { - inError = true; - addError("Could not create LoggerContextListener of type " + className + "].", oops); + } catch (Exception oops) { + inError = true; + addError("Could not create LoggerContextListener of type " + className + "].", oops); + } } - } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - if (inError) { - return; - } - Object o = ec.peekObject(); + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + if (inError) { + return; + } + Object o = ec.peekObject(); - if (o != lcl) { - addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier."); - } else { - if (lcl instanceof LifeCycle) { - ((LifeCycle) lcl).start(); - addInfo("Starting LoggerContextListener"); - } - ((LoggerContext) context).addListener(lcl); - ec.popObject(); + if (o != lcl) { + addWarn("The object on the top the of the stack is not the LoggerContextListener pushed earlier."); + } else { + if (lcl instanceof LifeCycle) { + ((LifeCycle) lcl).start(); + addInfo("Starting LoggerContextListener"); + } + ((LoggerContext) context).addListener(lcl); + ec.popObject(); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ReceiverAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ReceiverAction.java index 97e048b388b2ba69fe569488c519cd1f382f2d67..3a5dfdec726cac546491d7308775ff2896c23f71 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ReceiverAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/ReceiverAction.java @@ -29,53 +29,48 @@ import ch.qos.logback.core.util.OptionHelper; */ public class ReceiverAction extends Action { - private ReceiverBase receiver; - private boolean inError; - - @Override - public void begin(InterpretationContext ic, String name, - Attributes attributes) throws ActionException { - - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Missing class name for receiver. Near [" + name - + "] line " + getLineNumber(ic)); - inError = true; - return; - } + private ReceiverBase receiver; + private boolean inError; - try { - addInfo("About to instantiate receiver of type [" + className + "]"); + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { - receiver = (ReceiverBase) OptionHelper.instantiateByClassName( - className, ReceiverBase.class, context); - receiver.setContext(context); - - ic.pushObject(receiver); - } - catch (Exception ex) { - inError = true; - addError("Could not create a receiver of type [" + className + "].", ex); - throw new ActionException(ex); + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Missing class name for receiver. Near [" + name + "] line " + getLineNumber(ic)); + inError = true; + return; + } + + try { + addInfo("About to instantiate receiver of type [" + className + "]"); + + receiver = (ReceiverBase) OptionHelper.instantiateByClassName(className, ReceiverBase.class, context); + receiver.setContext(context); + + ic.pushObject(receiver); + } catch (Exception ex) { + inError = true; + addError("Could not create a receiver of type [" + className + "].", ex); + throw new ActionException(ex); + } } - } - @Override - public void end(InterpretationContext ic, String name) - throws ActionException { - - if (inError) return; - - ic.getContext().register(receiver); - receiver.start(); - - Object o = ic.peekObject(); - if (o != receiver) { - addWarn("The object at the of the stack is not the remote " + - "pushed earlier."); - } else { - ic.popObject(); + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + + if (inError) + return; + + ic.getContext().register(receiver); + receiver.start(); + + Object o = ic.peekObject(); + if (o != receiver) { + addWarn("The object at the of the stack is not the remote " + "pushed earlier."); + } else { + ic.popObject(); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/RootLoggerAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/RootLoggerAction.java index 7f86c6a0096b7afee2fba7455f3098b82e340963..5c136292f04a94f956e93d41d49e52e9ff6e0c88 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/RootLoggerAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/joran/action/RootLoggerAction.java @@ -24,38 +24,38 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.OptionHelper; public class RootLoggerAction extends Action { - - Logger root; - boolean inError = false; - public void begin(InterpretationContext ec, String name, Attributes attributes) { - inError = false; + Logger root; + boolean inError = false; - LoggerContext loggerContext = (LoggerContext) this.context; - root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + public void begin(InterpretationContext ec, String name, Attributes attributes) { + inError = false; - String levelStr = ec.subst(attributes.getValue(ActionConst.LEVEL_ATTRIBUTE)); - if (!OptionHelper.isEmpty(levelStr)) { - Level level = Level.toLevel(levelStr); - addInfo("Setting level of ROOT logger to " + level); - root.setLevel(level); - } - ec.pushObject(root); - } + LoggerContext loggerContext = (LoggerContext) this.context; + root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - public void end(InterpretationContext ec, String name) { - if (inError) { - return; + String levelStr = ec.subst(attributes.getValue(ActionConst.LEVEL_ATTRIBUTE)); + if (!OptionHelper.isEmpty(levelStr)) { + Level level = Level.toLevel(levelStr); + addInfo("Setting level of ROOT logger to " + level); + root.setLevel(level); + } + ec.pushObject(root); } - Object o = ec.peekObject(); - if (o != root) { - addWarn("The object on the top the of the stack is not the root logger"); - addWarn("It is: " + o); - } else { - ec.popObject(); + + public void end(InterpretationContext ec, String name) { + if (inError) { + return; + } + Object o = ec.peekObject(); + if (o != root) { + addWarn("The object on the top the of the stack is not the root logger"); + addWarn("It is: " + o); + } else { + ec.popObject(); + } } - } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/jul/JULHelper.java b/logback-classic/src/main/java/ch/qos/logback/classic/jul/JULHelper.java index 7a9bc80f7439ed433b9b86214cb544d114fd0757..4b5fb7e52af5f4903df7c1dac4b51d9cdc67cb3d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/jul/JULHelper.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/jul/JULHelper.java @@ -18,59 +18,56 @@ import ch.qos.logback.classic.Logger; public class JULHelper { + static public final boolean isRegularNonRootLogger(java.util.logging.Logger julLogger) { + if (julLogger == null) + return false; + return !julLogger.getName().equals(""); + } - static public final boolean isRegularNonRootLogger(java.util.logging.Logger julLogger) { - if (julLogger == null) - return false; - return !julLogger.getName().equals(""); - } - - static public final boolean isRoot(java.util.logging.Logger julLogger) { - if (julLogger == null) - return false; - return julLogger.getName().equals(""); - } + static public final boolean isRoot(java.util.logging.Logger julLogger) { + if (julLogger == null) + return false; + return julLogger.getName().equals(""); + } - static public java.util.logging.Level asJULLevel(Level lbLevel) { - if (lbLevel == null) - throw new IllegalArgumentException("Unexpected level [null]"); + static public java.util.logging.Level asJULLevel(Level lbLevel) { + if (lbLevel == null) + throw new IllegalArgumentException("Unexpected level [null]"); - switch (lbLevel.levelInt) { - case Level.ALL_INT: - return java.util.logging.Level.ALL; - case Level.TRACE_INT: - return java.util.logging.Level.FINEST; - case Level.DEBUG_INT: - return java.util.logging.Level.FINE; - case Level.INFO_INT: - return java.util.logging.Level.INFO; - case Level.WARN_INT: - return java.util.logging.Level.WARNING; - case Level.ERROR_INT: - return java.util.logging.Level.SEVERE; - case Level.OFF_INT: - return java.util.logging.Level.OFF; - default: - throw new IllegalArgumentException("Unexpected level [" + lbLevel + "]"); + switch (lbLevel.levelInt) { + case Level.ALL_INT: + return java.util.logging.Level.ALL; + case Level.TRACE_INT: + return java.util.logging.Level.FINEST; + case Level.DEBUG_INT: + return java.util.logging.Level.FINE; + case Level.INFO_INT: + return java.util.logging.Level.INFO; + case Level.WARN_INT: + return java.util.logging.Level.WARNING; + case Level.ERROR_INT: + return java.util.logging.Level.SEVERE; + case Level.OFF_INT: + return java.util.logging.Level.OFF; + default: + throw new IllegalArgumentException("Unexpected level [" + lbLevel + "]"); + } } - } - static public String asJULLoggerName(String loggerName) { - if (Logger.ROOT_LOGGER_NAME.equals(loggerName)) - return ""; - else - return loggerName; - } + static public String asJULLoggerName(String loggerName) { + if (Logger.ROOT_LOGGER_NAME.equals(loggerName)) + return ""; + else + return loggerName; + } - static public java.util.logging.Logger asJULLogger(String loggerName) { - String julLoggerName = asJULLoggerName(loggerName); - return java.util.logging.Logger.getLogger(julLoggerName); - } + static public java.util.logging.Logger asJULLogger(String loggerName) { + String julLoggerName = asJULLoggerName(loggerName); + return java.util.logging.Logger.getLogger(julLoggerName); + } - static public java.util.logging.Logger asJULLogger(Logger logger) { - return asJULLogger(logger.getName()); - } + static public java.util.logging.Logger asJULLogger(Logger logger) { + return asJULLogger(logger.getName()); + } } - - diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/jul/LevelChangePropagator.java b/logback-classic/src/main/java/ch/qos/logback/classic/jul/LevelChangePropagator.java index d781de45a5cb304d3e0622f1058da6d6b9e2a5db..a73894ad789694769feefceedaacae10a108f5a9 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/jul/LevelChangePropagator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/jul/LevelChangePropagator.java @@ -26,85 +26,84 @@ import java.util.List; import java.util.Set; import java.util.logging.LogManager; - /** * Propagate level changes made to a logback logger into the equivalent logger in j.u.l. */ public class LevelChangePropagator extends ContextAwareBase implements LoggerContextListener, LifeCycle { - private Set julLoggerSet = new HashSet(); - boolean isStarted = false; - boolean resetJUL = false; - - public void setResetJUL(boolean resetJUL) { - this.resetJUL = resetJUL; - } - - public boolean isResetResistant() { - return false; - } - - public void onStart(LoggerContext context) { - } - - public void onReset(LoggerContext context) { - } - - public void onStop(LoggerContext context) { - } - - public void onLevelChange(Logger logger, Level level) { - propagate(logger, level); - } - - private void propagate(Logger logger, Level level) { - addInfo("Propagating " + level + " level on " + logger + " onto the JUL framework"); - java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); - // prevent garbage collection of jul loggers whose level we set - // see also http://jira.qos.ch/browse/LBCLASSIC-256 - julLoggerSet.add(julLogger); - java.util.logging.Level julLevel = JULHelper.asJULLevel(level); - julLogger.setLevel(julLevel); - } - - public void resetJULLevels() { - LogManager lm = LogManager.getLogManager(); - - Enumeration e = lm.getLoggerNames(); - while (e.hasMoreElements()) { - String loggerName = e.nextElement(); - java.util.logging.Logger julLogger = lm.getLogger(loggerName); - if (JULHelper.isRegularNonRootLogger(julLogger) && julLogger.getLevel() != null) { - addInfo("Setting level of jul logger [" + loggerName + "] to null"); - julLogger.setLevel(null); - } + private Set julLoggerSet = new HashSet(); + boolean isStarted = false; + boolean resetJUL = false; + + public void setResetJUL(boolean resetJUL) { + this.resetJUL = resetJUL; + } + + public boolean isResetResistant() { + return false; + } + + public void onStart(LoggerContext context) { } - } - - private void propagateExistingLoggerLevels() { - LoggerContext loggerContext = (LoggerContext) context; - List loggerList = loggerContext.getLoggerList(); - for (Logger l : loggerList) { - if (l.getLevel() != null) { - propagate(l, l.getLevel()); - } + + public void onReset(LoggerContext context) { } - } - public void start() { - if (resetJUL) { - resetJULLevels(); + public void onStop(LoggerContext context) { } - propagateExistingLoggerLevels(); - isStarted = true; - } + public void onLevelChange(Logger logger, Level level) { + propagate(logger, level); + } - public void stop() { - isStarted = false; - } + private void propagate(Logger logger, Level level) { + addInfo("Propagating " + level + " level on " + logger + " onto the JUL framework"); + java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); + // prevent garbage collection of jul loggers whose level we set + // see also http://jira.qos.ch/browse/LBCLASSIC-256 + julLoggerSet.add(julLogger); + java.util.logging.Level julLevel = JULHelper.asJULLevel(level); + julLogger.setLevel(julLevel); + } - public boolean isStarted() { - return isStarted; - } + public void resetJULLevels() { + LogManager lm = LogManager.getLogManager(); + + Enumeration e = lm.getLoggerNames(); + while (e.hasMoreElements()) { + String loggerName = e.nextElement(); + java.util.logging.Logger julLogger = lm.getLogger(loggerName); + if (JULHelper.isRegularNonRootLogger(julLogger) && julLogger.getLevel() != null) { + addInfo("Setting level of jul logger [" + loggerName + "] to null"); + julLogger.setLevel(null); + } + } + } + + private void propagateExistingLoggerLevels() { + LoggerContext loggerContext = (LoggerContext) context; + List loggerList = loggerContext.getLoggerList(); + for (Logger l : loggerList) { + if (l.getLevel() != null) { + propagate(l, l.getLevel()); + } + } + } + + public void start() { + if (resetJUL) { + resetJULLevels(); + } + propagateExistingLoggerLevels(); + + isStarted = true; + } + + public void stop() { + isStarted = false; + } + + public boolean isStarted() { + return isStarted; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/log4j/XMLLayout.java b/logback-classic/src/main/java/ch/qos/logback/classic/log4j/XMLLayout.java index c345722f92887f341fd6d63ed64a9d0e2a1a9afe..ee640eeb6e59c903460aa7da179aa1213ae07fa4 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/log4j/XMLLayout.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/log4j/XMLLayout.java @@ -37,151 +37,149 @@ import ch.qos.logback.core.helpers.Transform; */ public class XMLLayout extends LayoutBase { - private final int DEFAULT_SIZE = 256; - private final int UPPER_LIMIT = 2048; - - private StringBuilder buf = new StringBuilder(DEFAULT_SIZE); - private boolean locationInfo = false; - private boolean properties = false; - - @Override - public void start() { - super.start(); - } - - /** - * The LocationInfo option takes a boolean value. By default, it is - * set to false which means there will be no location information output by - * this layout. If the the option is set to true, then the file name and line - * number of the statement at the origin of the log statement will be output. - * - *

If you are embedding this layout within an {@link - * org.apache.log4j.net.SMTPAppender} then make sure to set the - * LocationInfo option of that appender as well. - */ - public void setLocationInfo(boolean flag) { - locationInfo = flag; - } - - /** - * Returns the current value of the LocationInfo option. - */ - public boolean getLocationInfo() { - return locationInfo; - } - - /** - * Sets whether MDC key-value pairs should be output, default false. - * - * @param flag - * new value. - * @since 1.2.15 - */ - public void setProperties(final boolean flag) { - properties = flag; - } - - /** - * Gets whether MDC key-value pairs should be output. - * - * @return true if MDC key-value pairs are output. - * @since 1.2.15 - */ - public boolean getProperties() { - return properties; - } - - /** - * Formats a {@link ILoggingEvent} in conformity with the log4j.dtd. - */ - public String doLayout(ILoggingEvent event) { - - // Reset working buffer. If the buffer is too large, then we need a new - // one in order to avoid the penalty of creating a large array. - if (buf.capacity() > UPPER_LIMIT) { - buf = new StringBuilder(DEFAULT_SIZE); - } else { - buf.setLength(0); + private final int DEFAULT_SIZE = 256; + private final int UPPER_LIMIT = 2048; + + private StringBuilder buf = new StringBuilder(DEFAULT_SIZE); + private boolean locationInfo = false; + private boolean properties = false; + + @Override + public void start() { + super.start(); } - // We yield to the \r\n heresy. - - buf.append("\r\n"); - - buf.append(" "); - buf.append(Transform.escapeTags(event.getFormattedMessage())); - buf.append("\r\n"); - - // logback does not support NDC - // String ndc = event.getNDC(); - - - IThrowableProxy tp = event.getThrowableProxy(); - if (tp != null) { - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - buf.append(" \r\n"); + /** + * The LocationInfo option takes a boolean value. By default, it is + * set to false which means there will be no location information output by + * this layout. If the the option is set to true, then the file name and line + * number of the statement at the origin of the log statement will be output. + * + *

If you are embedding this layout within an {@link + * org.apache.log4j.net.SMTPAppender} then make sure to set the + * LocationInfo option of that appender as well. + */ + public void setLocationInfo(boolean flag) { + locationInfo = flag; } - if (locationInfo) { - StackTraceElement[] callerDataArray = event.getCallerData(); - if (callerDataArray != null && callerDataArray.length > 0) { - StackTraceElement immediateCallerData = callerDataArray[0]; - buf.append(" \r\n"); - } + /** + * Returns the current value of the LocationInfo option. + */ + public boolean getLocationInfo() { + return locationInfo; } - /* - * - * + /** + * Sets whether MDC key-value pairs should be output, default false. + * + * @param flag + * new value. + * @since 1.2.15 */ - if (this.getProperties()) { - Map propertyMap = event.getMDCPropertyMap(); - - if ((propertyMap != null) && (propertyMap.size() != 0)) { - Set> entrySet = propertyMap.entrySet(); - buf.append(" "); - for (Entry entry : entrySet) { - buf.append("\r\n "); - } - buf.append("\r\n "); - } + public void setProperties(final boolean flag) { + properties = flag; } - buf.append("\r\n\r\n\r\n"); + /** + * Gets whether MDC key-value pairs should be output. + * + * @return true if MDC key-value pairs are output. + * @since 1.2.15 + */ + public boolean getProperties() { + return properties; + } + + /** + * Formats a {@link ILoggingEvent} in conformity with the log4j.dtd. + */ + public String doLayout(ILoggingEvent event) { + + // Reset working buffer. If the buffer is too large, then we need a new + // one in order to avoid the penalty of creating a large array. + if (buf.capacity() > UPPER_LIMIT) { + buf = new StringBuilder(DEFAULT_SIZE); + } else { + buf.setLength(0); + } + + // We yield to the \r\n heresy. + + buf.append("\r\n"); + + buf.append(" "); + buf.append(Transform.escapeTags(event.getFormattedMessage())); + buf.append("\r\n"); + + // logback does not support NDC + // String ndc = event.getNDC(); + + IThrowableProxy tp = event.getThrowableProxy(); + if (tp != null) { + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + buf.append(" \r\n"); + } - return buf.toString(); - } + if (locationInfo) { + StackTraceElement[] callerDataArray = event.getCallerData(); + if (callerDataArray != null && callerDataArray.length > 0) { + StackTraceElement immediateCallerData = callerDataArray[0]; + buf.append(" \r\n"); + } + } - @Override - public String getContentType() { - return "text/xml"; - } + /* + * + */ + if (this.getProperties()) { + Map propertyMap = event.getMDCPropertyMap(); + + if ((propertyMap != null) && (propertyMap.size() != 0)) { + Set> entrySet = propertyMap.entrySet(); + buf.append(" "); + for (Entry entry : entrySet) { + buf.append("\r\n "); + } + buf.append("\r\n "); + } + } + + buf.append("\r\n\r\n\r\n"); + + return buf.toString(); + } + + @Override + public String getContentType() { + return "text/xml"; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueAppender.java index 4e4601906789712f36d5f049a0ae8ca1fa136b73..723f646d4e0f205d900f8b361817d0484b3f4dd6 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueAppender.java @@ -41,171 +41,166 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class JMSQueueAppender extends JMSAppenderBase { - static int SUCCESSIVE_FAILURE_LIMIT = 3; - - String queueBindingName; - String qcfBindingName; - QueueConnection queueConnection; - QueueSession queueSession; - QueueSender queueSender; - - int successiveFailureCount = 0; - - private PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - - /** - * The QueueConnectionFactoryBindingName option takes a string value. - * Its value will be used to lookup the appropriate - * QueueConnectionFactory from the JNDI context. - */ - public void setQueueConnectionFactoryBindingName(String qcfBindingName) { - this.qcfBindingName = qcfBindingName; - } - - /** - * Returns the value of the QueueConnectionFactoryBindingName option. - */ - public String getQueueConnectionFactoryBindingName() { - return qcfBindingName; - } - - /** - * The QueueBindingName option takes a string value. Its value will be - * used to lookup the appropriate Queue from the JNDI context. - */ - public void setQueueBindingName(String queueBindingName) { - this.queueBindingName = queueBindingName; - } - - /** - * Returns the value of the QueueBindingName option. - */ - public String getQueueBindingName() { - return queueBindingName; - } - - /** - * Options are activated and become effective only after calling this method. - */ - public void start() { - QueueConnectionFactory queueConnectionFactory; - - try { - Context jndi = buildJNDIContext(); - - // addInfo("Looking up [" + qcfBindingName + "]"); - queueConnectionFactory = (QueueConnectionFactory) lookup(jndi, - qcfBindingName); - // addInfo("About to create QueueConnection."); - if (userName != null) { - this.queueConnection = queueConnectionFactory.createQueueConnection( - userName, password); - } else { - this.queueConnection = queueConnectionFactory.createQueueConnection(); - } - - // addInfo( - // "Creating QueueSession, non-transactional, " - // + "in AUTO_ACKNOWLEDGE mode."); - this.queueSession = queueConnection.createQueueSession(false, - Session.AUTO_ACKNOWLEDGE); - - // addInfo("Looking up queue name [" + queueBindingName + "]."); - Queue queue = (Queue) lookup(jndi, queueBindingName); - - // addInfo("Creating QueueSender."); - this.queueSender = queueSession.createSender(queue); - - // addInfo("Starting QueueConnection."); - queueConnection.start(); - - jndi.close(); - } catch (Exception e) { - addError("Error while activating options for appender named [" + name - + "].", e); + static int SUCCESSIVE_FAILURE_LIMIT = 3; + + String queueBindingName; + String qcfBindingName; + QueueConnection queueConnection; + QueueSession queueSession; + QueueSender queueSender; + + int successiveFailureCount = 0; + + private PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + /** + * The QueueConnectionFactoryBindingName option takes a string value. + * Its value will be used to lookup the appropriate + * QueueConnectionFactory from the JNDI context. + */ + public void setQueueConnectionFactoryBindingName(String qcfBindingName) { + this.qcfBindingName = qcfBindingName; + } + + /** + * Returns the value of the QueueConnectionFactoryBindingName option. + */ + public String getQueueConnectionFactoryBindingName() { + return qcfBindingName; } - if (this.queueConnection != null && this.queueSession != null - && this.queueSender != null) { - super.start(); + /** + * The QueueBindingName option takes a string value. Its value will be + * used to lookup the appropriate Queue from the JNDI context. + */ + public void setQueueBindingName(String queueBindingName) { + this.queueBindingName = queueBindingName; } - } - - /** - * Close this JMSAppender. Closing releases all resources used by the - * appender. A closed appender cannot be re-opened. - */ - public synchronized void stop() { - // The synchronized modifier avoids concurrent append and close operations - if (!this.started) { - return; + + /** + * Returns the value of the QueueBindingName option. + */ + public String getQueueBindingName() { + return queueBindingName; + } + + /** + * Options are activated and become effective only after calling this method. + */ + public void start() { + QueueConnectionFactory queueConnectionFactory; + + try { + Context jndi = buildJNDIContext(); + + // addInfo("Looking up [" + qcfBindingName + "]"); + queueConnectionFactory = (QueueConnectionFactory) lookup(jndi, qcfBindingName); + // addInfo("About to create QueueConnection."); + if (userName != null) { + this.queueConnection = queueConnectionFactory.createQueueConnection(userName, password); + } else { + this.queueConnection = queueConnectionFactory.createQueueConnection(); + } + + // addInfo( + // "Creating QueueSession, non-transactional, " + // + "in AUTO_ACKNOWLEDGE mode."); + this.queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + + // addInfo("Looking up queue name [" + queueBindingName + "]."); + Queue queue = (Queue) lookup(jndi, queueBindingName); + + // addInfo("Creating QueueSender."); + this.queueSender = queueSession.createSender(queue); + + // addInfo("Starting QueueConnection."); + queueConnection.start(); + + jndi.close(); + } catch (Exception e) { + addError("Error while activating options for appender named [" + name + "].", e); + } + + if (this.queueConnection != null && this.queueSession != null && this.queueSender != null) { + super.start(); + } } - this.started = false; - - try { - if (queueSession != null) { - queueSession.close(); - } - if (queueConnection != null) { - queueConnection.close(); - } - } catch (Exception e) { - addError("Error while closing JMSAppender [" + name + "].", e); + /** + * Close this JMSAppender. Closing releases all resources used by the + * appender. A closed appender cannot be re-opened. + */ + public synchronized void stop() { + // The synchronized modifier avoids concurrent append and close operations + if (!this.started) { + return; + } + + this.started = false; + + try { + if (queueSession != null) { + queueSession.close(); + } + if (queueConnection != null) { + queueConnection.close(); + } + } catch (Exception e) { + addError("Error while closing JMSAppender [" + name + "].", e); + } + + // Help garbage collection + queueSender = null; + queueSession = null; + queueConnection = null; } - // Help garbage collection - queueSender = null; - queueSession = null; - queueConnection = null; - } - - /** - * This method called by {@link AppenderBase#doAppend} method to do most - * of the real appending work. - */ - public void append(ILoggingEvent event) { - if (!isStarted()) { - return; + /** + * This method called by {@link AppenderBase#doAppend} method to do most + * of the real appending work. + */ + public void append(ILoggingEvent event) { + if (!isStarted()) { + return; + } + + try { + ObjectMessage msg = queueSession.createObjectMessage(); + Serializable so = pst.transform(event); + msg.setObject(so); + queueSender.send(msg); + successiveFailureCount = 0; + } catch (Exception e) { + successiveFailureCount++; + if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { + stop(); + } + addError("Could not send message in JMSQueueAppender [" + name + "].", e); + + } } - try { - ObjectMessage msg = queueSession.createObjectMessage(); - Serializable so = pst.transform(event); - msg.setObject(so); - queueSender.send(msg); - successiveFailureCount = 0; - } catch (Exception e) { - successiveFailureCount++; - if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { - stop(); - } - addError("Could not send message in JMSQueueAppender [" + name + "].", e); + /** + * Returns the QueueConnection used for this appender. Only valid after + * start() method has been invoked. + */ + protected QueueConnection getQueueConnection() { + return queueConnection; + } + + /** + * Returns the QueueSession used for this appender. Only valid after start() + * method has been invoked. + */ + protected QueueSession getQueueSession() { + return queueSession; + } + /** + * Returns the QueueSender used for this appender. Only valid after start() + * method has been invoked. + */ + protected QueueSender getQueueSender() { + return queueSender; } - } - - /** - * Returns the QueueConnection used for this appender. Only valid after - * start() method has been invoked. - */ - protected QueueConnection getQueueConnection() { - return queueConnection; - } - - /** - * Returns the QueueSession used for this appender. Only valid after start() - * method has been invoked. - */ - protected QueueSession getQueueSession() { - return queueSession; - } - - /** - * Returns the QueueSender used for this appender. Only valid after start() - * method has been invoked. - */ - protected QueueSender getQueueSender() { - return queueSender; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueSink.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueSink.java index 8811cbda89cecc62ddecb527c5dd7012ffa9f53a..d1f3854dd276327f58f25ae5c9e93c4c7bbe2762 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueSink.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSQueueSink.java @@ -45,108 +45,97 @@ import ch.qos.logback.classic.util.ContextInitializer; */ public class JMSQueueSink implements javax.jms.MessageListener { - private Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicSink.class); - - static public void main(String[] args) throws Exception { - if (args.length < 2) { - usage("Wrong number of arguments."); + private Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicSink.class); + + static public void main(String[] args) throws Exception { + if (args.length < 2) { + usage("Wrong number of arguments."); + } + + String qcfBindingName = args[0]; + String queueBindingName = args[1]; + String username = null; + String password = null; + if (args.length == 4) { + username = args[2]; + password = args[3]; + } + + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + new ContextInitializer(loggerContext).autoConfig(); + + new JMSQueueSink(qcfBindingName, queueBindingName, username, password); + + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + // Loop until the word "exit" is typed + System.out.println("Type \"exit\" to quit JMSQueueSink."); + while (true) { + String s = stdin.readLine(); + if (s.equalsIgnoreCase("exit")) { + System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); + return; + } + } } - String qcfBindingName = args[0]; - String queueBindingName = args[1]; - String username = null; - String password = null; - if (args.length == 4) { - username = args[2]; - password = args[3]; - } + public JMSQueueSink(String qcfBindingName, String queueBindingName, String username, String password) { + + try { + Properties env = new Properties(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + env.put(Context.PROVIDER_URL, "tcp://localhost:61616"); + Context ctx = new InitialContext(env); + QueueConnectionFactory queueConnectionFactory; + queueConnectionFactory = (QueueConnectionFactory) lookup(ctx, qcfBindingName); + System.out.println("Queue Cnx Factory found"); + Queue queue = (Queue) ctx.lookup(queueBindingName); + System.out.println("Queue found: " + queue.getQueueName()); + + QueueConnection queueConnection = queueConnectionFactory.createQueueConnection(username, password); + System.out.println("Queue Connection created"); + + QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); + + MessageConsumer queueConsumer = queueSession.createConsumer(queue); - LoggerContext loggerContext = (LoggerContext) LoggerFactory - .getILoggerFactory(); - new ContextInitializer(loggerContext).autoConfig(); - - new JMSQueueSink(qcfBindingName, queueBindingName, username, password); - - BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); - // Loop until the word "exit" is typed - System.out.println("Type \"exit\" to quit JMSQueueSink."); - while (true) { - String s = stdin.readLine(); - if (s.equalsIgnoreCase("exit")) { - System.out.println("Exiting. Kill the application if it does not exit " - + "due to daemon threads."); - return; - } + queueConsumer.setMessageListener(this); + + queueConnection.start(); + System.out.println("Queue Connection started"); + + } catch (Exception e) { + logger.error("Could not read JMS message.", e); + } } - } - - public JMSQueueSink(String qcfBindingName, String queueBindingName, - String username, String password) { - - try { - Properties env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - env.put(Context.PROVIDER_URL, "tcp://localhost:61616"); - Context ctx = new InitialContext(env); - QueueConnectionFactory queueConnectionFactory; - queueConnectionFactory = (QueueConnectionFactory) lookup(ctx, - qcfBindingName); - System.out.println("Queue Cnx Factory found"); - Queue queue = (Queue) ctx.lookup(queueBindingName); - System.out.println("Queue found: " + queue.getQueueName()); - - QueueConnection queueConnection = queueConnectionFactory - .createQueueConnection(username, password); - System.out.println("Queue Connection created"); - - QueueSession queueSession = queueConnection.createQueueSession(false, - Session.AUTO_ACKNOWLEDGE); - - MessageConsumer queueConsumer = queueSession.createConsumer(queue); - - queueConsumer.setMessageListener(this); - - queueConnection.start(); - System.out.println("Queue Connection started"); - - } catch (Exception e) { - logger.error("Could not read JMS message.", e); + + public void onMessage(javax.jms.Message message) { + ILoggingEvent event; + try { + if (message instanceof ObjectMessage) { + ObjectMessage objectMessage = (ObjectMessage) message; + event = (ILoggingEvent) objectMessage.getObject(); + Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerName()); + log.callAppenders(event); + } else { + logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage."); + } + } catch (JMSException jmse) { + logger.error("Exception thrown while processing incoming message.", jmse); + } } - } - - public void onMessage(javax.jms.Message message) { - ILoggingEvent event; - try { - if (message instanceof ObjectMessage) { - ObjectMessage objectMessage = (ObjectMessage) message; - event = (ILoggingEvent) objectMessage.getObject(); - Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerName()); - log.callAppenders(event); - } else { - logger.warn("Received message is of type " + message.getJMSType() - + ", was expecting ObjectMessage."); - } - } catch (JMSException jmse) { - logger.error("Exception thrown while processing incoming message.", jmse); + + protected Object lookup(Context ctx, String name) throws NamingException { + try { + return ctx.lookup(name); + } catch (NameNotFoundException e) { + logger.error("Could not find name [" + name + "]."); + throw e; + } } - } - - protected Object lookup(Context ctx, String name) - throws NamingException { - try { - return ctx.lookup(name); - } catch (NameNotFoundException e) { - logger.error("Could not find name [" + name + "]."); - throw e; + + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + JMSQueueSink.class.getName() + " QueueConnectionFactoryBindingName QueueBindingName Username Password"); + System.exit(1); } - } - - static void usage(String msg) { - System.err.println(msg); - System.err - .println("Usage: java " - + JMSQueueSink.class.getName() - + " QueueConnectionFactoryBindingName QueueBindingName Username Password"); - System.exit(1); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicAppender.java index 36f5d1a841732e13b454bd6b06de9aada45a82bf..65ceb186c90b524d31c9dbf9b437237fe264bb8b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicAppender.java @@ -41,171 +41,165 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class JMSTopicAppender extends JMSAppenderBase { - static int SUCCESSIVE_FAILURE_LIMIT = 3; - - String topicBindingName; - String tcfBindingName; - TopicConnection topicConnection; - TopicSession topicSession; - TopicPublisher topicPublisher; - - int successiveFailureCount = 0; - - private PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - - /** - * The TopicConnectionFactoryBindingName option takes a string value. - * Its value will be used to lookup the appropriate - * TopicConnectionFactory from the JNDI context. - */ - public void setTopicConnectionFactoryBindingName(String tcfBindingName) { - this.tcfBindingName = tcfBindingName; - } - - /** - * Returns the value of the TopicConnectionFactoryBindingName option. - */ - public String getTopicConnectionFactoryBindingName() { - return tcfBindingName; - } - - /** - * The TopicBindingName option takes a string value. Its value will be - * used to lookup the appropriate Topic from the JNDI context. - */ - public void setTopicBindingName(String topicBindingName) { - this.topicBindingName = topicBindingName; - } - - /** - * Returns the value of the TopicBindingName option. - */ - public String getTopicBindingName() { - return topicBindingName; - } - - /** - * Options are activated and become effective only after calling this method. - */ - public void start() { - TopicConnectionFactory topicConnectionFactory; - - try { - Context jndi = buildJNDIContext(); - - // addInfo("Looking up [" + tcfBindingName + "]"); - topicConnectionFactory = (TopicConnectionFactory) lookup(jndi, - tcfBindingName); - // addInfo("About to create TopicConnection."); - if (userName != null) { - this.topicConnection = topicConnectionFactory.createTopicConnection( - userName, password); - } else { - this.topicConnection = topicConnectionFactory.createTopicConnection(); - } - - // addInfo( - // "Creating TopicSession, non-transactional, " - // + "in AUTO_ACKNOWLEDGE mode."); - this.topicSession = topicConnection.createTopicSession(false, - Session.AUTO_ACKNOWLEDGE); - - // addInfo("Looking up topic name [" + topicBindingName + "]."); - Topic topic = (Topic) lookup(jndi, topicBindingName); - - // addInfo("Creating TopicPublisher."); - this.topicPublisher = topicSession.createPublisher(topic); - - // addInfo("Starting TopicConnection."); - topicConnection.start(); - - jndi.close(); - } catch (Exception e) { - addError("Error while activating options for appender named [" + name - + "].", e); + static int SUCCESSIVE_FAILURE_LIMIT = 3; + + String topicBindingName; + String tcfBindingName; + TopicConnection topicConnection; + TopicSession topicSession; + TopicPublisher topicPublisher; + + int successiveFailureCount = 0; + + private PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + /** + * The TopicConnectionFactoryBindingName option takes a string value. + * Its value will be used to lookup the appropriate + * TopicConnectionFactory from the JNDI context. + */ + public void setTopicConnectionFactoryBindingName(String tcfBindingName) { + this.tcfBindingName = tcfBindingName; } - if (this.topicConnection != null && this.topicSession != null - && this.topicPublisher != null) { - super.start(); + /** + * Returns the value of the TopicConnectionFactoryBindingName option. + */ + public String getTopicConnectionFactoryBindingName() { + return tcfBindingName; } - } - - /** - * Close this JMSAppender. Closing releases all resources used by the - * appender. A closed appender cannot be re-opened. - */ - public synchronized void stop() { - // The synchronized modifier avoids concurrent append and close operations - if (!this.started) { - return; + + /** + * The TopicBindingName option takes a string value. Its value will be + * used to lookup the appropriate Topic from the JNDI context. + */ + public void setTopicBindingName(String topicBindingName) { + this.topicBindingName = topicBindingName; } - this.started = false; - - try { - if (topicSession != null) { - topicSession.close(); - } - if (topicConnection != null) { - topicConnection.close(); - } - } catch (Exception e) { - addError("Error while closing JMSAppender [" + name + "].", e); + /** + * Returns the value of the TopicBindingName option. + */ + public String getTopicBindingName() { + return topicBindingName; } - // Help garbage collection - topicPublisher = null; - topicSession = null; - topicConnection = null; - } + /** + * Options are activated and become effective only after calling this method. + */ + public void start() { + TopicConnectionFactory topicConnectionFactory; + + try { + Context jndi = buildJNDIContext(); + + // addInfo("Looking up [" + tcfBindingName + "]"); + topicConnectionFactory = (TopicConnectionFactory) lookup(jndi, tcfBindingName); + // addInfo("About to create TopicConnection."); + if (userName != null) { + this.topicConnection = topicConnectionFactory.createTopicConnection(userName, password); + } else { + this.topicConnection = topicConnectionFactory.createTopicConnection(); + } + + // addInfo( + // "Creating TopicSession, non-transactional, " + // + "in AUTO_ACKNOWLEDGE mode."); + this.topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + + // addInfo("Looking up topic name [" + topicBindingName + "]."); + Topic topic = (Topic) lookup(jndi, topicBindingName); + + // addInfo("Creating TopicPublisher."); + this.topicPublisher = topicSession.createPublisher(topic); + + // addInfo("Starting TopicConnection."); + topicConnection.start(); + + jndi.close(); + } catch (Exception e) { + addError("Error while activating options for appender named [" + name + "].", e); + } + + if (this.topicConnection != null && this.topicSession != null && this.topicPublisher != null) { + super.start(); + } + } + /** + * Close this JMSAppender. Closing releases all resources used by the + * appender. A closed appender cannot be re-opened. + */ + public synchronized void stop() { + // The synchronized modifier avoids concurrent append and close operations + if (!this.started) { + return; + } + + this.started = false; + + try { + if (topicSession != null) { + topicSession.close(); + } + if (topicConnection != null) { + topicConnection.close(); + } + } catch (Exception e) { + addError("Error while closing JMSAppender [" + name + "].", e); + } + + // Help garbage collection + topicPublisher = null; + topicSession = null; + topicConnection = null; + } + + /** + * This method called by {@link AppenderBase#doAppend} method to do most + * of the real appending work. + */ + public void append(ILoggingEvent event) { + if (!isStarted()) { + return; + } + + try { + ObjectMessage msg = topicSession.createObjectMessage(); + Serializable so = pst.transform(event); + msg.setObject(so); + topicPublisher.publish(msg); + successiveFailureCount = 0; + } catch (Exception e) { + successiveFailureCount++; + if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { + stop(); + } + addError("Could not publish message in JMSTopicAppender [" + name + "].", e); + } + } + + /** + * Returns the TopicConnection used for this appender. Only valid after + * start() method has been invoked. + */ + protected TopicConnection getTopicConnection() { + return topicConnection; + } - /** - * This method called by {@link AppenderBase#doAppend} method to do most - * of the real appending work. - */ - public void append(ILoggingEvent event) { - if (!isStarted()) { - return; + /** + * Returns the TopicSession used for this appender. Only valid after start() + * method has been invoked. + */ + protected TopicSession getTopicSession() { + return topicSession; } - try { - ObjectMessage msg = topicSession.createObjectMessage(); - Serializable so = pst.transform(event); - msg.setObject(so); - topicPublisher.publish(msg); - successiveFailureCount = 0; - } catch (Exception e) { - successiveFailureCount++; - if (successiveFailureCount > SUCCESSIVE_FAILURE_LIMIT) { - stop(); - } - addError("Could not publish message in JMSTopicAppender [" + name + "].", e); + /** + * Returns the TopicPublisher used for this appender. Only valid after start() + * method has been invoked. + */ + protected TopicPublisher getTopicPublisher() { + return topicPublisher; } - } - - /** - * Returns the TopicConnection used for this appender. Only valid after - * start() method has been invoked. - */ - protected TopicConnection getTopicConnection() { - return topicConnection; - } - - /** - * Returns the TopicSession used for this appender. Only valid after start() - * method has been invoked. - */ - protected TopicSession getTopicSession() { - return topicSession; - } - - /** - * Returns the TopicPublisher used for this appender. Only valid after start() - * method has been invoked. - */ - protected TopicPublisher getTopicPublisher() { - return topicPublisher; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicSink.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicSink.java index 1b3b4aa88949ad7ac0c2fd994e0960bf02256388..a7d4beed4b7e210814172b772ddf44a51a0bc762 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicSink.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/JMSTopicSink.java @@ -45,108 +45,97 @@ import ch.qos.logback.classic.util.ContextInitializer; */ public class JMSTopicSink implements javax.jms.MessageListener { - private Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicSink.class); - - static public void main(String[] args) throws Exception { - if (args.length < 2) { - usage("Wrong number of arguments."); + private Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicSink.class); + + static public void main(String[] args) throws Exception { + if (args.length < 2) { + usage("Wrong number of arguments."); + } + + String tcfBindingName = args[0]; + String topicBindingName = args[1]; + String username = null; + String password = null; + if (args.length == 4) { + username = args[2]; + password = args[3]; + } + + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + new ContextInitializer(loggerContext).autoConfig(); + + new JMSTopicSink(tcfBindingName, topicBindingName, username, password); + + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); + // Loop until the word "exit" is typed + System.out.println("Type \"exit\" to quit JMSTopicSink."); + while (true) { + String s = stdin.readLine(); + if (s.equalsIgnoreCase("exit")) { + System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); + return; + } + } } - String tcfBindingName = args[0]; - String topicBindingName = args[1]; - String username = null; - String password = null; - if (args.length == 4) { - username = args[2]; - password = args[3]; - } + public JMSTopicSink(String tcfBindingName, String topicBindingName, String username, String password) { + + try { + Properties env = new Properties(); + env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + env.put(Context.PROVIDER_URL, "tcp://localhost:61616"); + Context ctx = new InitialContext(env); + TopicConnectionFactory topicConnectionFactory; + topicConnectionFactory = (TopicConnectionFactory) lookup(ctx, tcfBindingName); + System.out.println("Topic Cnx Factory found"); + Topic topic = (Topic) ctx.lookup(topicBindingName); + System.out.println("Topic found: " + topic.getTopicName()); + + TopicConnection topicConnection = topicConnectionFactory.createTopicConnection(username, password); + System.out.println("Topic Connection created"); + + TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); + + TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); - LoggerContext loggerContext = (LoggerContext) LoggerFactory - .getILoggerFactory(); - new ContextInitializer(loggerContext).autoConfig(); - - new JMSTopicSink(tcfBindingName, topicBindingName, username, password); - - BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); - // Loop until the word "exit" is typed - System.out.println("Type \"exit\" to quit JMSTopicSink."); - while (true) { - String s = stdin.readLine(); - if (s.equalsIgnoreCase("exit")) { - System.out.println("Exiting. Kill the application if it does not exit " - + "due to daemon threads."); - return; - } + topicSubscriber.setMessageListener(this); + + topicConnection.start(); + System.out.println("Topic Connection started"); + + } catch (Exception e) { + logger.error("Could not read JMS message.", e); + } } - } - - public JMSTopicSink(String tcfBindingName, String topicBindingName, - String username, String password) { - - try { - Properties env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - env.put(Context.PROVIDER_URL, "tcp://localhost:61616"); - Context ctx = new InitialContext(env); - TopicConnectionFactory topicConnectionFactory; - topicConnectionFactory = (TopicConnectionFactory) lookup(ctx, - tcfBindingName); - System.out.println("Topic Cnx Factory found"); - Topic topic = (Topic) ctx.lookup(topicBindingName); - System.out.println("Topic found: " + topic.getTopicName()); - - TopicConnection topicConnection = topicConnectionFactory - .createTopicConnection(username, password); - System.out.println("Topic Connection created"); - - TopicSession topicSession = topicConnection.createTopicSession(false, - Session.AUTO_ACKNOWLEDGE); - - TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic); - - topicSubscriber.setMessageListener(this); - - topicConnection.start(); - System.out.println("Topic Connection started"); - - } catch (Exception e) { - logger.error("Could not read JMS message.", e); + + public void onMessage(javax.jms.Message message) { + ILoggingEvent event; + try { + if (message instanceof ObjectMessage) { + ObjectMessage objectMessage = (ObjectMessage) message; + event = (ILoggingEvent) objectMessage.getObject(); + Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerName()); + log.callAppenders(event); + } else { + logger.warn("Received message is of type " + message.getJMSType() + ", was expecting ObjectMessage."); + } + } catch (JMSException jmse) { + logger.error("Exception thrown while processing incoming message.", jmse); + } } - } - - public void onMessage(javax.jms.Message message) { - ILoggingEvent event; - try { - if (message instanceof ObjectMessage) { - ObjectMessage objectMessage = (ObjectMessage) message; - event = (ILoggingEvent) objectMessage.getObject(); - Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerName()); - log.callAppenders(event); - } else { - logger.warn("Received message is of type " + message.getJMSType() - + ", was expecting ObjectMessage."); - } - } catch (JMSException jmse) { - logger.error("Exception thrown while processing incoming message.", jmse); + + protected Object lookup(Context ctx, String name) throws NamingException { + try { + return ctx.lookup(name); + } catch (NameNotFoundException e) { + logger.error("Could not find name [" + name + "]."); + throw e; + } } - } - - protected Object lookup(Context ctx, String name) - throws NamingException { - try { - return ctx.lookup(name); - } catch (NameNotFoundException e) { - logger.error("Could not find name [" + name + "]."); - throw e; + + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + JMSTopicSink.class.getName() + " TopicConnectionFactoryBindingName TopicBindingName Username Password"); + System.exit(1); } - } - - static void usage(String msg) { - System.err.println(msg); - System.err - .println("Usage: java " - + JMSTopicSink.class.getName() - + " TopicConnectionFactoryBindingName TopicBindingName Username Password"); - System.exit(1); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/LoggingEventPreSerializationTransformer.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/LoggingEventPreSerializationTransformer.java index cd8c3be1c93ff4d83520fd87709e05c56aa27f57..5db326d78577506015ec42dd438342b50397288d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/LoggingEventPreSerializationTransformer.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/LoggingEventPreSerializationTransformer.java @@ -20,20 +20,19 @@ import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.classic.spi.LoggingEventVO; import ch.qos.logback.core.spi.PreSerializationTransformer; -public class LoggingEventPreSerializationTransformer implements - PreSerializationTransformer { +public class LoggingEventPreSerializationTransformer implements PreSerializationTransformer { - public Serializable transform(ILoggingEvent event) { - if(event == null) { - return null; + public Serializable transform(ILoggingEvent event) { + if (event == null) { + return null; + } + if (event instanceof LoggingEvent) { + return LoggingEventVO.build(event); + } else if (event instanceof LoggingEventVO) { + return (LoggingEventVO) event; + } else { + throw new IllegalArgumentException("Unsupported type " + event.getClass().getName()); + } } - if (event instanceof LoggingEvent) { - return LoggingEventVO.build(event); - } else if (event instanceof LoggingEventVO) { - return (LoggingEventVO) event; - } else { - throw new IllegalArgumentException("Unsupported type "+event.getClass().getName()); - } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java index e21b1301a9ef1f6207e6eb90fb124662a6358074..24dd1bf6ac3eaf45cfe4c0edadf4b5dcc81a7d33 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/ReceiverBase.java @@ -22,66 +22,66 @@ import ch.qos.logback.core.spi.LifeCycle; * * @author Carl Harris */ -public abstract class ReceiverBase extends ContextAwareBase - implements LifeCycle { +public abstract class ReceiverBase extends ContextAwareBase implements LifeCycle { - private boolean started; - - /** - * {@inheritDoc} - */ - public final void start() { - if (isStarted()) return; - if (getContext() == null) { - throw new IllegalStateException("context not set"); - } - if (shouldStart()) { - getContext().getExecutorService().execute(getRunnableTask()); - started = true; + private boolean started; + + /** + * {@inheritDoc} + */ + public final void start() { + if (isStarted()) + return; + if (getContext() == null) { + throw new IllegalStateException("context not set"); + } + if (shouldStart()) { + getContext().getExecutorService().execute(getRunnableTask()); + started = true; + } } - } - /** - * {@inheritDoc} - */ - public final void stop() { - if (!isStarted()) return; - try { - onStop(); + /** + * {@inheritDoc} + */ + public final void stop() { + if (!isStarted()) + return; + try { + onStop(); + } catch (RuntimeException ex) { + addError("on stop: " + ex, ex); + } + started = false; } - catch (RuntimeException ex) { - addError("on stop: " + ex, ex); + + /** + * {@inheritDoc} + */ + public final boolean isStarted() { + return started; } - started = false; - } - - /** - * {@inheritDoc} - */ - public final boolean isStarted() { - return started; - } - /** - * Determines whether this receiver should start. - *

- * Subclasses will implement this method to do any subclass-specific - * validation. The subclass's {@link #getRunnableTask()} method will be - * invoked (and the task returned will be submitted to the executor) - * if and only if this method returns {@code true} - * @return flag indicating whether this receiver should start - */ - protected abstract boolean shouldStart(); - - /** - * Allows a subclass to participate in receiver shutdown. - */ - protected abstract void onStop(); - - /** - * Provides the runnable task this receiver will execute. - * @return runnable task - */ - protected abstract Runnable getRunnableTask(); - + /** + * Determines whether this receiver should start. + *

+ * Subclasses will implement this method to do any subclass-specific + * validation. The subclass's {@link #getRunnableTask()} method will be + * invoked (and the task returned will be submitted to the executor) + * if and only if this method returns {@code true} + * @return flag indicating whether this receiver should start + */ + protected abstract boolean shouldStart(); + + /** + * Allows a subclass to participate in receiver shutdown. + */ + protected abstract void onStop(); + + /** + * Provides the runnable task this receiver will execute. + * @return runnable task + */ + protected abstract Runnable getRunnableTask(); + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java index 970357237c92a0eb2a2dd179d273d20ee20fc73a..acbb52c3ac5bce76805d0d76f25d767ba6b5697b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SMTPAppender.java @@ -36,100 +36,96 @@ import org.slf4j.Marker; */ public class SMTPAppender extends SMTPAppenderBase { - // value "%logger{20} - %m" is referenced in the docs! - static final String DEFAULT_SUBJECT_PATTERN = "%logger{20} - %m"; - - private int bufferSize = 512; - private boolean includeCallerData = false; - - - - /** - * The default constructor will instantiate the appender with a - * {@link EventEvaluator} that will trigger on events with level - * ERROR or higher. - */ - public SMTPAppender() { - - } - - public void start() { - if (eventEvaluator == null) { - OnErrorEvaluator onError = new OnErrorEvaluator(); - onError.setContext(getContext()); - onError.setName("onError"); - onError.start(); - this.eventEvaluator = onError; + // value "%logger{20} - %m" is referenced in the docs! + static final String DEFAULT_SUBJECT_PATTERN = "%logger{20} - %m"; + + private int bufferSize = 512; + private boolean includeCallerData = false; + + /** + * The default constructor will instantiate the appender with a + * {@link EventEvaluator} that will trigger on events with level + * ERROR or higher. + */ + public SMTPAppender() { + + } + + public void start() { + if (eventEvaluator == null) { + OnErrorEvaluator onError = new OnErrorEvaluator(); + onError.setContext(getContext()); + onError.setName("onError"); + onError.start(); + this.eventEvaluator = onError; + } + super.start(); } - super.start(); - } - - /** - * Use the parameter as the {@link - * EventEvaluator} for this SMTPAppender. - */ - public SMTPAppender(EventEvaluator eventEvaluator) { - this.eventEvaluator = eventEvaluator; - } - - /** - * Perform SMTPAppender specific appending actions, mainly adding the event to - * a cyclic buffer. - */ - protected void subAppend(CyclicBuffer cb, ILoggingEvent event) { - if(includeCallerData) { - event.getCallerData(); + + /** + * Use the parameter as the {@link + * EventEvaluator} for this SMTPAppender. + */ + public SMTPAppender(EventEvaluator eventEvaluator) { + this.eventEvaluator = eventEvaluator; } - event.prepareForDeferredProcessing(); - cb.add(event); - } - - @Override - protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf) { - int len = cb.length(); - for (int i = 0; i < len; i++) { - ILoggingEvent event = cb.get(); - sbuf.append(layout.doLayout(event)); + + /** + * Perform SMTPAppender specific appending actions, mainly adding the event to + * a cyclic buffer. + */ + protected void subAppend(CyclicBuffer cb, ILoggingEvent event) { + if (includeCallerData) { + event.getCallerData(); + } + event.prepareForDeferredProcessing(); + cb.add(event); } - } - protected boolean eventMarksEndOfLife(ILoggingEvent eventObject) { - Marker marker = eventObject.getMarker(); - if(marker == null) - return false; + @Override + protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf) { + int len = cb.length(); + for (int i = 0; i < len; i++) { + ILoggingEvent event = cb.get(); + sbuf.append(layout.doLayout(event)); + } + } - return marker.contains(ClassicConstants.FINALIZE_SESSION_MARKER); - } + protected boolean eventMarksEndOfLife(ILoggingEvent eventObject) { + Marker marker = eventObject.getMarker(); + if (marker == null) + return false; + return marker.contains(ClassicConstants.FINALIZE_SESSION_MARKER); + } + + @Override + protected Layout makeSubjectLayout(String subjectStr) { + if (subjectStr == null) { + subjectStr = DEFAULT_SUBJECT_PATTERN; + } + PatternLayout pl = new PatternLayout(); + pl.setContext(getContext()); + pl.setPattern(subjectStr); + // we don't want a ThrowableInformationConverter appended + // to the end of the converter chain + // This fixes issue LBCLASSIC-67 + pl.setPostCompileProcessor(null); + pl.start(); + return pl; + } + + protected PatternLayout makeNewToPatternLayout(String toPattern) { + PatternLayout pl = new PatternLayout(); + pl.setPattern(toPattern + "%nopex"); + return pl; + } + + public boolean isIncludeCallerData() { + return includeCallerData; + } - @Override - protected Layout makeSubjectLayout(String subjectStr) { - if(subjectStr == null) { - subjectStr = DEFAULT_SUBJECT_PATTERN; + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; } - PatternLayout pl = new PatternLayout(); - pl.setContext(getContext()); - pl.setPattern(subjectStr); - // we don't want a ThrowableInformationConverter appended - // to the end of the converter chain - // This fixes issue LBCLASSIC-67 - pl.setPostCompileProcessor(null); - pl.start(); - return pl; - } - - - protected PatternLayout makeNewToPatternLayout(String toPattern) { - PatternLayout pl = new PatternLayout(); - pl.setPattern(toPattern+"%nopex"); - return pl; - } - - public boolean isIncludeCallerData() { - return includeCallerData; - } - - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketAppender.java index 1b05bd8e263ff426def61e2811976a3b4e437ddc..46a8d67232181e14f362edb244ac37a505ae2771 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketAppender.java @@ -29,27 +29,26 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class SSLSocketAppender extends AbstractSSLSocketAppender { - private final PreSerializationTransformer pst = - new LoggingEventPreSerializationTransformer(); - - private boolean includeCallerData; - - public SSLSocketAppender() { - } - - @Override - protected void postProcessEvent(ILoggingEvent event) { - if (includeCallerData) { - event.getCallerData(); + private final PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + private boolean includeCallerData; + + public SSLSocketAppender() { } - } - - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } - - public PreSerializationTransformer getPST() { - return pst; - } - + + @Override + protected void postProcessEvent(ILoggingEvent event) { + if (includeCallerData) { + event.getCallerData(); + } + } + + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; + } + + public PreSerializationTransformer getPST() { + return pst; + } + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketReceiver.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketReceiver.java index f5282a8994ff7682c9060c2ac7b77c707af9934f..1146fcbf99b31d676601f9773324bd68bb40d85a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketReceiver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SSLSocketReceiver.java @@ -26,59 +26,56 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; * * @author Carl Harris */ -public class SSLSocketReceiver extends SocketReceiver - implements SSLComponent { +public class SSLSocketReceiver extends SocketReceiver implements SSLComponent { - private SSLConfiguration ssl; - private SocketFactory socketFactory; + private SSLConfiguration ssl; + private SocketFactory socketFactory; - /** - * Gets an {@link SocketFactory} that produces SSL sockets using an - * {@link SSLContext} that is derived from the receiver's configuration. - * @return socket factory - */ - @Override - protected SocketFactory getSocketFactory() { - return socketFactory; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean shouldStart() { - try { - SSLContext sslContext = getSsl().createContext(this); - SSLParametersConfiguration parameters = getSsl().getParameters(); - parameters.setContext(getContext()); - socketFactory = new ConfigurableSSLSocketFactory(parameters, - sslContext.getSocketFactory()); - return super.shouldStart(); + /** + * Gets an {@link SocketFactory} that produces SSL sockets using an + * {@link SSLContext} that is derived from the receiver's configuration. + * @return socket factory + */ + @Override + protected SocketFactory getSocketFactory() { + return socketFactory; } - catch (Exception ex) { - addError(ex.getMessage(), ex); - return false; + + /** + * {@inheritDoc} + */ + @Override + protected boolean shouldStart() { + try { + SSLContext sslContext = getSsl().createContext(this); + SSLParametersConfiguration parameters = getSsl().getParameters(); + parameters.setContext(getContext()); + socketFactory = new ConfigurableSSLSocketFactory(parameters, sslContext.getSocketFactory()); + return super.shouldStart(); + } catch (Exception ex) { + addError(ex.getMessage(), ex); + return false; + } } - } - /** - * Gets the SSL configuration. - * @return SSL configuration; if no configuration has been set, a - * default configuration is returned - */ - public SSLConfiguration getSsl() { - if (ssl == null) { - ssl = new SSLConfiguration(); + /** + * Gets the SSL configuration. + * @return SSL configuration; if no configuration has been set, a + * default configuration is returned + */ + public SSLConfiguration getSsl() { + if (ssl == null) { + ssl = new SSLConfiguration(); + } + return ssl; } - return ssl; - } - /** - * Sets the SSL configuration. - * @param ssl the SSL configuration to set - */ - public void setSsl(SSLConfiguration ssl) { - this.ssl = ssl; - } + /** + * Sets the SSL configuration. + * @param ssl the SSL configuration to set + */ + public void setSsl(SSLConfiguration ssl) { + this.ssl = ssl; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSSLSocketServer.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSSLSocketServer.java index cc6dd4311d2862213880aa3f01a29168cf55b34c..848ffc50fb2600a16dbe14a5118adbd7eb87c694 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSSLSocketServer.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSSLSocketServer.java @@ -56,46 +56,43 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; */ public class SimpleSSLSocketServer extends SimpleSocketServer { - private final ServerSocketFactory socketFactory; + private final ServerSocketFactory socketFactory; - public static void main(String argv[]) throws Exception { - doMain(SimpleSSLSocketServer.class, argv); - } + public static void main(String argv[]) throws Exception { + doMain(SimpleSSLSocketServer.class, argv); + } + + /** + * Creates a new server using the default SSL context. + * @param lc logger context for received events + * @param port port on which the server is to listen + * @throws NoSuchAlgorithmException if the default SSL context cannot be + * created + */ + public SimpleSSLSocketServer(LoggerContext lc, int port) throws NoSuchAlgorithmException { + this(lc, port, SSLContext.getDefault()); + } - /** - * Creates a new server using the default SSL context. - * @param lc logger context for received events - * @param port port on which the server is to listen - * @throws NoSuchAlgorithmException if the default SSL context cannot be - * created - */ - public SimpleSSLSocketServer(LoggerContext lc, int port) - throws NoSuchAlgorithmException { - this(lc, port, SSLContext.getDefault()); - } + /** + * Creates a new server using a custom SSL context. + * @param lc logger context for received events + * @param port port on which the server is to listen + * @param sslContext custom SSL context + */ + public SimpleSSLSocketServer(LoggerContext lc, int port, SSLContext sslContext) { + super(lc, port); + if (sslContext == null) { + throw new NullPointerException("SSL context required"); + } + SSLParametersConfiguration parameters = new SSLParametersConfiguration(); - /** - * Creates a new server using a custom SSL context. - * @param lc logger context for received events - * @param port port on which the server is to listen - * @param sslContext custom SSL context - */ - public SimpleSSLSocketServer(LoggerContext lc, int port, - SSLContext sslContext) { - super(lc, port); - if (sslContext == null) { - throw new NullPointerException("SSL context required"); + parameters.setContext(lc); + this.socketFactory = new ConfigurableSSLServerSocketFactory(parameters, sslContext.getServerSocketFactory()); } - SSLParametersConfiguration parameters = new SSLParametersConfiguration(); - - parameters.setContext(lc); - this.socketFactory = new ConfigurableSSLServerSocketFactory( - parameters, sslContext.getServerSocketFactory()); - } - @Override - protected ServerSocketFactory getServerSocketFactory() { - return socketFactory; - } + @Override + protected ServerSocketFactory getServerSocketFactory() { + return socketFactory; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSocketServer.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSocketServer.java index fe765cb70af7df2c6b8ed80ba33f52ddf7841acb..6d39a24737944995290443022f8b33a299a9a878 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSocketServer.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SimpleSocketServer.java @@ -50,190 +50,188 @@ import ch.qos.logback.core.joran.spi.JoranException; */ public class SimpleSocketServer extends Thread { - Logger logger = LoggerFactory.getLogger(SimpleSocketServer.class); - - private final int port; - private final LoggerContext lc; - private boolean closed = false; - private ServerSocket serverSocket; - private List socketNodeList = new ArrayList(); - - // used for testing purposes - private CountDownLatch latch; - - public static void main(String argv[]) throws Exception { - doMain(SimpleSocketServer.class, argv); - } - - protected static void doMain(Class serverClass, - String argv[]) throws Exception { - int port = -1; - if (argv.length == 2) { - port = parsePortNumber(argv[0]); - } else { - usage("Wrong number of arguments."); - } - - String configFile = argv[1]; - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - configureLC(lc, configFile); - - SimpleSocketServer sss = new SimpleSocketServer(lc, port); - sss.start(); - } - - public SimpleSocketServer(LoggerContext lc, int port) { - this.lc = lc; - this.port = port; - } - - - public void run() { - - final String oldThreadName = Thread.currentThread().getName(); - - try { - - final String newThreadName = getServerThreadName(); - Thread.currentThread().setName(newThreadName); - - logger.info("Listening on port " + port); - serverSocket = getServerSocketFactory().createServerSocket(port); - while (!closed) { - logger.info("Waiting to accept a new client."); - signalAlmostReadiness(); - Socket socket = serverSocket.accept(); - logger.info("Connected to client at " + socket.getInetAddress()); - logger.info("Starting new socket node."); - SocketNode newSocketNode = new SocketNode(this, socket, lc); + Logger logger = LoggerFactory.getLogger(SimpleSocketServer.class); + + private final int port; + private final LoggerContext lc; + private boolean closed = false; + private ServerSocket serverSocket; + private List socketNodeList = new ArrayList(); + + // used for testing purposes + private CountDownLatch latch; + + public static void main(String argv[]) throws Exception { + doMain(SimpleSocketServer.class, argv); + } + + protected static void doMain(Class serverClass, String argv[]) throws Exception { + int port = -1; + if (argv.length == 2) { + port = parsePortNumber(argv[0]); + } else { + usage("Wrong number of arguments."); + } + + String configFile = argv[1]; + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + configureLC(lc, configFile); + + SimpleSocketServer sss = new SimpleSocketServer(lc, port); + sss.start(); + } + + public SimpleSocketServer(LoggerContext lc, int port) { + this.lc = lc; + this.port = port; + } + + public void run() { + + final String oldThreadName = Thread.currentThread().getName(); + + try { + + final String newThreadName = getServerThreadName(); + Thread.currentThread().setName(newThreadName); + + logger.info("Listening on port " + port); + serverSocket = getServerSocketFactory().createServerSocket(port); + while (!closed) { + logger.info("Waiting to accept a new client."); + signalAlmostReadiness(); + Socket socket = serverSocket.accept(); + logger.info("Connected to client at " + socket.getInetAddress()); + logger.info("Starting new socket node."); + SocketNode newSocketNode = new SocketNode(this, socket, lc); + synchronized (socketNodeList) { + socketNodeList.add(newSocketNode); + } + final String clientThreadName = getClientThreadName(socket); + new Thread(newSocketNode, clientThreadName).start(); + } + } catch (Exception e) { + if (closed) { + logger.info("Exception in run method for a closed server. This is normal."); + } else { + logger.error("Unexpected failure in run method", e); + } + } + + finally { + Thread.currentThread().setName(oldThreadName); + } + } + + /** + * Returns the name given to the server thread. + */ + protected String getServerThreadName() { + return String.format("Logback %s (port %d)", getClass().getSimpleName(), port); + } + + /** + * Returns a name to identify each client thread. + */ + protected String getClientThreadName(Socket socket) { + return String.format("Logback SocketNode (client: %s)", socket.getRemoteSocketAddress()); + } + + /** + * Gets the platform default {@link ServerSocketFactory}. + *

+ * Subclasses may override to provide a custom server socket factory. + */ + protected ServerSocketFactory getServerSocketFactory() { + return ServerSocketFactory.getDefault(); + } + + /** + * Signal another thread that we have established a connection + * This is useful for testing purposes. + */ + void signalAlmostReadiness() { + if (latch != null && latch.getCount() != 0) { + // System.out.println("signalAlmostReadiness() with latch "+latch); + latch.countDown(); + } + } + + /** + * Used for testing purposes + * @param latch + */ + void setLatch(CountDownLatch latch) { + this.latch = latch; + } + + /** + * Used for testing purposes + */ + public CountDownLatch getLatch() { + return latch; + } + + public boolean isClosed() { + return closed; + } + + public void close() { + closed = true; + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException e) { + logger.error("Failed to close serverSocket", e); + } finally { + serverSocket = null; + } + } + + logger.info("closing this server"); + synchronized (socketNodeList) { + for (SocketNode sn : socketNodeList) { + sn.close(); + } + } + if (socketNodeList.size() != 0) { + logger.warn("Was expecting a 0-sized socketNodeList after server shutdown"); + } + + } + + public void socketNodeClosing(SocketNode sn) { + logger.debug("Removing {}", sn); + + // don't allow simultaneous access to the socketNodeList + // (e.g. removal whole iterating on the list causes + // java.util.ConcurrentModificationException synchronized (socketNodeList) { - socketNodeList.add(newSocketNode); + socketNodeList.remove(sn); + } + } + + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SimpleSocketServer.class.getName() + " port configFile"); + System.exit(1); + } + + static int parsePortNumber(String portStr) { + try { + return Integer.parseInt(portStr); + } catch (java.lang.NumberFormatException e) { + e.printStackTrace(); + usage("Could not interpret port number [" + portStr + "]."); + // we won't get here + return -1; } - final String clientThreadName = getClientThreadName(socket); - new Thread(newSocketNode, clientThreadName).start(); - } - } catch (Exception e) { - if(closed) { - logger.info("Exception in run method for a closed server. This is normal."); - } else { - logger.error("Unexpected failure in run method", e); - } - } - - finally { - Thread.currentThread().setName(oldThreadName); - } - } - - /** - * Returns the name given to the server thread. - */ - protected String getServerThreadName() { - return String.format("Logback %s (port %d)", getClass().getSimpleName(), port); - } - - /** - * Returns a name to identify each client thread. - */ - protected String getClientThreadName(Socket socket) { - return String.format("Logback SocketNode (client: %s)", socket.getRemoteSocketAddress()); - } - - /** - * Gets the platform default {@link ServerSocketFactory}. - *

- * Subclasses may override to provide a custom server socket factory. - */ - protected ServerSocketFactory getServerSocketFactory() { - return ServerSocketFactory.getDefault(); - } - - /** - * Signal another thread that we have established a connection - * This is useful for testing purposes. - */ - void signalAlmostReadiness() { - if(latch != null && latch.getCount() != 0) { - //System.out.println("signalAlmostReadiness() with latch "+latch); - latch.countDown(); - } - } - - /** - * Used for testing purposes - * @param latch - */ - void setLatch(CountDownLatch latch) { - this.latch = latch; - } - /** - * Used for testing purposes - */ - public CountDownLatch getLatch() { - return latch; - } - public boolean isClosed() { - return closed; - } - - public void close() { - closed = true; - if (serverSocket != null) { - try { - serverSocket.close(); - } catch (IOException e) { - logger.error("Failed to close serverSocket", e); - } finally { - serverSocket = null; - } - } - - logger.info("closing this server"); - synchronized (socketNodeList) { - for(SocketNode sn: socketNodeList) { - sn.close(); - } - } - if(socketNodeList.size() != 0) { - logger.warn("Was expecting a 0-sized socketNodeList after server shutdown"); - } - - } - - public void socketNodeClosing(SocketNode sn) { - logger.debug("Removing {}", sn); - - // don't allow simultaneous access to the socketNodeList - // (e.g. removal whole iterating on the list causes - // java.util.ConcurrentModificationException - synchronized (socketNodeList) { - socketNodeList.remove(sn); - } - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SimpleSocketServer.class.getName() - + " port configFile"); - System.exit(1); - } - - static int parsePortNumber(String portStr) { - try { - return Integer.parseInt(portStr); - } catch (java.lang.NumberFormatException e) { - e.printStackTrace(); - usage("Could not interpret port number [" + portStr + "]."); - // we won't get here - return -1; - } - } - - static public void configureLC(LoggerContext lc, String configFile) - throws JoranException { - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - } + } + + static public void configureLC(LoggerContext lc, String configFile) throws JoranException { + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAcceptor.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAcceptor.java index 57d2688de998a38d7afa17c20956904bbed4ef4f..93a2b2981d5017b10974c2b0a360338778b52c36 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAcceptor.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAcceptor.java @@ -15,9 +15,8 @@ package ch.qos.logback.classic.net; class SocketAcceptor extends Thread { - - @Override - public void run() { - - } + @Override + public void run() { + + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAppender.java index ee92073d740a4185b8d567e68660fe060bf1f3b5..c293cce561392b8b0f8a9be3e3f850feedc4d3e0 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketAppender.java @@ -33,28 +33,26 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; public class SocketAppender extends AbstractSocketAppender { - private static final PreSerializationTransformer pst = - new LoggingEventPreSerializationTransformer(); - - private boolean includeCallerData = false; + private static final PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - public SocketAppender() { - } + private boolean includeCallerData = false; + public SocketAppender() { + } + + @Override + protected void postProcessEvent(ILoggingEvent event) { + if (includeCallerData) { + event.getCallerData(); + } + } - @Override - protected void postProcessEvent(ILoggingEvent event) { - if (includeCallerData) { - event.getCallerData(); + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; } - } - - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } - - public PreSerializationTransformer getPST() { - return pst; - } - + + public PreSerializationTransformer getPST() { + return pst; + } + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketNode.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketNode.java index 577c55d3f8026ca330cacf2489537aa458d33209..21474a43907298c38fdbb1eee4ee58f23b0055f0 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketNode.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketNode.java @@ -42,88 +42,87 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class SocketNode implements Runnable { - Socket socket; - LoggerContext context; - ObjectInputStream ois; - SocketAddress remoteSocketAddress; - - Logger logger; - boolean closed = false; - SimpleSocketServer socketServer; - - public SocketNode(SimpleSocketServer socketServer, Socket socket, LoggerContext context) { - this.socketServer = socketServer; - this.socket = socket; - remoteSocketAddress = socket.getRemoteSocketAddress(); - this.context = context; - logger = context.getLogger(SocketNode.class); - } - - // public - // void finalize() { - // System.err.println("-------------------------Finalize called"); - // System.err.flush(); - // } - - public void run() { - - try { - ois = new ObjectInputStream(new BufferedInputStream(socket - .getInputStream())); - } catch (Exception e) { - logger.error("Could not open ObjectInputStream to " + socket, e); - closed = true; + Socket socket; + LoggerContext context; + ObjectInputStream ois; + SocketAddress remoteSocketAddress; + + Logger logger; + boolean closed = false; + SimpleSocketServer socketServer; + + public SocketNode(SimpleSocketServer socketServer, Socket socket, LoggerContext context) { + this.socketServer = socketServer; + this.socket = socket; + remoteSocketAddress = socket.getRemoteSocketAddress(); + this.context = context; + logger = context.getLogger(SocketNode.class); } - ILoggingEvent event; - Logger remoteLogger; - - try { - while (!closed) { - // read an event from the wire - event = (ILoggingEvent) ois.readObject(); - // get a logger from the hierarchy. The name of the logger is taken to - // be the name contained in the event. - remoteLogger = context.getLogger(event.getLoggerName()); - // apply the logger-level filter - if (remoteLogger.isEnabledFor(event.getLevel())) { - // finally log the event as if was generated locally - remoteLogger.callAppenders(event); + // public + // void finalize() { + // System.err.println("-------------------------Finalize called"); + // System.err.flush(); + // } + + public void run() { + + try { + ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream())); + } catch (Exception e) { + logger.error("Could not open ObjectInputStream to " + socket, e); + closed = true; } - } - } catch (java.io.EOFException e) { - logger.info("Caught java.io.EOFException closing connection."); - } catch (java.net.SocketException e) { - logger.info("Caught java.net.SocketException closing connection."); - } catch (IOException e) { - logger.info("Caught java.io.IOException: " + e); - logger.info("Closing connection."); - } catch (Exception e) { - logger.error("Unexpected exception. Closing connection.", e); + + ILoggingEvent event; + Logger remoteLogger; + + try { + while (!closed) { + // read an event from the wire + event = (ILoggingEvent) ois.readObject(); + // get a logger from the hierarchy. The name of the logger is taken to + // be the name contained in the event. + remoteLogger = context.getLogger(event.getLoggerName()); + // apply the logger-level filter + if (remoteLogger.isEnabledFor(event.getLevel())) { + // finally log the event as if was generated locally + remoteLogger.callAppenders(event); + } + } + } catch (java.io.EOFException e) { + logger.info("Caught java.io.EOFException closing connection."); + } catch (java.net.SocketException e) { + logger.info("Caught java.net.SocketException closing connection."); + } catch (IOException e) { + logger.info("Caught java.io.IOException: " + e); + logger.info("Closing connection."); + } catch (Exception e) { + logger.error("Unexpected exception. Closing connection.", e); + } + + socketServer.socketNodeClosing(this); + close(); } - socketServer.socketNodeClosing(this); - close(); - } - - void close() { - if(closed) { - return; + void close() { + if (closed) { + return; + } + closed = true; + if (ois != null) { + try { + ois.close(); + } catch (IOException e) { + logger.warn("Could not close connection.", e); + } finally { + ois = null; + } + } } - closed = true; - if (ois != null) { - try { - ois.close(); - } catch (IOException e) { - logger.warn("Could not close connection.", e); - } finally { - ois = null; - } + + @Override + public String toString() { + return this.getClass().getName() + remoteSocketAddress.toString(); } - } - - @Override - public String toString() { - return this.getClass().getName()+remoteSocketAddress.toString(); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java index 223e584332e9734add0976fbefb82d74af1b4698..4652339225e6a764b7dfbbb24b979f61764b81e5 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SocketReceiver.java @@ -40,186 +40,178 @@ import ch.qos.logback.core.util.CloseUtil; * * @author Carl Harris */ -public class SocketReceiver extends ReceiverBase - implements Runnable, SocketConnector.ExceptionHandler { - - private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000; - - private String remoteHost; - private InetAddress address; - private int port; - private int reconnectionDelay; - private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY; - - private String receiverId; - private volatile Socket socket; - private Future connectorTask; - - /** - * {@inheritDoc} - */ - protected boolean shouldStart() { - int errorCount = 0; - if (port == 0) { - errorCount++; - addError("No port was configured for receiver. " - + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_port"); - } +public class SocketReceiver extends ReceiverBase implements Runnable, SocketConnector.ExceptionHandler { + + private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000; + + private String remoteHost; + private InetAddress address; + private int port; + private int reconnectionDelay; + private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY; + + private String receiverId; + private volatile Socket socket; + private Future connectorTask; + + /** + * {@inheritDoc} + */ + protected boolean shouldStart() { + int errorCount = 0; + if (port == 0) { + errorCount++; + addError("No port was configured for receiver. " + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_port"); + } - if (remoteHost == null) { - errorCount++; - addError("No host name or address was configured for receiver. " - + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_host"); - } + if (remoteHost == null) { + errorCount++; + addError("No host name or address was configured for receiver. " + + "For more information, please visit http://logback.qos.ch/codes.html#receiver_no_host"); + } - if (reconnectionDelay == 0) { - reconnectionDelay = AbstractSocketAppender.DEFAULT_RECONNECTION_DELAY; - } + if (reconnectionDelay == 0) { + reconnectionDelay = AbstractSocketAppender.DEFAULT_RECONNECTION_DELAY; + } - if (errorCount == 0) { - try { - address = InetAddress.getByName(remoteHost); - } catch (UnknownHostException ex) { - addError("unknown host: " + remoteHost); - errorCount++; - } - } + if (errorCount == 0) { + try { + address = InetAddress.getByName(remoteHost); + } catch (UnknownHostException ex) { + addError("unknown host: " + remoteHost); + errorCount++; + } + } + + if (errorCount == 0) { + receiverId = "receiver " + remoteHost + ":" + port + ": "; + } - if (errorCount == 0) { - receiverId = "receiver " + remoteHost + ":" + port + ": "; + return errorCount == 0; } - return errorCount == 0; - } + /** + * {@inheritDoc} + */ + protected void onStop() { + if (socket != null) { + CloseUtil.closeQuietly(socket); + } + } - /** - * {@inheritDoc} - */ - protected void onStop() { - if (socket != null) { - CloseUtil.closeQuietly(socket); + @Override + protected Runnable getRunnableTask() { + return this; } - } - - @Override - protected Runnable getRunnableTask() { - return this; - } - - /** - * {@inheritDoc} - */ - public void run() { - try { - LoggerContext lc = (LoggerContext) getContext(); - while (!Thread.currentThread().isInterrupted()) { - SocketConnector connector = createConnector(address, port, 0, - reconnectionDelay); - connectorTask = activateConnector(connector); - if (connectorTask == null) - break; - socket = waitForConnectorToReturnASocket(); - if (socket == null) - break; - dispatchEvents(lc); - } - } catch (InterruptedException ex) { - assert true; // ok... we'll exit now + + /** + * {@inheritDoc} + */ + public void run() { + try { + LoggerContext lc = (LoggerContext) getContext(); + while (!Thread.currentThread().isInterrupted()) { + SocketConnector connector = createConnector(address, port, 0, reconnectionDelay); + connectorTask = activateConnector(connector); + if (connectorTask == null) + break; + socket = waitForConnectorToReturnASocket(); + if (socket == null) + break; + dispatchEvents(lc); + } + } catch (InterruptedException ex) { + assert true; // ok... we'll exit now + } + addInfo("shutting down"); } - addInfo("shutting down"); - } - - private SocketConnector createConnector(InetAddress address, int port, - int initialDelay, int retryDelay) { - SocketConnector connector = newConnector(address, port, initialDelay, - retryDelay); - connector.setExceptionHandler(this); - connector.setSocketFactory(getSocketFactory()); - return connector; - } - - - private Future activateConnector(SocketConnector connector) { - try { - return getContext().getExecutorService().submit(connector); - } catch (RejectedExecutionException ex) { - return null; + + private SocketConnector createConnector(InetAddress address, int port, int initialDelay, int retryDelay) { + SocketConnector connector = newConnector(address, port, initialDelay, retryDelay); + connector.setExceptionHandler(this); + connector.setSocketFactory(getSocketFactory()); + return connector; } - } - - private Socket waitForConnectorToReturnASocket() throws InterruptedException { - try { - Socket s = connectorTask.get(); - connectorTask = null; - return s; - } catch (ExecutionException e) { - return null; + + private Future activateConnector(SocketConnector connector) { + try { + return getContext().getExecutorService().submit(connector); + } catch (RejectedExecutionException ex) { + return null; + } } - } - - private void dispatchEvents(LoggerContext lc) { - try { - socket.setSoTimeout(acceptConnectionTimeout); - ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); - socket.setSoTimeout(0); - addInfo(receiverId + "connection established"); - while (true) { - ILoggingEvent event = (ILoggingEvent) ois.readObject(); - Logger remoteLogger = lc.getLogger(event.getLoggerName()); - if (remoteLogger.isEnabledFor(event.getLevel())) { - remoteLogger.callAppenders(event); + + private Socket waitForConnectorToReturnASocket() throws InterruptedException { + try { + Socket s = connectorTask.get(); + connectorTask = null; + return s; + } catch (ExecutionException e) { + return null; } - } - } catch (EOFException ex) { - addInfo(receiverId + "end-of-stream detected"); - } catch (IOException ex) { - addInfo(receiverId + "connection failed: " + ex); - } catch (ClassNotFoundException ex) { - addInfo(receiverId + "unknown event class: " + ex); - } finally { - CloseUtil.closeQuietly(socket); - socket = null; - addInfo(receiverId + "connection closed"); } - } - - /** - * {@inheritDoc} - */ - public void connectionFailed(SocketConnector connector, Exception ex) { - if (ex instanceof InterruptedException) { - addInfo("connector interrupted"); - } else if (ex instanceof ConnectException) { - addInfo(receiverId + "connection refused"); - } else { - addInfo(receiverId + ex); + + private void dispatchEvents(LoggerContext lc) { + try { + socket.setSoTimeout(acceptConnectionTimeout); + ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); + socket.setSoTimeout(0); + addInfo(receiverId + "connection established"); + while (true) { + ILoggingEvent event = (ILoggingEvent) ois.readObject(); + Logger remoteLogger = lc.getLogger(event.getLoggerName()); + if (remoteLogger.isEnabledFor(event.getLevel())) { + remoteLogger.callAppenders(event); + } + } + } catch (EOFException ex) { + addInfo(receiverId + "end-of-stream detected"); + } catch (IOException ex) { + addInfo(receiverId + "connection failed: " + ex); + } catch (ClassNotFoundException ex) { + addInfo(receiverId + "unknown event class: " + ex); + } finally { + CloseUtil.closeQuietly(socket); + socket = null; + addInfo(receiverId + "connection closed"); + } } - } + /** + * {@inheritDoc} + */ + public void connectionFailed(SocketConnector connector, Exception ex) { + if (ex instanceof InterruptedException) { + addInfo("connector interrupted"); + } else if (ex instanceof ConnectException) { + addInfo(receiverId + "connection refused"); + } else { + addInfo(receiverId + ex); + } + } - protected SocketConnector newConnector(InetAddress address, - int port, int initialDelay, int retryDelay) { - return new DefaultSocketConnector(address, port, initialDelay, retryDelay); - } + protected SocketConnector newConnector(InetAddress address, int port, int initialDelay, int retryDelay) { + return new DefaultSocketConnector(address, port, initialDelay, retryDelay); + } - protected SocketFactory getSocketFactory() { - return SocketFactory.getDefault(); - } + protected SocketFactory getSocketFactory() { + return SocketFactory.getDefault(); + } - public void setRemoteHost(String remoteHost) { - this.remoteHost = remoteHost; - } + public void setRemoteHost(String remoteHost) { + this.remoteHost = remoteHost; + } - public void setPort(int port) { - this.port = port; - } + public void setPort(int port) { + this.port = port; + } - public void setReconnectionDelay(int reconnectionDelay) { - this.reconnectionDelay = reconnectionDelay; - } + public void setReconnectionDelay(int reconnectionDelay) { + this.reconnectionDelay = reconnectionDelay; + } - public void setAcceptConnectionTimeout(int acceptConnectionTimeout) { - this.acceptConnectionTimeout = acceptConnectionTimeout; - } + public void setAcceptConnectionTimeout(int acceptConnectionTimeout) { + this.acceptConnectionTimeout = acceptConnectionTimeout; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/SyslogAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/SyslogAppender.java index ea6ad3d21e31ef33a38be012db923964ad36fb89..13c78669127d13495c05fec3f9eff1964782df45 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/SyslogAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/SyslogAppender.java @@ -38,146 +38,143 @@ import ch.qos.logback.core.net.SyslogOutputStream; */ public class SyslogAppender extends SyslogAppenderBase { - static final public String DEFAULT_SUFFIX_PATTERN = "[%thread] %logger %msg"; - static final public String DEFAULT_STACKTRACE_PATTERN = "" + CoreConstants.TAB; - - PatternLayout stackTraceLayout = new PatternLayout(); - String stackTracePattern = DEFAULT_STACKTRACE_PATTERN; - - boolean throwableExcluded = false; - - - public void start() { - super.start(); - setupStackTraceLayout(); - } - - String getPrefixPattern() { - return "%syslogStart{" + getFacility() + "}%nopex{}"; - } - - @Override - public SyslogOutputStream createOutputStream() throws SocketException, UnknownHostException { - return new SyslogOutputStream(getSyslogHost(), getPort()); - } - - /** - * Convert a level to equivalent syslog severity. Only levels for printing - * methods i.e DEBUG, WARN, INFO and ERROR are converted. - * - * @see ch.qos.logback.core.net.SyslogAppenderBase#getSeverityForEvent(java.lang.Object) - */ - @Override - public int getSeverityForEvent(Object eventObject) { - ILoggingEvent event = (ILoggingEvent) eventObject; - return LevelToSyslogSeverity.convert(event); - } - - @Override - protected void postProcess(Object eventObject, OutputStream sw) { - if (throwableExcluded) - return; - - ILoggingEvent event = (ILoggingEvent) eventObject; - IThrowableProxy tp = event.getThrowableProxy(); - - if (tp == null) - return; - - String stackTracePrefix = stackTraceLayout.doLayout(event); - boolean isRootException = true; - while (tp != null) { - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - try { - handleThrowableFirstLine(sw, tp, stackTracePrefix, isRootException); - isRootException = false; - for (StackTraceElementProxy step : stepArray) { - StringBuilder sb = new StringBuilder(); - sb.append(stackTracePrefix).append(step); - sw.write(sb.toString().getBytes()); - sw.flush(); + static final public String DEFAULT_SUFFIX_PATTERN = "[%thread] %logger %msg"; + static final public String DEFAULT_STACKTRACE_PATTERN = "" + CoreConstants.TAB; + + PatternLayout stackTraceLayout = new PatternLayout(); + String stackTracePattern = DEFAULT_STACKTRACE_PATTERN; + + boolean throwableExcluded = false; + + public void start() { + super.start(); + setupStackTraceLayout(); + } + + String getPrefixPattern() { + return "%syslogStart{" + getFacility() + "}%nopex{}"; + } + + @Override + public SyslogOutputStream createOutputStream() throws SocketException, UnknownHostException { + return new SyslogOutputStream(getSyslogHost(), getPort()); + } + + /** + * Convert a level to equivalent syslog severity. Only levels for printing + * methods i.e DEBUG, WARN, INFO and ERROR are converted. + * + * @see ch.qos.logback.core.net.SyslogAppenderBase#getSeverityForEvent(java.lang.Object) + */ + @Override + public int getSeverityForEvent(Object eventObject) { + ILoggingEvent event = (ILoggingEvent) eventObject; + return LevelToSyslogSeverity.convert(event); + } + + @Override + protected void postProcess(Object eventObject, OutputStream sw) { + if (throwableExcluded) + return; + + ILoggingEvent event = (ILoggingEvent) eventObject; + IThrowableProxy tp = event.getThrowableProxy(); + + if (tp == null) + return; + + String stackTracePrefix = stackTraceLayout.doLayout(event); + boolean isRootException = true; + while (tp != null) { + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + try { + handleThrowableFirstLine(sw, tp, stackTracePrefix, isRootException); + isRootException = false; + for (StackTraceElementProxy step : stepArray) { + StringBuilder sb = new StringBuilder(); + sb.append(stackTracePrefix).append(step); + sw.write(sb.toString().getBytes()); + sw.flush(); + } + } catch (IOException e) { + break; + } + tp = tp.getCause(); + } + } + + // LOGBACK-411 and LOGBACK-750 + private void handleThrowableFirstLine(OutputStream sw, IThrowableProxy tp, String stackTracePrefix, boolean isRootException) throws IOException { + StringBuilder sb = new StringBuilder().append(stackTracePrefix); + + if (!isRootException) { + sb.append(CoreConstants.CAUSED_BY); + } + sb.append(tp.getClassName()).append(": ").append(tp.getMessage()); + sw.write(sb.toString().getBytes()); + sw.flush(); + } + + boolean stackTraceHeaderLine(StringBuilder sb, boolean topException) { + + return false; + } + + public Layout buildLayout() { + PatternLayout layout = new PatternLayout(); + layout.getInstanceConverterMap().put("syslogStart", SyslogStartConverter.class.getName()); + if (suffixPattern == null) { + suffixPattern = DEFAULT_SUFFIX_PATTERN; } - } catch (IOException e) { - break; - } - tp = tp.getCause(); + layout.setPattern(getPrefixPattern() + suffixPattern); + layout.setContext(getContext()); + layout.start(); + return layout; } - } - // LOGBACK-411 and LOGBACK-750 - private void handleThrowableFirstLine(OutputStream sw, IThrowableProxy tp, String stackTracePrefix, boolean isRootException) throws IOException { - StringBuilder sb = new StringBuilder().append(stackTracePrefix); + private void setupStackTraceLayout() { + stackTraceLayout.getInstanceConverterMap().put("syslogStart", SyslogStartConverter.class.getName()); - if (!isRootException) { - sb.append(CoreConstants.CAUSED_BY); + stackTraceLayout.setPattern(getPrefixPattern() + stackTracePattern); + stackTraceLayout.setContext(getContext()); + stackTraceLayout.start(); } - sb.append(tp.getClassName()).append(": ").append(tp.getMessage()); - sw.write(sb.toString().getBytes()); - sw.flush(); - } - - boolean stackTraceHeaderLine(StringBuilder sb, boolean topException) { - - return false; - } - - public Layout buildLayout() { - PatternLayout layout = new PatternLayout(); - layout.getInstanceConverterMap().put("syslogStart", - SyslogStartConverter.class.getName()); - if (suffixPattern == null) { - suffixPattern = DEFAULT_SUFFIX_PATTERN; + + public boolean isThrowableExcluded() { + return throwableExcluded; + } + + /** + * Setting throwableExcluded to true causes no Throwable's stack trace data to be sent to + * the syslog daemon. By default, stack trace data is sent to syslog daemon. + * + * @param throwableExcluded + * @since 1.0.4 + */ + public void setThrowableExcluded(boolean throwableExcluded) { + this.throwableExcluded = throwableExcluded; + } + + /** + * See {@link #setStackTracePattern(String). + * + * @return the stackTraceSuffixPattern + * @since 1.0.4 + */ + public String getStackTracePattern() { + return stackTracePattern; + } + + /** + * Stack trace lines are sent to the syslog server separately from the main message + * For stack trace lines, the stackTracePattern is used instead of {@link #suffixPattern}. + * The stackTracePattern option allows specification of a separately format for the + * non-standardized part of stack trace lines. + * + * @param stackTracePattern + * @since 1.0.4 + */ + public void setStackTracePattern(String stackTracePattern) { + this.stackTracePattern = stackTracePattern; } - layout.setPattern(getPrefixPattern() + suffixPattern); - layout.setContext(getContext()); - layout.start(); - return layout; - } - - private void setupStackTraceLayout() { - stackTraceLayout.getInstanceConverterMap().put("syslogStart", - SyslogStartConverter.class.getName()); - - stackTraceLayout.setPattern(getPrefixPattern() + stackTracePattern); - stackTraceLayout.setContext(getContext()); - stackTraceLayout.start(); - } - - public boolean isThrowableExcluded() { - return throwableExcluded; - } - - /** - * Setting throwableExcluded to true causes no Throwable's stack trace data to be sent to - * the syslog daemon. By default, stack trace data is sent to syslog daemon. - * - * @param throwableExcluded - * @since 1.0.4 - */ - public void setThrowableExcluded(boolean throwableExcluded) { - this.throwableExcluded = throwableExcluded; - } - - /** - * See {@link #setStackTracePattern(String). - * - * @return the stackTraceSuffixPattern - * @since 1.0.4 - */ - public String getStackTracePattern() { - return stackTracePattern; - } - - /** - * Stack trace lines are sent to the syslog server separately from the main message - * For stack trace lines, the stackTracePattern is used instead of {@link #suffixPattern}. - * The stackTracePattern option allows specification of a separately format for the - * non-standardized part of stack trace lines. - * - * @param stackTracePattern - * @since 1.0.4 - */ - public void setStackTracePattern(String stackTracePattern) { - this.stackTracePattern = stackTracePattern; - } } \ No newline at end of file diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderClient.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderClient.java index 9c3d3843004d6dfa7a24644cc976838e191db22a..12aa3a4713a00f0a98469a8fa481bc5e11ec96f4 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderClient.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderClient.java @@ -17,7 +17,6 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.net.server.Client; import ch.qos.logback.core.net.server.ServerRunner; - /** * A client of a {@link ServerRunner} that receives events from a remote * appender. @@ -26,16 +25,16 @@ import ch.qos.logback.core.net.server.ServerRunner; */ interface RemoteAppenderClient extends Client { - /** - * Sets the client's logger context. - *

- * This provides the local logging context to the client's service thread, - * and is used as the destination for logging events received from the - * client. - *

- * This method must be invoked before the {@link #run()} method. - * @param lc the logger context to set - */ - void setLoggerContext(LoggerContext lc); - + /** + * Sets the client's logger context. + *

+ * This provides the local logging context to the client's service thread, + * and is used as the destination for logging events received from the + * client. + *

+ * This method must be invoked before the {@link #run()} method. + * @param lc the logger context to set + */ + void setLoggerContext(LoggerContext lc); + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerListener.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerListener.java index 0235502e702185dabcc7e88aa0b418e7b59217cf..3320ee8842238227b8e7683d9878cae86be2ea63 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerListener.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerListener.java @@ -25,25 +25,23 @@ import ch.qos.logback.core.net.server.ServerSocketListener; * * @author Carl Harris */ -class RemoteAppenderServerListener - extends ServerSocketListener { +class RemoteAppenderServerListener extends ServerSocketListener { - /** - * Constructs a new listener. - * @param serverSocket the {@link ServerSocket} from which to accept - * new client connections - */ - public RemoteAppenderServerListener(ServerSocket serverSocket) { - super(serverSocket); - } + /** + * Constructs a new listener. + * @param serverSocket the {@link ServerSocket} from which to accept + * new client connections + */ + public RemoteAppenderServerListener(ServerSocket serverSocket) { + super(serverSocket); + } - /** - * {@inheritDoc} - */ - @Override - protected RemoteAppenderClient createClient(String id, Socket socket) - throws IOException { - return new RemoteAppenderStreamClient(id, socket); - } + /** + * {@inheritDoc} + */ + @Override + protected RemoteAppenderClient createClient(String id, Socket socket) throws IOException { + return new RemoteAppenderStreamClient(id, socket); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java index 9f837e7728781eb21675680dd9b331d853bc66ba..2f78e3b3d9f6a854aa110efe1000fbf9e10a5962 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderServerRunner.java @@ -26,28 +26,26 @@ import ch.qos.logback.core.net.server.ServerRunner; * * @author Carl Harris */ -class RemoteAppenderServerRunner - extends ConcurrentServerRunner { +class RemoteAppenderServerRunner extends ConcurrentServerRunner { - /** - * Constructs a new server runner. - * @param listener the listener from which the server will accept new - * clients - * @param executor that will be used to execute asynchronous tasks - * on behalf of the runner. - */ - public RemoteAppenderServerRunner( - ServerListener listener, Executor executor) { - super(listener, executor); - } + /** + * Constructs a new server runner. + * @param listener the listener from which the server will accept new + * clients + * @param executor that will be used to execute asynchronous tasks + * on behalf of the runner. + */ + public RemoteAppenderServerRunner(ServerListener listener, Executor executor) { + super(listener, executor); + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean configureClient(RemoteAppenderClient client) { + client.setLoggerContext((LoggerContext) getContext()); + return true; + } - /** - * {@inheritDoc} - */ - @Override - protected boolean configureClient(RemoteAppenderClient client) { - client.setLoggerContext((LoggerContext) getContext()); - return true; - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClient.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClient.java index 07f268f3e7ea5bb71c173bc9e75bb136a7d5d8b2..4221e9d12d08c02ac822bed3fae8db07efa862db 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClient.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClient.java @@ -32,111 +32,107 @@ import ch.qos.logback.core.util.CloseUtil; */ class RemoteAppenderStreamClient implements RemoteAppenderClient { - private final String id; - private final Socket socket; - private final InputStream inputStream; - - private LoggerContext lc; - private Logger logger; - - /** - * Constructs a new client. - * @param id a display name for the client - * @param inputStream input stream from which events will be read - */ - public RemoteAppenderStreamClient(String id, Socket socket) { - this.id = id; - this.socket = socket; - this.inputStream = null; - } + private final String id; + private final Socket socket; + private final InputStream inputStream; - /** - * Constructs a new client. - *

- * This constructor is provided primarily to support unit tests for which - * it is inconvenient to create a socket. - * - * @param id a display name for the client - * @param inputStream input stream from which events will be read - */ - public RemoteAppenderStreamClient(String id, InputStream inputStream) { - this.id = id; - this.socket = null; - this.inputStream = inputStream; - } + private LoggerContext lc; + private Logger logger; - /** - * {@inheritDoc} - */ - public void setLoggerContext(LoggerContext lc) { - this.lc = lc; - this.logger = lc.getLogger(getClass().getPackage().getName()); - } - - /** - * {@inheritDoc} - */ - public void close() { - if (socket == null) return; - CloseUtil.closeQuietly(socket); - } - - /** - * {@inheritDoc} - */ - public void run() { - logger.info(this + ": connected"); - ObjectInputStream ois = null; - try { - ois = createObjectInputStream(); - while (true) { - // read an event from the wire - ILoggingEvent event = (ILoggingEvent) ois.readObject(); - // get a logger from the hierarchy. The name of the logger is taken to - // be the name contained in the event. - Logger remoteLogger = lc.getLogger(event.getLoggerName()); - // apply the logger-level filter - if (remoteLogger.isEnabledFor(event.getLevel())) { - // finally log the event as if was generated locally - remoteLogger.callAppenders(event); - } - } + /** + * Constructs a new client. + * @param id a display name for the client + * @param inputStream input stream from which events will be read + */ + public RemoteAppenderStreamClient(String id, Socket socket) { + this.id = id; + this.socket = socket; + this.inputStream = null; } - catch (EOFException ex) { - // this is normal and expected - assert true; + + /** + * Constructs a new client. + *

+ * This constructor is provided primarily to support unit tests for which + * it is inconvenient to create a socket. + * + * @param id a display name for the client + * @param inputStream input stream from which events will be read + */ + public RemoteAppenderStreamClient(String id, InputStream inputStream) { + this.id = id; + this.socket = null; + this.inputStream = inputStream; } - catch (IOException ex) { - logger.info(this + ": " + ex); + + /** + * {@inheritDoc} + */ + public void setLoggerContext(LoggerContext lc) { + this.lc = lc; + this.logger = lc.getLogger(getClass().getPackage().getName()); } - catch (ClassNotFoundException ex) { - logger.error(this + ": unknown event class"); + + /** + * {@inheritDoc} + */ + public void close() { + if (socket == null) + return; + CloseUtil.closeQuietly(socket); } - catch (RuntimeException ex) { - logger.error(this + ": " + ex); + + /** + * {@inheritDoc} + */ + public void run() { + logger.info(this + ": connected"); + ObjectInputStream ois = null; + try { + ois = createObjectInputStream(); + while (true) { + // read an event from the wire + ILoggingEvent event = (ILoggingEvent) ois.readObject(); + // get a logger from the hierarchy. The name of the logger is taken to + // be the name contained in the event. + Logger remoteLogger = lc.getLogger(event.getLoggerName()); + // apply the logger-level filter + if (remoteLogger.isEnabledFor(event.getLevel())) { + // finally log the event as if was generated locally + remoteLogger.callAppenders(event); + } + } + } catch (EOFException ex) { + // this is normal and expected + assert true; + } catch (IOException ex) { + logger.info(this + ": " + ex); + } catch (ClassNotFoundException ex) { + logger.error(this + ": unknown event class"); + } catch (RuntimeException ex) { + logger.error(this + ": " + ex); + } finally { + if (ois != null) { + CloseUtil.closeQuietly(ois); + } + close(); + logger.info(this + ": connection closed"); + } } - finally { - if (ois != null) { - CloseUtil.closeQuietly(ois); - } - close(); - logger.info(this + ": connection closed"); + + private ObjectInputStream createObjectInputStream() throws IOException { + if (inputStream != null) { + return new ObjectInputStream(inputStream); + } + return new ObjectInputStream(socket.getInputStream()); } - } - private ObjectInputStream createObjectInputStream() throws IOException { - if (inputStream != null) { - return new ObjectInputStream(inputStream); + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "client " + id; } - return new ObjectInputStream(socket.getInputStream()); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "client " + id; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketAppender.java index 0261139f6d4266e944c10a72e598169adfcd54b4..1baed299ebdf0cdbadca741abed1b84b1893cd49 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketAppender.java @@ -23,32 +23,30 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * * @author Carl Harris */ -public class SSLServerSocketAppender - extends SSLServerSocketAppenderBase { - - private static final PreSerializationTransformer pst = - new LoggingEventPreSerializationTransformer(); - - private boolean includeCallerData; - - @Override - protected void postProcessEvent(ILoggingEvent event) { - if (isIncludeCallerData()) { - event.getCallerData(); +public class SSLServerSocketAppender extends SSLServerSocketAppenderBase { + + private static final PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + private boolean includeCallerData; + + @Override + protected void postProcessEvent(ILoggingEvent event) { + if (isIncludeCallerData()) { + event.getCallerData(); + } } - } - @Override - protected PreSerializationTransformer getPST() { - return pst; - } + @Override + protected PreSerializationTransformer getPST() { + return pst; + } - public boolean isIncludeCallerData() { - return includeCallerData; - } + public boolean isIncludeCallerData() { + return includeCallerData; + } - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiver.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiver.java index 2b72ef0b5ec271665a34f6338a10c99fff362102..34fb28e40d69caa404cdba8d72065ef060635e92 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiver.java @@ -26,45 +26,43 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; * * @author Carl Harris */ -public class SSLServerSocketReceiver extends ServerSocketReceiver - implements SSLComponent { +public class SSLServerSocketReceiver extends ServerSocketReceiver implements SSLComponent { - private SSLConfiguration ssl; - private ServerSocketFactory socketFactory; - - /** - * {@inheritDoc} - */ - @Override - protected ServerSocketFactory getServerSocketFactory() throws Exception { - if (socketFactory == null) { - SSLContext sslContext = getSsl().createContext(this); - SSLParametersConfiguration parameters = getSsl().getParameters(); - parameters.setContext(getContext()); - socketFactory = new ConfigurableSSLServerSocketFactory( - parameters, sslContext.getServerSocketFactory()); + private SSLConfiguration ssl; + private ServerSocketFactory socketFactory; + + /** + * {@inheritDoc} + */ + @Override + protected ServerSocketFactory getServerSocketFactory() throws Exception { + if (socketFactory == null) { + SSLContext sslContext = getSsl().createContext(this); + SSLParametersConfiguration parameters = getSsl().getParameters(); + parameters.setContext(getContext()); + socketFactory = new ConfigurableSSLServerSocketFactory(parameters, sslContext.getServerSocketFactory()); + } + return socketFactory; } - return socketFactory; - } - /** - * Gets the server's SSL configuration. - * @return SSL configuration; if no SSL configuration was provided - * a default configuration is returned - */ - public SSLConfiguration getSsl() { - if (ssl == null) { - ssl = new SSLConfiguration(); + /** + * Gets the server's SSL configuration. + * @return SSL configuration; if no SSL configuration was provided + * a default configuration is returned + */ + public SSLConfiguration getSsl() { + if (ssl == null) { + ssl = new SSLConfiguration(); + } + return ssl; } - return ssl; - } - /** - * Gets the server's SSL configuration. - * @param ssl the SSL configuration to set. - */ - public void setSsl(SSLConfiguration ssl) { - this.ssl = ssl; - } + /** + * Gets the server's SSL configuration. + * @param ssl the SSL configuration to set. + */ + public void setSsl(SSLConfiguration ssl) { + this.ssl = ssl; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketAppender.java index c906ab7d4bc18a9d01759d0bf239723bba4639b5..ca93d6c5ca11f7cce5987a810f437c5087bf52a6 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketAppender.java @@ -25,32 +25,30 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * * @author Carl Harris */ -public class ServerSocketAppender - extends AbstractServerSocketAppender { - - private static final PreSerializationTransformer pst = - new LoggingEventPreSerializationTransformer(); - - private boolean includeCallerData; - - @Override - protected void postProcessEvent(ILoggingEvent event) { - if (isIncludeCallerData()) { - event.getCallerData(); +public class ServerSocketAppender extends AbstractServerSocketAppender { + + private static final PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + private boolean includeCallerData; + + @Override + protected void postProcessEvent(ILoggingEvent event) { + if (isIncludeCallerData()) { + event.getCallerData(); + } } - } - @Override - protected PreSerializationTransformer getPST() { - return pst; - } + @Override + protected PreSerializationTransformer getPST() { + return pst; + } - public boolean isIncludeCallerData() { - return includeCallerData; - } + public boolean isIncludeCallerData() { + return includeCallerData; + } - public void setIncludeCallerData(boolean includeCallerData) { - this.includeCallerData = includeCallerData; - } + public void setIncludeCallerData(boolean includeCallerData) { + this.includeCallerData = includeCallerData; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketReceiver.java b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketReceiver.java index 7fd84232420986f3777a0f77eac2775abfcf8a79..2122ae9d678de71b2633ae441e56c3986ce9ecd2 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketReceiver.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/net/server/ServerSocketReceiver.java @@ -33,146 +33,141 @@ import ch.qos.logback.core.util.CloseUtil; * @author Carl Harris */ public class ServerSocketReceiver extends ReceiverBase { - - /** - * Default {@link ServerSocket} backlog - */ - public static final int DEFAULT_BACKLOG = 50; - - private int port = AbstractSocketAppender.DEFAULT_PORT; - private int backlog = DEFAULT_BACKLOG; - - private String address; - - private ServerSocket serverSocket; - private ServerRunner runner; - - /** - * Starts the server. - */ - protected boolean shouldStart() { - try { - ServerSocket serverSocket = getServerSocketFactory().createServerSocket( - getPort(), getBacklog(), getInetAddress()); - - ServerListener listener = - createServerListener(serverSocket); - - runner = createServerRunner(listener, getContext().getExecutorService()); - runner.setContext(getContext()); - return true; + + /** + * Default {@link ServerSocket} backlog + */ + public static final int DEFAULT_BACKLOG = 50; + + private int port = AbstractSocketAppender.DEFAULT_PORT; + private int backlog = DEFAULT_BACKLOG; + + private String address; + + private ServerSocket serverSocket; + private ServerRunner runner; + + /** + * Starts the server. + */ + protected boolean shouldStart() { + try { + ServerSocket serverSocket = getServerSocketFactory().createServerSocket(getPort(), getBacklog(), getInetAddress()); + + ServerListener listener = createServerListener(serverSocket); + + runner = createServerRunner(listener, getContext().getExecutorService()); + runner.setContext(getContext()); + return true; + } catch (Exception ex) { + addError("server startup error: " + ex, ex); + CloseUtil.closeQuietly(serverSocket); + return false; + } + } + + protected ServerListener createServerListener(ServerSocket socket) { + return new RemoteAppenderServerListener(socket); + } + + protected ServerRunner createServerRunner(ServerListener listener, Executor executor) { + return new RemoteAppenderServerRunner(listener, executor); + } + + @Override + protected Runnable getRunnableTask() { + return runner; + } + + /** + * {@inheritDoc} + */ + protected void onStop() { + try { + if (runner == null) + return; + runner.stop(); + } catch (IOException ex) { + addError("server shutdown error: " + ex, ex); + } + } + + /** + * Gets the server socket factory. + *

+ * Subclasses may override to provide a custom factory. + * @return server socket factory + * @throws Exception + */ + protected ServerSocketFactory getServerSocketFactory() throws Exception { + return ServerSocketFactory.getDefault(); + } + + /** + * Gets the local address for the listener. + * @return an {@link InetAddress} representation of the local address. + * @throws UnknownHostException + */ + protected InetAddress getInetAddress() throws UnknownHostException { + if (getAddress() == null) + return null; + return InetAddress.getByName(getAddress()); + } + + /** + * Gets the local port for the listener. + * @return local port + */ + public int getPort() { + return port; } - catch (Exception ex) { - addError("server startup error: " + ex, ex); - CloseUtil.closeQuietly(serverSocket); - return false; + + /** + * Sets the local port for the listener. + * @param port the local port to set + */ + public void setPort(int port) { + this.port = port; + } + + /** + * Gets the listener queue depth. + *

+ * This represents the number of connected clients whose connections + * have not yet been accepted. + * @return queue depth + * @see java.net.ServerSocket + */ + public int getBacklog() { + return backlog; } - } - - protected ServerListener createServerListener( - ServerSocket socket) { - return new RemoteAppenderServerListener(socket); - } - - protected ServerRunner createServerRunner( - ServerListener listener, - Executor executor) { - return new RemoteAppenderServerRunner(listener, executor); - } - - @Override - protected Runnable getRunnableTask() { - return runner; - } - - /** - * {@inheritDoc} - */ - protected void onStop() { - try { - if (runner == null) return; - runner.stop(); + + /** + * Sets the listener queue depth. + *

+ * This represents the number of connected clients whose connections + * have not yet been accepted. + * @param backlog the queue depth to set + * @see java.net.ServerSocket + */ + public void setBacklog(int backlog) { + this.backlog = backlog; } - catch (IOException ex) { - addError("server shutdown error: " + ex, ex); + + /** + * Gets the local address for the listener. + * @return a string representation of the local address + */ + public String getAddress() { + return address; + } + + /** + * Sets the local address for the listener. + * @param address a host name or a string representation of an IP address + */ + public void setAddress(String address) { + this.address = address; } - } - - /** - * Gets the server socket factory. - *

- * Subclasses may override to provide a custom factory. - * @return server socket factory - * @throws Exception - */ - protected ServerSocketFactory getServerSocketFactory() throws Exception { - return ServerSocketFactory.getDefault(); - } - - /** - * Gets the local address for the listener. - * @return an {@link InetAddress} representation of the local address. - * @throws UnknownHostException - */ - protected InetAddress getInetAddress() throws UnknownHostException { - if (getAddress() == null) return null; - return InetAddress.getByName(getAddress()); - } - - /** - * Gets the local port for the listener. - * @return local port - */ - public int getPort() { - return port; - } - - /** - * Sets the local port for the listener. - * @param port the local port to set - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Gets the listener queue depth. - *

- * This represents the number of connected clients whose connections - * have not yet been accepted. - * @return queue depth - * @see java.net.ServerSocket - */ - public int getBacklog() { - return backlog; - } - - /** - * Sets the listener queue depth. - *

- * This represents the number of connected clients whose connections - * have not yet been accepted. - * @param backlog the queue depth to set - * @see java.net.ServerSocket - */ - public void setBacklog(int backlog) { - this.backlog = backlog; - } - - /** - * Gets the local address for the listener. - * @return a string representation of the local address - */ - public String getAddress() { - return address; - } - - /** - * Sets the local address for the listener. - * @param address a host name or a string representation of an IP address - */ - public void setAddress(String address) { - this.address = address; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Abbreviator.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Abbreviator.java index ed583617f6e877b3265134a8a511f6f648ef4d56..177cbea0774a7200e7dcd6f0c15136561a352af0 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Abbreviator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Abbreviator.java @@ -20,5 +20,5 @@ package ch.qos.logback.classic.pattern; */ public interface Abbreviator { - String abbreviate(String in); + String abbreviate(String in); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassNameOnlyAbbreviator.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassNameOnlyAbbreviator.java index af3a7372a17129a0511229306ea7620ac7529212..040e2aa8a9542fa28977e6ea68a0e7fd1dee6e47 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassNameOnlyAbbreviator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassNameOnlyAbbreviator.java @@ -23,15 +23,15 @@ import ch.qos.logback.core.CoreConstants; */ public class ClassNameOnlyAbbreviator implements Abbreviator { - public String abbreviate(String fqClassName) { - // we ignore the fact that the separator character can also be a dollar - // If the inner class is org.good.AClass#Inner, returning - // AClass#Inner seems most appropriate - int lastIndex = fqClassName.lastIndexOf(CoreConstants.DOT); - if (lastIndex != -1) { - return fqClassName.substring(lastIndex + 1, fqClassName.length()); - } else { - return fqClassName; + public String abbreviate(String fqClassName) { + // we ignore the fact that the separator character can also be a dollar + // If the inner class is org.good.AClass#Inner, returning + // AClass#Inner seems most appropriate + int lastIndex = fqClassName.lastIndexOf(CoreConstants.DOT); + if (lastIndex != -1) { + return fqClassName.substring(lastIndex + 1, fqClassName.length()); + } else { + return fqClassName; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassOfCallerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassOfCallerConverter.java index d24ce36beaa8ce80fb6e98503a59f437d7f1f886..6d491475122f8bd10eec4f1ae55ad3691123524a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassOfCallerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassOfCallerConverter.java @@ -18,13 +18,13 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class ClassOfCallerConverter extends NamedConverter { - protected String getFullyQualifiedName(ILoggingEvent event) { - - StackTraceElement[] cda = event.getCallerData(); - if (cda != null && cda.length > 0) { - return cda[0].getClassName(); - } else { - return CallerData.NA; + protected String getFullyQualifiedName(ILoggingEvent event) { + + StackTraceElement[] cda = event.getCallerData(); + if (cda != null && cda.length > 0) { + return cda[0].getClassName(); + } else { + return CallerData.NA; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassicConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassicConverter.java index d946e230177d4ecfce9042362b1374de1d9f9d31..b0103cba9e415d0b5033cab2d111895e87384cc7 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassicConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ClassicConverter.java @@ -22,6 +22,6 @@ import ch.qos.logback.core.pattern.DynamicConverter; * * @author Ceki Gulcu */ -abstract public class ClassicConverter extends DynamicConverter { +abstract public class ClassicConverter extends DynamicConverter { } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ContextNameConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ContextNameConverter.java index 1db74da317d8d7578032e27a9f9851986c7aa792..5a5b69230c62e385ac8c7c5351b04bda5fa53baf 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ContextNameConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ContextNameConverter.java @@ -22,11 +22,11 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class ContextNameConverter extends ClassicConverter { - /** - * Return the name of the logger context's name. - */ - public String convert(ILoggingEvent event) { - return event.getLoggerContextVO().getName(); - } + /** + * Return the name of the logger context's name. + */ + public String convert(ILoggingEvent event) { + return event.getLoggerContextVO().getName(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/DateConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/DateConverter.java index 8cbb01dcbe18878fb5a2a1a679c53c50f00e5de7..6ae752104b14683a90e7ff92cd3485758d569bce 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/DateConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/DateConverter.java @@ -22,44 +22,42 @@ import ch.qos.logback.core.util.CachingDateFormatter; public class DateConverter extends ClassicConverter { - long lastTimestamp = -1; - String timestampStrCache = null; - CachingDateFormatter cachingDateFormatter = null; - - public void start() { - - - String datePattern = getFirstOption(); - if (datePattern == null) { - datePattern = CoreConstants.ISO8601_PATTERN; - } - - if (datePattern.equals(CoreConstants.ISO8601_STR)) { - datePattern = CoreConstants.ISO8601_PATTERN; + long lastTimestamp = -1; + String timestampStrCache = null; + CachingDateFormatter cachingDateFormatter = null; + + public void start() { + + String datePattern = getFirstOption(); + if (datePattern == null) { + datePattern = CoreConstants.ISO8601_PATTERN; + } + + if (datePattern.equals(CoreConstants.ISO8601_STR)) { + datePattern = CoreConstants.ISO8601_PATTERN; + } + + try { + cachingDateFormatter = new CachingDateFormatter(datePattern); + // maximumCacheValidity = + // CachedDateFormat.getMaximumCacheValidity(pattern); + } catch (IllegalArgumentException e) { + addWarn("Could not instantiate SimpleDateFormat with pattern " + datePattern, e); + // default to the ISO8601 format + cachingDateFormatter = new CachingDateFormatter(CoreConstants.ISO8601_PATTERN); + } + + List optionList = getOptionList(); + + // if the option list contains a TZ option, then set it. + if (optionList != null && optionList.size() > 1) { + TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1)); + cachingDateFormatter.setTimeZone(tz); + } } - try { - cachingDateFormatter = new CachingDateFormatter(datePattern); - // maximumCacheValidity = - // CachedDateFormat.getMaximumCacheValidity(pattern); - } catch (IllegalArgumentException e) { - addWarn("Could not instantiate SimpleDateFormat with pattern " - + datePattern, e); - // default to the ISO8601 format - cachingDateFormatter = new CachingDateFormatter(CoreConstants.ISO8601_PATTERN); + public String convert(ILoggingEvent le) { + long timestamp = le.getTimeStamp(); + return cachingDateFormatter.format(timestamp); } - - List optionList = getOptionList(); - - // if the option list contains a TZ option, then set it. - if (optionList != null && optionList.size() > 1) { - TimeZone tz = TimeZone.getTimeZone((String) optionList.get(1)); - cachingDateFormatter.setTimeZone(tz); - } - } - - public String convert(ILoggingEvent le) { - long timestamp = le.getTimeStamp(); - return cachingDateFormatter.format(timestamp); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/EnsureExceptionHandling.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/EnsureExceptionHandling.java index a867105e27ccb3180525751eb15023364f529cae..e3f23022a41e5858eeb80c20705c010a8f614afa 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/EnsureExceptionHandling.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/EnsureExceptionHandling.java @@ -20,58 +20,57 @@ import ch.qos.logback.core.pattern.Converter; import ch.qos.logback.core.pattern.ConverterUtil; import ch.qos.logback.core.pattern.PostCompileProcessor; -public class EnsureExceptionHandling implements - PostCompileProcessor { +public class EnsureExceptionHandling implements PostCompileProcessor { - /** - * This implementation checks if any of the converters in the chain handles - * exceptions. If not, then this method adds a - * {@link ExtendedThrowableProxyConverter} instance to the end of the chain. - *

- * This allows appenders using this layout to output exception information - * event if the user forgets to add %ex to the pattern. Note that the - * appenders defined in the Core package are not aware of exceptions nor - * LoggingEvents. - *

- * If for some reason the user wishes to NOT print exceptions, then she can - * add %nopex to the pattern. - * - * - */ - public void process(Context context, Converter head) { - if(head == null) { - // this should never happen - throw new IllegalArgumentException("cannot process empty chain"); + /** + * This implementation checks if any of the converters in the chain handles + * exceptions. If not, then this method adds a + * {@link ExtendedThrowableProxyConverter} instance to the end of the chain. + *

+ * This allows appenders using this layout to output exception information + * event if the user forgets to add %ex to the pattern. Note that the + * appenders defined in the Core package are not aware of exceptions nor + * LoggingEvents. + *

+ * If for some reason the user wishes to NOT print exceptions, then she can + * add %nopex to the pattern. + * + * + */ + public void process(Context context, Converter head) { + if (head == null) { + // this should never happen + throw new IllegalArgumentException("cannot process empty chain"); + } + if (!chainHandlesThrowable(head)) { + Converter tail = ConverterUtil.findTail(head); + Converter exConverter = null; + LoggerContext loggerContext = (LoggerContext) context; + if (loggerContext.isPackagingDataEnabled()) { + exConverter = new ExtendedThrowableProxyConverter(); + } else { + exConverter = new ThrowableProxyConverter(); + } + tail.setNext(exConverter); + } } - if (!chainHandlesThrowable(head)) { - Converter tail = ConverterUtil.findTail(head); - Converter exConverter = null; - LoggerContext loggerContext = (LoggerContext) context; - if(loggerContext.isPackagingDataEnabled()) { - exConverter = new ExtendedThrowableProxyConverter(); - } else { - exConverter = new ThrowableProxyConverter(); - } - tail.setNext(exConverter); - } - } - /** - * This method computes whether a chain of converters handles exceptions or - * not. - * - * @param head - * The first element of the chain - * @return true if can handle throwables contained in logging events - */ - public boolean chainHandlesThrowable(Converter head) { - Converter c = head; - while (c != null) { - if (c instanceof ThrowableHandlingConverter) { - return true; - } - c = c.getNext(); + /** + * This method computes whether a chain of converters handles exceptions or + * not. + * + * @param head + * The first element of the chain + * @return true if can handle throwables contained in logging events + */ + public boolean chainHandlesThrowable(Converter head) { + Converter c = head; + while (c != null) { + if (c instanceof ThrowableHandlingConverter) { + return true; + } + c = c.getNext(); + } + return false; } - return false; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverter.java index 11b3d856adee55ae79cec4446f4b8dd5360ac581..ea7387d7e445dc82fec327cb906eb607215b2b1b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverter.java @@ -19,13 +19,13 @@ import ch.qos.logback.classic.spi.ThrowableProxyUtil; public class ExtendedThrowableProxyConverter extends ThrowableProxyConverter { - @Override - protected void extraData(StringBuilder builder, StackTraceElementProxy step) { - ThrowableProxyUtil.subjoinPackagingData(builder, step); - } + @Override + protected void extraData(StringBuilder builder, StackTraceElementProxy step) { + ThrowableProxyUtil.subjoinPackagingData(builder, step); + } - protected void prepareLoggingEvent(ILoggingEvent event) { - - } + protected void prepareLoggingEvent(ILoggingEvent event) { + + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/FileOfCallerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/FileOfCallerConverter.java index 06149fce492a8a618cfed8f7cd41c8bc9d9b3b62..8783f746be3793b1330707de9b97c9c0e55af0fc 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/FileOfCallerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/FileOfCallerConverter.java @@ -18,13 +18,13 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class FileOfCallerConverter extends ClassicConverter { - public String convert(ILoggingEvent le) { - StackTraceElement[] cda = le.getCallerData(); - if (cda != null && cda.length > 0) { - return cda[0].getFileName(); - } else { - return CallerData.NA; + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + return cda[0].getFileName(); + } else { + return CallerData.NA; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LevelConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LevelConverter.java index 75fc7d6339ee5b8a9558fc1989f2ecc684e78804..f772254105ed407b0f6b1410d9934bd39ffbf86e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LevelConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LevelConverter.java @@ -22,8 +22,8 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class LevelConverter extends ClassicConverter { - public String convert(ILoggingEvent le) { - return le.getLevel().toString(); - } + public String convert(ILoggingEvent le) { + return le.getLevel().toString(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineOfCallerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineOfCallerConverter.java index 5afd14847ce109cfa0d90d5198bff66a2b42cc26..385a784febb1dc4bad21b4d7b7435cd9c7c37c99 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineOfCallerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineOfCallerConverter.java @@ -18,13 +18,13 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class LineOfCallerConverter extends ClassicConverter { - public String convert(ILoggingEvent le) { - StackTraceElement[] cda = le.getCallerData(); - if (cda != null && cda.length > 0) { - return Integer.toString(cda[0].getLineNumber()); - } else { - return CallerData.NA; + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + return Integer.toString(cda[0].getLineNumber()); + } else { + return CallerData.NA; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineSeparatorConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineSeparatorConverter.java index 41fde8a77243b98a4c0e8e151e1071faf1bea6ee..e0bb1dcbfdc1a538f70182033367327e6a91ac53 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineSeparatorConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LineSeparatorConverter.java @@ -18,8 +18,8 @@ import ch.qos.logback.core.CoreConstants; public class LineSeparatorConverter extends ClassicConverter { - public String convert(ILoggingEvent event) { - return CoreConstants.LINE_SEPARATOR; - } + public String convert(ILoggingEvent event) { + return CoreConstants.LINE_SEPARATOR; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LocalSequenceNumberConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LocalSequenceNumberConverter.java index fda9d9caff8c7be63b30a58b491aa85faad4af01..db72b8261a59d8a153d4fda0cb84b2225034cd84 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LocalSequenceNumberConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LocalSequenceNumberConverter.java @@ -27,10 +27,10 @@ import java.util.concurrent.atomic.AtomicLong; */ public class LocalSequenceNumberConverter extends ClassicConverter { - AtomicLong sequenceNumber = new AtomicLong(System.currentTimeMillis()); + AtomicLong sequenceNumber = new AtomicLong(System.currentTimeMillis()); - @Override - public String convert(ILoggingEvent event) { - return Long.toString(sequenceNumber.getAndIncrement()); - } + @Override + public String convert(ILoggingEvent event) { + return Long.toString(sequenceNumber.getAndIncrement()); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LoggerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LoggerConverter.java index 23dcfd32728d1d546b52021e8ca12ec597961e33..011fc8e2594882702bd88473b011f0fcdeaede08 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LoggerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/LoggerConverter.java @@ -17,7 +17,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class LoggerConverter extends NamedConverter { - protected String getFullyQualifiedName(ILoggingEvent event) { - return event.getLoggerName(); - } + protected String getFullyQualifiedName(ILoggingEvent event) { + return event.getLoggerName(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MDCConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MDCConverter.java index f9ad61c265620f7cc0f3164d8b8532c992f752cf..2662da0a0d96892c19c53b301cade9c1d5aba949 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MDCConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MDCConverter.java @@ -21,61 +21,61 @@ import static ch.qos.logback.core.util.OptionHelper.extractDefaultReplacement; public class MDCConverter extends ClassicConverter { - private String key; - private String defaultValue = ""; + private String key; + private String defaultValue = ""; - @Override - public void start() { - String[] keyInfo = extractDefaultReplacement(getFirstOption()); - key = keyInfo[0]; - if (keyInfo[1] != null) { - defaultValue = keyInfo[1]; + @Override + public void start() { + String[] keyInfo = extractDefaultReplacement(getFirstOption()); + key = keyInfo[0]; + if (keyInfo[1] != null) { + defaultValue = keyInfo[1]; + } + super.start(); } - super.start(); - } - @Override - public void stop() { - key = null; - super.stop(); - } + @Override + public void stop() { + key = null; + super.stop(); + } - @Override - public String convert(ILoggingEvent event) { - Map mdcPropertyMap = event.getMDCPropertyMap(); + @Override + public String convert(ILoggingEvent event) { + Map mdcPropertyMap = event.getMDCPropertyMap(); - if (mdcPropertyMap == null) { - return defaultValue; - } + if (mdcPropertyMap == null) { + return defaultValue; + } - if (key == null) { - return outputMDCForAllKeys(mdcPropertyMap); - } else { + if (key == null) { + return outputMDCForAllKeys(mdcPropertyMap); + } else { - String value = event.getMDCPropertyMap().get(key); - if (value != null) { - return value; - } else { - return defaultValue; - } + String value = event.getMDCPropertyMap().get(key); + if (value != null) { + return value; + } else { + return defaultValue; + } + } } - } - /** - * if no key is specified, return all the values present in the MDC, in the format "k1=v1, k2=v2, ..." - */ - private String outputMDCForAllKeys(Map mdcPropertyMap) { - StringBuilder buf = new StringBuilder(); - boolean first = true; - for (Map.Entry entry : mdcPropertyMap.entrySet()) { - if (first) { - first = false; - } else { - buf.append(", "); - } - //format: key0=value0, key1=value1 - buf.append(entry.getKey()).append('=').append(entry.getValue()); + /** + * if no key is specified, return all the values present in the MDC, in the format "k1=v1, k2=v2, ..." + */ + private String outputMDCForAllKeys(Map mdcPropertyMap) { + StringBuilder buf = new StringBuilder(); + boolean first = true; + for (Map.Entry entry : mdcPropertyMap.entrySet()) { + if (first) { + first = false; + } else { + buf.append(", "); + } + // format: key0=value0, key1=value1 + buf.append(entry.getKey()).append('=').append(entry.getValue()); + } + return buf.toString(); } - return buf.toString(); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MarkerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MarkerConverter.java index 1b617abed3ea3b7216a6abd305357fd696eb13b0..61cc97a4ea122cf7f069d0cc792c875bc4bb5bbb 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MarkerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MarkerConverter.java @@ -24,15 +24,15 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class MarkerConverter extends ClassicConverter { - private static String EMPTY = ""; + private static String EMPTY = ""; - public String convert(ILoggingEvent le) { - Marker marker = le.getMarker(); - if (marker == null) { - return EMPTY; - } else { - return marker.toString(); + public String convert(ILoggingEvent le) { + Marker marker = le.getMarker(); + if (marker == null) { + return EMPTY; + } else { + return marker.toString(); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MessageConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MessageConverter.java index d1c88b862ac27de835d723fd2c1e832321271957..77c08a0a15ab231e778e85b555713d0ecb366bb6 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MessageConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MessageConverter.java @@ -22,8 +22,8 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class MessageConverter extends ClassicConverter { - public String convert(ILoggingEvent event) { - return event.getFormattedMessage(); - } + public String convert(ILoggingEvent event) { + return event.getFormattedMessage(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MethodOfCallerConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MethodOfCallerConverter.java index f6456d335ace32527c1d3acef329492caf7bc01d..5327e1ef69e4ee616a33b6b0994a9ee1971e81e7 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MethodOfCallerConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/MethodOfCallerConverter.java @@ -18,13 +18,13 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class MethodOfCallerConverter extends ClassicConverter { - public String convert(ILoggingEvent le) { - StackTraceElement[] cda = le.getCallerData(); - if (cda != null && cda.length > 0) { - return cda[0].getMethodName(); - } else { - return CallerData.NA; + public String convert(ILoggingEvent le) { + StackTraceElement[] cda = le.getCallerData(); + if (cda != null && cda.length > 0) { + return cda[0].getMethodName(); + } else { + return CallerData.NA; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NamedConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NamedConverter.java index fc5e6e64906c18dc58f7fd8ad64c8db0043ed3bc..2148b18b74a8a972f6d9dd53cd2648d64db7ffa8 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NamedConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NamedConverter.java @@ -17,40 +17,40 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public abstract class NamedConverter extends ClassicConverter { - Abbreviator abbreviator = null; + Abbreviator abbreviator = null; - /** - * Gets fully qualified name from event. - * - * @param event - * The LoggingEvent to process, cannot not be null. - * @return name, must not be null. - */ - protected abstract String getFullyQualifiedName(final ILoggingEvent event); + /** + * Gets fully qualified name from event. + * + * @param event + * The LoggingEvent to process, cannot not be null. + * @return name, must not be null. + */ + protected abstract String getFullyQualifiedName(final ILoggingEvent event); - public void start() { - String optStr = getFirstOption(); - if (optStr != null) { - try { - int targetLen = Integer.parseInt(optStr); - if (targetLen == 0) { - abbreviator = new ClassNameOnlyAbbreviator(); - } else if (targetLen > 0) { - abbreviator = new TargetLengthBasedClassNameAbbreviator(targetLen); + public void start() { + String optStr = getFirstOption(); + if (optStr != null) { + try { + int targetLen = Integer.parseInt(optStr); + if (targetLen == 0) { + abbreviator = new ClassNameOnlyAbbreviator(); + } else if (targetLen > 0) { + abbreviator = new TargetLengthBasedClassNameAbbreviator(targetLen); + } + } catch (NumberFormatException nfe) { + // FIXME: better error reporting + } } - } catch (NumberFormatException nfe) { - // FIXME: better error reporting - } } - } - public String convert(ILoggingEvent event) { - String fqn = getFullyQualifiedName(event); + public String convert(ILoggingEvent event) { + String fqn = getFullyQualifiedName(event); - if (abbreviator == null) { - return fqn; - } else { - return abbreviator.abbreviate(fqn); + if (abbreviator == null) { + return fqn; + } else { + return abbreviator.abbreviate(fqn); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NopThrowableInformationConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NopThrowableInformationConverter.java index d06f54645e971fc5f141cb54b7bbc545328829a7..b359bdd11c341b0720296db5e5c149b037df47b4 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NopThrowableInformationConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/NopThrowableInformationConverter.java @@ -17,8 +17,6 @@ import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.CoreConstants; - - /** * Always returns an empty string. *

@@ -36,8 +34,8 @@ import ch.qos.logback.core.CoreConstants; */ public class NopThrowableInformationConverter extends ThrowableHandlingConverter { - public String convert(ILoggingEvent event) { - return CoreConstants.EMPTY_STRING; - } - + public String convert(ILoggingEvent event) { + return CoreConstants.EMPTY_STRING; + } + } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/PropertyConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/PropertyConverter.java index 35d7c7b04e1972f87a7483a372a34e06bcf2ea4d..98f70050ed139faff59cf805392e07967899c477 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/PropertyConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/PropertyConverter.java @@ -20,28 +20,28 @@ import ch.qos.logback.classic.spi.LoggerContextVO; public final class PropertyConverter extends ClassicConverter { - String key; + String key; - public void start() { - String optStr = getFirstOption(); - if (optStr != null) { - key = optStr; - super.start(); + public void start() { + String optStr = getFirstOption(); + if (optStr != null) { + key = optStr; + super.start(); + } } - } - public String convert(ILoggingEvent event) { - if (key == null) { - return "Property_HAS_NO_KEY"; - } else { - LoggerContextVO lcvo = event.getLoggerContextVO(); - Map map = lcvo.getPropertyMap(); - String val = map.get(key); - if (val != null) { - return val; - } else { - return System.getProperty(key); - } + public String convert(ILoggingEvent event) { + if (key == null) { + return "Property_HAS_NO_KEY"; + } else { + LoggerContextVO lcvo = event.getLoggerContextVO(); + Map map = lcvo.getPropertyMap(); + String val = map.get(key); + if (val != null) { + return val; + } else { + return System.getProperty(key); + } + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RelativeTimeConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RelativeTimeConverter.java index 50b61f8933e626642efdc542a34225d02796dc53..2004e1927a07cf9c44eaf0fbdac3c6befe3d19df 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RelativeTimeConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RelativeTimeConverter.java @@ -17,19 +17,19 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class RelativeTimeConverter extends ClassicConverter { - long lastTimestamp = -1; - String timesmapCache = null; + long lastTimestamp = -1; + String timesmapCache = null; - public String convert(ILoggingEvent event) { - long now = event.getTimeStamp(); + public String convert(ILoggingEvent event) { + long now = event.getTimeStamp(); - synchronized (this) { - // update timesmapStrCache only if now != lastTimestamp - if (now != lastTimestamp) { - lastTimestamp = now; - timesmapCache = Long.toString(now - event.getLoggerContextVO().getBirthTime()); - } - return timesmapCache; + synchronized (this) { + // update timesmapStrCache only if now != lastTimestamp + if (now != lastTimestamp) { + lastTimestamp = now; + timesmapCache = Long.toString(now - event.getLoggerContextVO().getBirthTime()); + } + return timesmapCache; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverter.java index e664259c2bfa257eb58a193da8d876f77ebfa179..1bc4c99bf704cd7758531661cdcf51cf8d8a614b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverter.java @@ -23,30 +23,30 @@ import ch.qos.logback.core.CoreConstants; */ public class RootCauseFirstThrowableProxyConverter extends ExtendedThrowableProxyConverter { - @Override - protected String throwableProxyToString(IThrowableProxy tp) { - StringBuilder buf = new StringBuilder(BUILDER_CAPACITY); - recursiveAppendRootCauseFirst(buf, null, ThrowableProxyUtil.REGULAR_EXCEPTION_INDENT, tp); - return buf.toString(); - } - - protected void recursiveAppendRootCauseFirst(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { - if (tp.getCause() != null) { - recursiveAppendRootCauseFirst(sb, prefix, indent, tp.getCause()); - prefix = null; // to avoid adding it more than once - } - ThrowableProxyUtil.indent(sb, indent - 1); - if (prefix != null) { - sb.append(prefix); + @Override + protected String throwableProxyToString(IThrowableProxy tp) { + StringBuilder buf = new StringBuilder(BUILDER_CAPACITY); + recursiveAppendRootCauseFirst(buf, null, ThrowableProxyUtil.REGULAR_EXCEPTION_INDENT, tp); + return buf.toString(); } - ThrowableProxyUtil.subjoinFirstLineRootCauseFirst(sb, tp); - sb.append(CoreConstants.LINE_SEPARATOR); - subjoinSTEPArray(sb, indent, tp); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current : suppressed) { - recursiveAppendRootCauseFirst(sb, CoreConstants.SUPPRESSED, indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, current); - } + + protected void recursiveAppendRootCauseFirst(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { + if (tp.getCause() != null) { + recursiveAppendRootCauseFirst(sb, prefix, indent, tp.getCause()); + prefix = null; // to avoid adding it more than once + } + ThrowableProxyUtil.indent(sb, indent - 1); + if (prefix != null) { + sb.append(prefix); + } + ThrowableProxyUtil.subjoinFirstLineRootCauseFirst(sb, tp); + sb.append(CoreConstants.LINE_SEPARATOR); + subjoinSTEPArray(sb, indent, tp); + IThrowableProxy[] suppressed = tp.getSuppressed(); + if (suppressed != null) { + for (IThrowableProxy current : suppressed) { + recursiveAppendRootCauseFirst(sb, CoreConstants.SUPPRESSED, indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, current); + } + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/SyslogStartConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/SyslogStartConverter.java index 420243fd65af7420a5ef1b6f782c8ef0389ea0ca..6796f740fa73d2d11808bb940460b50d8e794da9 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/SyslogStartConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/SyslogStartConverter.java @@ -26,85 +26,86 @@ import ch.qos.logback.core.net.SyslogAppenderBase; public class SyslogStartConverter extends ClassicConverter { - long lastTimestamp = -1; - String timesmapStr = null; - SimpleDateFormat simpleMonthFormat; - SimpleDateFormat simpleTimeFormat; - private final Calendar calendar = Calendar.getInstance(Locale.US); - - String localHostName; - int facility; - - public void start() { - int errorCount = 0; - - String facilityStr = getFirstOption(); - if (facilityStr == null) { - addError("was expecting a facility string as an option"); - return; - } + long lastTimestamp = -1; + String timesmapStr = null; + SimpleDateFormat simpleMonthFormat; + SimpleDateFormat simpleTimeFormat; + private final Calendar calendar = Calendar.getInstance(Locale.US); + + String localHostName; + int facility; + + public void start() { + int errorCount = 0; + + String facilityStr = getFirstOption(); + if (facilityStr == null) { + addError("was expecting a facility string as an option"); + return; + } + + facility = SyslogAppenderBase.facilityStringToint(facilityStr); + + localHostName = getLocalHostname(); + try { + // hours should be in 0-23, see also http://jira.qos.ch/browse/LBCLASSIC-48 + simpleMonthFormat = new SimpleDateFormat("MMM", Locale.US); + simpleTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.US); + } catch (IllegalArgumentException e) { + addError("Could not instantiate SimpleDateFormat", e); + errorCount++; + } - facility = SyslogAppenderBase.facilityStringToint(facilityStr); - - localHostName = getLocalHostname(); - try { - // hours should be in 0-23, see also http://jira.qos.ch/browse/LBCLASSIC-48 - simpleMonthFormat = new SimpleDateFormat("MMM", Locale.US); - simpleTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.US); - } catch (IllegalArgumentException e) { - addError("Could not instantiate SimpleDateFormat", e); - errorCount++; + if (errorCount == 0) { + super.start(); + } } - if(errorCount == 0) { - super.start(); + public String convert(ILoggingEvent event) { + StringBuilder sb = new StringBuilder(); + + int pri = facility + LevelToSyslogSeverity.convert(event); + + sb.append("<"); + sb.append(pri); + sb.append(">"); + sb.append(computeTimeStampString(event.getTimeStamp())); + sb.append(' '); + sb.append(localHostName); + sb.append(' '); + + return sb.toString(); } - } - - public String convert(ILoggingEvent event) { - StringBuilder sb = new StringBuilder(); - - int pri = facility + LevelToSyslogSeverity.convert(event); - - sb.append("<"); - sb.append(pri); - sb.append(">"); - sb.append(computeTimeStampString(event.getTimeStamp())); - sb.append(' '); - sb.append(localHostName); - sb.append(' '); - - return sb.toString(); - } - - /** - * This method gets the network name of the machine we are running on. - * Returns "UNKNOWN_LOCALHOST" in the unlikely case where the host name - * cannot be found. - * @return String the name of the local host - */ - public String getLocalHostname() { - try { - InetAddress addr = InetAddress.getLocalHost(); - return addr.getHostName(); - } catch (UnknownHostException uhe) { - addError("Could not determine local host name", uhe); - return "UNKNOWN_LOCALHOST"; + + /** + * This method gets the network name of the machine we are running on. + * Returns "UNKNOWN_LOCALHOST" in the unlikely case where the host name + * cannot be found. + * @return String the name of the local host + */ + public String getLocalHostname() { + try { + InetAddress addr = InetAddress.getLocalHost(); + return addr.getHostName(); + } catch (UnknownHostException uhe) { + addError("Could not determine local host name", uhe); + return "UNKNOWN_LOCALHOST"; + } } - } - - String computeTimeStampString(long now) { - synchronized (this) { - // Since the formatted output is only precise to the second, we can use the same cached string if the current - // second is the same (stripping off the milliseconds). - if ((now / 1000) != lastTimestamp) { - lastTimestamp = now / 1000; - Date nowDate = new Date(now); - calendar.setTime(nowDate); - timesmapStr = String.format("%s %2d %s", simpleMonthFormat.format(nowDate), - calendar.get(Calendar.DAY_OF_MONTH), simpleTimeFormat.format(nowDate)); - } - return timesmapStr; + + String computeTimeStampString(long now) { + synchronized (this) { + // Since the formatted output is only precise to the second, we can use the same cached string if the + // current + // second is the same (stripping off the milliseconds). + if ((now / 1000) != lastTimestamp) { + lastTimestamp = now / 1000; + Date nowDate = new Date(now); + calendar.setTime(nowDate); + timesmapStr = String.format("%s %2d %s", simpleMonthFormat.format(nowDate), calendar.get(Calendar.DAY_OF_MONTH), + simpleTimeFormat.format(nowDate)); + } + return timesmapStr; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviator.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviator.java index 09e3462a9a2f9e21f2a80e64d5b5a6a2a3dfde37..3a919b36357acd3494771fba7bfab8bc8b7dc3b9 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviator.java @@ -18,111 +18,109 @@ import ch.qos.logback.core.CoreConstants; public class TargetLengthBasedClassNameAbbreviator implements Abbreviator { - final int targetLength; + final int targetLength; - public TargetLengthBasedClassNameAbbreviator(int targetLength) { - this.targetLength = targetLength; - } - - public String abbreviate(String fqClassName) { - StringBuilder buf = new StringBuilder(targetLength); - if (fqClassName == null) { - throw new IllegalArgumentException("Class name may not be null"); + public TargetLengthBasedClassNameAbbreviator(int targetLength) { + this.targetLength = targetLength; } - int inLen = fqClassName.length(); - if (inLen < targetLength) { - return fqClassName; + public String abbreviate(String fqClassName) { + StringBuilder buf = new StringBuilder(targetLength); + if (fqClassName == null) { + throw new IllegalArgumentException("Class name may not be null"); + } + + int inLen = fqClassName.length(); + if (inLen < targetLength) { + return fqClassName; + } + + int[] dotIndexesArray = new int[ClassicConstants.MAX_DOTS]; + // a.b.c contains 2 dots but 2+1 parts. + // see also http://jira.qos.ch/browse/LBCLASSIC-110 + int[] lengthArray = new int[ClassicConstants.MAX_DOTS + 1]; + + int dotCount = computeDotIndexes(fqClassName, dotIndexesArray); + + // System.out.println(); + // System.out.println("Dot count for [" + className + "] is " + dotCount); + // if there are not dots than abbreviation is not possible + if (dotCount == 0) { + return fqClassName; + } + // printArray("dotArray: ", dotArray); + computeLengthArray(fqClassName, dotIndexesArray, lengthArray, dotCount); + // printArray("lengthArray: ", lengthArray); + for (int i = 0; i <= dotCount; i++) { + if (i == 0) { + buf.append(fqClassName.substring(0, lengthArray[i] - 1)); + } else { + buf.append(fqClassName.substring(dotIndexesArray[i - 1], dotIndexesArray[i - 1] + lengthArray[i])); + } + // System.out.println("i=" + i + ", buf=" + buf); + } + + return buf.toString(); } - int[] dotIndexesArray = new int[ClassicConstants.MAX_DOTS]; - // a.b.c contains 2 dots but 2+1 parts. - // see also http://jira.qos.ch/browse/LBCLASSIC-110 - int[] lengthArray = new int[ClassicConstants.MAX_DOTS + 1]; - - int dotCount = computeDotIndexes(fqClassName, dotIndexesArray); - - // System.out.println(); - // System.out.println("Dot count for [" + className + "] is " + dotCount); - // if there are not dots than abbreviation is not possible - if (dotCount == 0) { - return fqClassName; - } - // printArray("dotArray: ", dotArray); - computeLengthArray(fqClassName, dotIndexesArray, lengthArray, dotCount); - // printArray("lengthArray: ", lengthArray); - for (int i = 0; i <= dotCount; i++) { - if (i == 0) { - buf.append(fqClassName.substring(0, lengthArray[i] - 1)); - } else { - buf.append(fqClassName.substring(dotIndexesArray[i - 1], - dotIndexesArray[i - 1] + lengthArray[i])); - } - // System.out.println("i=" + i + ", buf=" + buf); + static int computeDotIndexes(final String className, int[] dotArray) { + int dotCount = 0; + int k = 0; + while (true) { + // ignore the $ separator in our computations. This is both convenient + // and sensible. + k = className.indexOf(CoreConstants.DOT, k); + if (k != -1 && dotCount < ClassicConstants.MAX_DOTS) { + dotArray[dotCount] = k; + dotCount++; + k++; + } else { + break; + } + } + return dotCount; } - return buf.toString(); - } - - static int computeDotIndexes(final String className, int[] dotArray) { - int dotCount = 0; - int k = 0; - while (true) { - // ignore the $ separator in our computations. This is both convenient - // and sensible. - k = className.indexOf(CoreConstants.DOT, k); - if (k != -1 && dotCount < ClassicConstants.MAX_DOTS) { - dotArray[dotCount] = k; - dotCount++; - k++; - } else { - break; - } - } - return dotCount; - } - - void computeLengthArray(final String className, int[] dotArray, - int[] lengthArray, int dotCount) { - int toTrim = className.length() - targetLength; - // System.out.println("toTrim=" + toTrim); - - // int toTrimAvarage = 0; - - int len; - for (int i = 0; i < dotCount; i++) { - int previousDotPosition = -1; - if (i > 0) { - previousDotPosition = dotArray[i - 1]; - } - int available = dotArray[i] - previousDotPosition - 1; - // System.out.println("i=" + i + ", available = " + available); - - len = (available < 1) ? available : 1; - // System.out.println("i=" + i + ", toTrim = " + toTrim); - - if (toTrim > 0) { - len = (available < 1) ? available : 1; - } else { - len = available; - } - toTrim -= (available - len); - lengthArray[i] = len + 1; + void computeLengthArray(final String className, int[] dotArray, int[] lengthArray, int dotCount) { + int toTrim = className.length() - targetLength; + // System.out.println("toTrim=" + toTrim); + + // int toTrimAvarage = 0; + + int len; + for (int i = 0; i < dotCount; i++) { + int previousDotPosition = -1; + if (i > 0) { + previousDotPosition = dotArray[i - 1]; + } + int available = dotArray[i] - previousDotPosition - 1; + // System.out.println("i=" + i + ", available = " + available); + + len = (available < 1) ? available : 1; + // System.out.println("i=" + i + ", toTrim = " + toTrim); + + if (toTrim > 0) { + len = (available < 1) ? available : 1; + } else { + len = available; + } + toTrim -= (available - len); + lengthArray[i] = len + 1; + } + + int lastDotIndex = dotCount - 1; + lengthArray[dotCount] = className.length() - dotArray[lastDotIndex]; } - int lastDotIndex = dotCount - 1; - lengthArray[dotCount] = className.length() - dotArray[lastDotIndex]; - } - - static void printArray(String msg, int[] ia) { - System.out.print(msg); - for (int i = 0; i < ia.length; i++) { - if (i == 0) { - System.out.print(ia[i]); - } else { - System.out.print(", " + ia[i]); - } + static void printArray(String msg, int[] ia) { + System.out.print(msg); + for (int i = 0; i < ia.length; i++) { + if (i == 0) { + System.out.print(ia[i]); + } else { + System.out.print(", " + ia[i]); + } + } + System.out.println(); } - System.out.println(); - } } \ No newline at end of file diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThreadConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThreadConverter.java index abc24170d908c929ebc5f9ef098c36e43d8bdc2d..d442a39580aaaa311bff5ea2980c6af0e88e8b21 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThreadConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThreadConverter.java @@ -22,8 +22,8 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class ThreadConverter extends ClassicConverter { - public String convert(ILoggingEvent event) { - return event.getThreadName(); - } + public String convert(ILoggingEvent event) { + return event.getThreadName(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableHandlingConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableHandlingConverter.java index 51ebdb25570ff6f5ec7efa70df99827c86f22e60..16c719f0d8876ce8a21c18eccfc29088d6f4c481 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableHandlingConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableHandlingConverter.java @@ -13,15 +13,13 @@ */ package ch.qos.logback.classic.pattern; - - /** * Converter which handle throwables should be derived from this class. * */ public abstract class ThrowableHandlingConverter extends ClassicConverter { - - boolean handlesThrowable() { - return true; - } + + boolean handlesThrowable() { + return true; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableProxyConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableProxyConverter.java index 9861646b00f89987c9e4307fc8d08671c18df179..a09c11e5a1126dd467f7c31c528be4e4f8f3bc41 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableProxyConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/ThrowableProxyConverter.java @@ -34,217 +34,210 @@ import ch.qos.logback.core.status.ErrorStatus; */ public class ThrowableProxyConverter extends ThrowableHandlingConverter { - protected static final int BUILDER_CAPACITY = 2048; - - int lengthOption; - List> evaluatorList = null; - List ignoredStackTraceLines = null; - - int errorCount = 0; - - @SuppressWarnings("unchecked") - public void start() { - - String lengthStr = getFirstOption(); - - if (lengthStr == null) { - lengthOption = Integer.MAX_VALUE; - } else { - lengthStr = lengthStr.toLowerCase(); - if ("full".equals(lengthStr)) { - lengthOption = Integer.MAX_VALUE; - } else if ("short".equals(lengthStr)) { - lengthOption = 1; - } else { - try { - lengthOption = Integer.parseInt(lengthStr); - } catch (NumberFormatException nfe) { - addError("Could not parse [" + lengthStr + "] as an integer"); - lengthOption = Integer.MAX_VALUE; - } - } - } + protected static final int BUILDER_CAPACITY = 2048; + + int lengthOption; + List> evaluatorList = null; + List ignoredStackTraceLines = null; + + int errorCount = 0; - final List optionList = getOptionList(); - - if (optionList != null && optionList.size() > 1) { - final int optionListSize = optionList.size(); - for (int i = 1; i < optionListSize; i++) { - String evaluatorOrIgnoredStackTraceLine = (String) optionList.get(i); - Context context = getContext(); - Map> evaluatorMap = (Map>) context.getObject(CoreConstants.EVALUATOR_MAP); - EventEvaluator ee = (EventEvaluator) evaluatorMap - .get(evaluatorOrIgnoredStackTraceLine); - if (ee != null) { - addEvaluator(ee); + @SuppressWarnings("unchecked") + public void start() { + + String lengthStr = getFirstOption(); + + if (lengthStr == null) { + lengthOption = Integer.MAX_VALUE; } else { - addIgnoreStackTraceLine(evaluatorOrIgnoredStackTraceLine); + lengthStr = lengthStr.toLowerCase(); + if ("full".equals(lengthStr)) { + lengthOption = Integer.MAX_VALUE; + } else if ("short".equals(lengthStr)) { + lengthOption = 1; + } else { + try { + lengthOption = Integer.parseInt(lengthStr); + } catch (NumberFormatException nfe) { + addError("Could not parse [" + lengthStr + "] as an integer"); + lengthOption = Integer.MAX_VALUE; + } + } } - } + + final List optionList = getOptionList(); + + if (optionList != null && optionList.size() > 1) { + final int optionListSize = optionList.size(); + for (int i = 1; i < optionListSize; i++) { + String evaluatorOrIgnoredStackTraceLine = (String) optionList.get(i); + Context context = getContext(); + Map> evaluatorMap = (Map>) context.getObject(CoreConstants.EVALUATOR_MAP); + EventEvaluator ee = (EventEvaluator) evaluatorMap.get(evaluatorOrIgnoredStackTraceLine); + if (ee != null) { + addEvaluator(ee); + } else { + addIgnoreStackTraceLine(evaluatorOrIgnoredStackTraceLine); + } + } + } + super.start(); } - super.start(); - } - private void addEvaluator(EventEvaluator ee) { - if (evaluatorList == null) { - evaluatorList = new ArrayList>(); + private void addEvaluator(EventEvaluator ee) { + if (evaluatorList == null) { + evaluatorList = new ArrayList>(); + } + evaluatorList.add(ee); } - evaluatorList.add(ee); - } - private void addIgnoreStackTraceLine(String ignoredStackTraceLine) { - if (ignoredStackTraceLines == null) { - ignoredStackTraceLines = new ArrayList(); + private void addIgnoreStackTraceLine(String ignoredStackTraceLine) { + if (ignoredStackTraceLines == null) { + ignoredStackTraceLines = new ArrayList(); + } + ignoredStackTraceLines.add(ignoredStackTraceLine); } - ignoredStackTraceLines.add(ignoredStackTraceLine); - } - public void stop() { - evaluatorList = null; - super.stop(); - } + public void stop() { + evaluatorList = null; + super.stop(); + } - protected void extraData(StringBuilder builder, StackTraceElementProxy step) { - // nop - } + protected void extraData(StringBuilder builder, StackTraceElementProxy step) { + // nop + } - public String convert(ILoggingEvent event) { + public String convert(ILoggingEvent event) { - IThrowableProxy tp = event.getThrowableProxy(); - if (tp == null) { - return CoreConstants.EMPTY_STRING; - } + IThrowableProxy tp = event.getThrowableProxy(); + if (tp == null) { + return CoreConstants.EMPTY_STRING; + } - // an evaluator match will cause stack printing to be skipped - if (evaluatorList != null) { - boolean printStack = true; - for (int i = 0; i < evaluatorList.size(); i++) { - EventEvaluator ee = evaluatorList.get(i); - try { - if (ee.evaluate(event)) { - printStack = false; - break; - } - } catch (EvaluationException eex) { - errorCount++; - if (errorCount < CoreConstants.MAX_ERROR_COUNT) { - addError("Exception thrown for evaluator named [" + ee.getName() - + "]", eex); - } else if (errorCount == CoreConstants.MAX_ERROR_COUNT) { - ErrorStatus errorStatus = new ErrorStatus( - "Exception thrown for evaluator named [" + ee.getName() + "].", - this, eex); - errorStatus.add(new ErrorStatus( - "This was the last warning about this evaluator's errors." - + "We don't want the StatusManager to get flooded.", this)); - addStatus(errorStatus); - } + // an evaluator match will cause stack printing to be skipped + if (evaluatorList != null) { + boolean printStack = true; + for (int i = 0; i < evaluatorList.size(); i++) { + EventEvaluator ee = evaluatorList.get(i); + try { + if (ee.evaluate(event)) { + printStack = false; + break; + } + } catch (EvaluationException eex) { + errorCount++; + if (errorCount < CoreConstants.MAX_ERROR_COUNT) { + addError("Exception thrown for evaluator named [" + ee.getName() + "]", eex); + } else if (errorCount == CoreConstants.MAX_ERROR_COUNT) { + ErrorStatus errorStatus = new ErrorStatus("Exception thrown for evaluator named [" + ee.getName() + "].", this, eex); + errorStatus.add(new ErrorStatus("This was the last warning about this evaluator's errors." + + "We don't want the StatusManager to get flooded.", this)); + addStatus(errorStatus); + } + } + } + + if (!printStack) { + return CoreConstants.EMPTY_STRING; + } } - } - if (!printStack) { - return CoreConstants.EMPTY_STRING; - } + return throwableProxyToString(tp); } - return throwableProxyToString(tp); - } - - protected String throwableProxyToString(IThrowableProxy tp) { - StringBuilder sb = new StringBuilder(BUILDER_CAPACITY); + protected String throwableProxyToString(IThrowableProxy tp) { + StringBuilder sb = new StringBuilder(BUILDER_CAPACITY); - recursiveAppend(sb, null, ThrowableProxyUtil.REGULAR_EXCEPTION_INDENT, tp); + recursiveAppend(sb, null, ThrowableProxyUtil.REGULAR_EXCEPTION_INDENT, tp); - return sb.toString(); - } + return sb.toString(); + } - private void recursiveAppend(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { - if(tp == null) - return; - subjoinFirstLine(sb, prefix, indent, tp); - sb.append(CoreConstants.LINE_SEPARATOR); - subjoinSTEPArray(sb, indent, tp); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current : suppressed) { - recursiveAppend(sb, CoreConstants.SUPPRESSED, indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, current); - } + private void recursiveAppend(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { + if (tp == null) + return; + subjoinFirstLine(sb, prefix, indent, tp); + sb.append(CoreConstants.LINE_SEPARATOR); + subjoinSTEPArray(sb, indent, tp); + IThrowableProxy[] suppressed = tp.getSuppressed(); + if (suppressed != null) { + for (IThrowableProxy current : suppressed) { + recursiveAppend(sb, CoreConstants.SUPPRESSED, indent + ThrowableProxyUtil.SUPPRESSED_EXCEPTION_INDENT, current); + } + } + recursiveAppend(sb, CoreConstants.CAUSED_BY, indent, tp.getCause()); } - recursiveAppend(sb, CoreConstants.CAUSED_BY, indent, tp.getCause()); - } - private void subjoinFirstLine(StringBuilder buf, String prefix, int indent, IThrowableProxy tp) { - ThrowableProxyUtil.indent(buf, indent - 1); - if (prefix != null) { - buf.append(prefix); + private void subjoinFirstLine(StringBuilder buf, String prefix, int indent, IThrowableProxy tp) { + ThrowableProxyUtil.indent(buf, indent - 1); + if (prefix != null) { + buf.append(prefix); + } + subjoinExceptionMessage(buf, tp); } - subjoinExceptionMessage(buf, tp); - } - private void subjoinExceptionMessage(StringBuilder buf, IThrowableProxy tp) { - buf.append(tp.getClassName()).append(": ").append(tp.getMessage()); - } + private void subjoinExceptionMessage(StringBuilder buf, IThrowableProxy tp) { + buf.append(tp.getClassName()).append(": ").append(tp.getMessage()); + } - protected void subjoinSTEPArray(StringBuilder buf, int indent, IThrowableProxy tp) { - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - int commonFrames = tp.getCommonFrames(); + protected void subjoinSTEPArray(StringBuilder buf, int indent, IThrowableProxy tp) { + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + int commonFrames = tp.getCommonFrames(); - boolean unrestrictedPrinting = lengthOption > stepArray.length; + boolean unrestrictedPrinting = lengthOption > stepArray.length; + int maxIndex = (unrestrictedPrinting) ? stepArray.length : lengthOption; + if (commonFrames > 0 && unrestrictedPrinting) { + maxIndex -= commonFrames; + } - int maxIndex = (unrestrictedPrinting) ? stepArray.length : lengthOption; - if (commonFrames > 0 && unrestrictedPrinting) { - maxIndex -= commonFrames; - } + int ignoredCount = 0; + for (int i = 0; i < maxIndex; i++) { + StackTraceElementProxy element = stepArray[i]; + if (!isIgnoredStackTraceLine(element.toString())) { + ThrowableProxyUtil.indent(buf, indent); + printStackLine(buf, ignoredCount, element); + ignoredCount = 0; + buf.append(CoreConstants.LINE_SEPARATOR); + } else { + ++ignoredCount; + if (maxIndex < stepArray.length) { + ++maxIndex; + } + } + } + if (ignoredCount > 0) { + printIgnoredCount(buf, ignoredCount); + buf.append(CoreConstants.LINE_SEPARATOR); + } - int ignoredCount = 0; - for (int i = 0; i < maxIndex; i++) { - StackTraceElementProxy element = stepArray[i]; - if (!isIgnoredStackTraceLine(element.toString())) { - ThrowableProxyUtil.indent(buf, indent); - printStackLine(buf, ignoredCount, element); - ignoredCount = 0; - buf.append(CoreConstants.LINE_SEPARATOR); - } else { - ++ignoredCount; - if (maxIndex < stepArray.length) { - ++maxIndex; + if (commonFrames > 0 && unrestrictedPrinting) { + ThrowableProxyUtil.indent(buf, indent); + buf.append("... ").append(tp.getCommonFrames()).append(" common frames omitted").append(CoreConstants.LINE_SEPARATOR); } - } - } - if (ignoredCount > 0) { - printIgnoredCount(buf, ignoredCount); - buf.append(CoreConstants.LINE_SEPARATOR); } - if (commonFrames > 0 && unrestrictedPrinting) { - ThrowableProxyUtil.indent(buf, indent); - buf.append("... ").append(tp.getCommonFrames()).append( - " common frames omitted").append(CoreConstants.LINE_SEPARATOR); + private void printStackLine(StringBuilder buf, int ignoredCount, StackTraceElementProxy element) { + buf.append(element); + extraData(buf, element); // allow other data to be added + if (ignoredCount > 0) { + printIgnoredCount(buf, ignoredCount); + } } - } - private void printStackLine(StringBuilder buf, int ignoredCount, StackTraceElementProxy element) { - buf.append(element); - extraData(buf, element); // allow other data to be added - if (ignoredCount > 0) { - printIgnoredCount(buf, ignoredCount); + private void printIgnoredCount(StringBuilder buf, int ignoredCount) { + buf.append(" [").append(ignoredCount).append(" skipped]"); } - } - - private void printIgnoredCount(StringBuilder buf, int ignoredCount) { - buf.append(" [").append(ignoredCount).append(" skipped]"); - } - private boolean isIgnoredStackTraceLine(String line) { - if (ignoredStackTraceLines != null) { - for (String ignoredStackTraceLine : ignoredStackTraceLines) { - if (line.contains(ignoredStackTraceLine)) { - return true; + private boolean isIgnoredStackTraceLine(String line) { + if (ignoredStackTraceLines != null) { + for (String ignoredStackTraceLine : ignoredStackTraceLines) { + if (line.contains(ignoredStackTraceLine)) { + return true; + } + } } - } + return false; } - return false; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Util.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Util.java index a743c344b0432cd19c33eb8da7fd942c1a217972..319bd8b83852c72dd167a5dd4edbcc1205a07e82 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Util.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/Util.java @@ -26,25 +26,24 @@ import ch.qos.logback.classic.spi.ClassPackagingData; */ public class Util { - static Map cache = new HashMap(); + static Map cache = new HashMap(); - static public boolean match(Marker marker, Marker[] markerArray) { - if (markerArray == null) { - throw new IllegalArgumentException("markerArray should not be null"); - } + static public boolean match(Marker marker, Marker[] markerArray) { + if (markerArray == null) { + throw new IllegalArgumentException("markerArray should not be null"); + } - // System.out.println("event marker="+marker); + // System.out.println("event marker="+marker); - final int size = markerArray.length; - for (int i = 0; i < size; i++) { - // System.out.println("other:"+markerArray[i]); + final int size = markerArray.length; + for (int i = 0; i < size; i++) { + // System.out.println("other:"+markerArray[i]); - if (marker.contains(markerArray[i])) { - return true; - } + if (marker.contains(markerArray[i])) { + return true; + } + } + return false; } - return false; - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.java b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.java index 41acf66d34fb9e7f329d817050e37d13e39dc31b..144b18c4b27d776cc7fc8e226287297c27dcf472 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.java @@ -18,22 +18,25 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import static ch.qos.logback.core.pattern.color.ANSIConstants.*; import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase; - /** * Highlights inner-text depending on the level, in bold red for events of level ERROR, in red for WARN, * in BLUE for INFO, and in the default color for other levels. */ public class HighlightingCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(ILoggingEvent event) { - Level level = event.getLevel(); - switch (level.toInt()) { - case Level.ERROR_INT: return BOLD+RED_FG; - case Level.WARN_INT: return RED_FG; - case Level.INFO_INT: return BLUE_FG; - default: return DEFAULT_FG; - } + @Override + protected String getForegroundColorCode(ILoggingEvent event) { + Level level = event.getLevel(); + switch (level.toInt()) { + case Level.ERROR_INT: + return BOLD + RED_FG; + case Level.WARN_INT: + return RED_FG; + case Level.INFO_INT: + return BLUE_FG; + default: + return DEFAULT_FG; + } - } + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextJNDISelector.java b/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextJNDISelector.java index f97730889f226e2c556a037d52acf2bd456c7f85..5a4e0a777e7839d56c0827682a1786921a9e233e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextJNDISelector.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextJNDISelector.java @@ -51,155 +51,149 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class ContextJNDISelector implements ContextSelector { - private final Map synchronizedContextMap; - private final LoggerContext defaultContext; + private final Map synchronizedContextMap; + private final LoggerContext defaultContext; - private static final ThreadLocal threadLocal = new ThreadLocal(); + private static final ThreadLocal threadLocal = new ThreadLocal(); - public ContextJNDISelector(LoggerContext context) { - synchronizedContextMap = Collections - .synchronizedMap(new HashMap()); - defaultContext = context; - } + public ContextJNDISelector(LoggerContext context) { + synchronizedContextMap = Collections.synchronizedMap(new HashMap()); + defaultContext = context; + } + + public LoggerContext getDefaultLoggerContext() { + return defaultContext; + } - public LoggerContext getDefaultLoggerContext() { - return defaultContext; - } + public LoggerContext detachLoggerContext(String loggerContextName) { + return synchronizedContextMap.remove(loggerContextName); + } + + public LoggerContext getLoggerContext() { + String contextName = null; + Context ctx = null; - public LoggerContext detachLoggerContext(String loggerContextName) { - return synchronizedContextMap.remove(loggerContextName); - } + // First check if ThreadLocal has been set already + LoggerContext lc = threadLocal.get(); + if (lc != null) { + return lc; + } - public LoggerContext getLoggerContext() { - String contextName = null; - Context ctx = null; + try { + // We first try to find the name of our + // environment's LoggerContext + ctx = JNDIUtil.getInitialContext(); + contextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); + } catch (NamingException ne) { + // We can't log here + } - // First check if ThreadLocal has been set already - LoggerContext lc = threadLocal.get(); - if (lc != null) { - return lc; + if (contextName == null) { + // We return the default context + return defaultContext; + } else { + // Let's see if we already know such a context + LoggerContext loggerContext = synchronizedContextMap.get(contextName); + + if (loggerContext == null) { + // We have to create a new LoggerContext + loggerContext = new LoggerContext(); + loggerContext.setName(contextName); + synchronizedContextMap.put(contextName, loggerContext); + URL url = findConfigFileURL(ctx, loggerContext); + if (url != null) { + configureLoggerContextByURL(loggerContext, url); + } else { + try { + new ContextInitializer(loggerContext).autoConfig(); + } catch (JoranException je) { + } + } + // logback-292 + if (!StatusUtil.contextHasStatusListener(loggerContext)) + StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); + } + return loggerContext; + } } - try { - // We first try to find the name of our - // environment's LoggerContext - ctx = JNDIUtil.getInitialContext(); - contextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); - } catch (NamingException ne) { - // We can't log here + private String conventionalConfigFileName(String contextName) { + return "logback-" + contextName + ".xml"; } - if (contextName == null) { - // We return the default context - return defaultContext; - } else { - // Let's see if we already know such a context - LoggerContext loggerContext = synchronizedContextMap.get(contextName); - - if (loggerContext == null) { - // We have to create a new LoggerContext - loggerContext = new LoggerContext(); - loggerContext.setName(contextName); - synchronizedContextMap.put(contextName, loggerContext); - URL url = findConfigFileURL(ctx, loggerContext); - if (url != null) { - configureLoggerContextByURL(loggerContext, url); + private URL findConfigFileURL(Context ctx, LoggerContext loggerContext) { + StatusManager sm = loggerContext.getStatusManager(); + + String jndiEntryForConfigResource = JNDIUtil.lookup(ctx, JNDI_CONFIGURATION_RESOURCE); + // Do we have a dedicated configuration file? + if (jndiEntryForConfigResource != null) { + sm.add(new InfoStatus("Searching for [" + jndiEntryForConfigResource + "]", this)); + URL url = urlByResourceName(sm, jndiEntryForConfigResource); + if (url == null) { + String msg = "The jndi resource [" + jndiEntryForConfigResource + "] for context [" + loggerContext.getName() + + "] does not lead to a valid file"; + sm.add(new WarnStatus(msg, this)); + } + return url; } else { - try { - new ContextInitializer(loggerContext).autoConfig(); - } catch (JoranException je) { - } + String resourceByConvention = conventionalConfigFileName(loggerContext.getName()); + return urlByResourceName(sm, resourceByConvention); + } + } + + private URL urlByResourceName(StatusManager sm, String resourceName) { + sm.add(new InfoStatus("Searching for [" + resourceName + "]", this)); + URL url = Loader.getResource(resourceName, Loader.getTCL()); + if (url != null) { + return url; + } + return Loader.getResourceBySelfClassLoader(resourceName); + } + + private void configureLoggerContextByURL(LoggerContext context, URL url) { + try { + JoranConfigurator configurator = new JoranConfigurator(); + context.reset(); + configurator.setContext(context); + configurator.doConfigure(url); + } catch (JoranException e) { } - // logback-292 - if (!StatusUtil.contextHasStatusListener(loggerContext)) - StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); - } - return loggerContext; + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + } + + public List getContextNames() { + List list = new ArrayList(); + list.addAll(synchronizedContextMap.keySet()); + return list; + } + + public LoggerContext getLoggerContext(String name) { + return synchronizedContextMap.get(name); } - } - - private String conventionalConfigFileName(String contextName) { - return "logback-" + contextName + ".xml"; - } - - private URL findConfigFileURL(Context ctx, LoggerContext loggerContext) { - StatusManager sm = loggerContext.getStatusManager(); - - String jndiEntryForConfigResource = JNDIUtil.lookup(ctx, - JNDI_CONFIGURATION_RESOURCE); - // Do we have a dedicated configuration file? - if (jndiEntryForConfigResource != null) { - sm.add(new InfoStatus("Searching for [" + jndiEntryForConfigResource - + "]", this)); - URL url = urlByResourceName(sm, jndiEntryForConfigResource); - if (url == null) { - String msg = "The jndi resource [" + jndiEntryForConfigResource - + "] for context [" + loggerContext.getName() - + "] does not lead to a valid file"; - sm.add(new WarnStatus(msg, this)); - } - return url; - } else { - String resourceByConvention = conventionalConfigFileName(loggerContext - .getName()); - return urlByResourceName(sm, resourceByConvention); + + /** + * Returns the number of managed contexts Used for testing purposes + * + * @return the number of managed contexts + */ + public int getCount() { + return synchronizedContextMap.size(); } - } - - private URL urlByResourceName(StatusManager sm, String resourceName) { - sm.add(new InfoStatus("Searching for [" + resourceName + "]", - this)); - URL url = Loader.getResource(resourceName, Loader.getTCL()); - if (url != null) { - return url; + + /** + * These methods are used by the LoggerContextFilter. + *

+ * They provide a way to tell the selector which context to use, thus saving + * the cost of a JNDI call at each new request. + * + * @param context + */ + public void setLocalContext(LoggerContext context) { + threadLocal.set(context); } - return Loader.getResourceBySelfClassLoader(resourceName); - } - - private void configureLoggerContextByURL(LoggerContext context, URL url) { - try { - JoranConfigurator configurator = new JoranConfigurator(); - context.reset(); - configurator.setContext(context); - configurator.doConfigure(url); - } catch (JoranException e) { + + public void removeLocalContext() { + threadLocal.remove(); } - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - } - - public List getContextNames() { - List list = new ArrayList(); - list.addAll(synchronizedContextMap.keySet()); - return list; - } - - public LoggerContext getLoggerContext(String name) { - return synchronizedContextMap.get(name); - } - - /** - * Returns the number of managed contexts Used for testing purposes - * - * @return the number of managed contexts - */ - public int getCount() { - return synchronizedContextMap.size(); - } - - /** - * These methods are used by the LoggerContextFilter. - *

- * They provide a way to tell the selector which context to use, thus saving - * the cost of a JNDI call at each new request. - * - * @param context - */ - public void setLocalContext(LoggerContext context) { - threadLocal.set(context); - } - - public void removeLocalContext() { - threadLocal.remove(); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextSelector.java b/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextSelector.java index 1c9ff20698906b45ea13158271d26b9a9b1b249a..dbc1ff518df1b25717829d72f2709f1a0fd7f6da 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextSelector.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/selector/ContextSelector.java @@ -28,13 +28,13 @@ import ch.qos.logback.classic.LoggerContext; */ public interface ContextSelector { - LoggerContext getLoggerContext(); - - LoggerContext getLoggerContext(String name); - - LoggerContext getDefaultLoggerContext(); - - LoggerContext detachLoggerContext(String loggerContextName); - - List getContextNames(); + LoggerContext getLoggerContext(); + + LoggerContext getLoggerContext(String name); + + LoggerContext getDefaultLoggerContext(); + + LoggerContext detachLoggerContext(String loggerContextName); + + List getContextNames(); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/selector/DefaultContextSelector.java b/logback-classic/src/main/java/ch/qos/logback/classic/selector/DefaultContextSelector.java index e0db1dab73c74785f724c47179872d2dbf23434c..0396000c64dfb5619e2692c59e7711db3b9bb92a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/selector/DefaultContextSelector.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/selector/DefaultContextSelector.java @@ -20,33 +20,33 @@ import ch.qos.logback.classic.LoggerContext; public class DefaultContextSelector implements ContextSelector { - private LoggerContext defaultLoggerContext; - - public DefaultContextSelector(LoggerContext context) { - this.defaultLoggerContext = context; - } - - public LoggerContext getLoggerContext() { - return getDefaultLoggerContext(); - } - - public LoggerContext getDefaultLoggerContext() { - return defaultLoggerContext; - } - - public LoggerContext detachLoggerContext(String loggerContextName) { - return defaultLoggerContext; - } - - public List getContextNames() { - return Arrays.asList(defaultLoggerContext.getName()); - } - - public LoggerContext getLoggerContext(String name) { - if (defaultLoggerContext.getName().equals(name)) { - return defaultLoggerContext; - } else { - return null; + private LoggerContext defaultLoggerContext; + + public DefaultContextSelector(LoggerContext context) { + this.defaultLoggerContext = context; + } + + public LoggerContext getLoggerContext() { + return getDefaultLoggerContext(); + } + + public LoggerContext getDefaultLoggerContext() { + return defaultLoggerContext; + } + + public LoggerContext detachLoggerContext(String loggerContextName) { + return defaultLoggerContext; + } + + public List getContextNames() { + return Arrays.asList(defaultLoggerContext.getName()); + } + + public LoggerContext getLoggerContext(String name) { + if (defaultLoggerContext.getName().equals(name)) { + return defaultLoggerContext; + } else { + return null; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/ContextDetachingSCL.java b/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/ContextDetachingSCL.java index bc55dd122a4d84c91a54bcf1815dfe10239a8769..be6ab0c1d9b273cd79c65f2f7f58b49b3bc3099d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/ContextDetachingSCL.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/ContextDetachingSCL.java @@ -29,38 +29,38 @@ import ch.qos.logback.classic.util.JNDIUtil; public class ContextDetachingSCL implements ServletContextListener { - public void contextDestroyed(ServletContextEvent servletContextEvent) { - String loggerContextName = null; - - try { - Context ctx = JNDIUtil.getInitialContext(); - loggerContextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); - } catch (NamingException ne) { - } - - if (loggerContextName != null) { - System.out.println("About to detach context named " + loggerContextName); - - ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); - if(selector == null) { - System.out.println("Selector is null, cannot detach context. Skipping."); - return; - } - LoggerContext context = selector.getLoggerContext(loggerContextName); - if (context != null) { - Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME); - logger.warn("Stopping logger context " + loggerContextName); - selector.detachLoggerContext(loggerContextName); - // when the web-app is destroyed, its logger context should be stopped - context.stop(); - } else { - System.out.println("No context named " + loggerContextName + " was found."); - } + public void contextDestroyed(ServletContextEvent servletContextEvent) { + String loggerContextName = null; + + try { + Context ctx = JNDIUtil.getInitialContext(); + loggerContextName = (String) JNDIUtil.lookup(ctx, JNDI_CONTEXT_NAME); + } catch (NamingException ne) { + } + + if (loggerContextName != null) { + System.out.println("About to detach context named " + loggerContextName); + + ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); + if (selector == null) { + System.out.println("Selector is null, cannot detach context. Skipping."); + return; + } + LoggerContext context = selector.getLoggerContext(loggerContextName); + if (context != null) { + Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME); + logger.warn("Stopping logger context " + loggerContextName); + selector.detachLoggerContext(loggerContextName); + // when the web-app is destroyed, its logger context should be stopped + context.stop(); + } else { + System.out.println("No context named " + loggerContextName + " was found."); + } + } } - } - public void contextInitialized(ServletContextEvent arg0) { - // do nothing - } + public void contextInitialized(ServletContextEvent arg0) { + // do nothing + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/LoggerContextFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/LoggerContextFilter.java index d76a393beba59471259c4fb99776204c842f365a..28f7d38b2d83e519b9d65eaab173d90d66a87e22 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/LoggerContextFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/selector/servlet/LoggerContextFilter.java @@ -50,32 +50,31 @@ import ch.qos.logback.classic.util.ContextSelectorStaticBinder; */ public class LoggerContextFilter implements Filter { - public void destroy() { - //do nothing - } + public void destroy() { + // do nothing + } - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); - ContextJNDISelector sel = null; + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); + ContextJNDISelector sel = null; - if (selector instanceof ContextJNDISelector) { - sel = (ContextJNDISelector)selector; - sel.setLocalContext(lc); - } + if (selector instanceof ContextJNDISelector) { + sel = (ContextJNDISelector) selector; + sel.setLocalContext(lc); + } - try { - chain.doFilter(request, response); - } finally { - if (sel != null) { - sel.removeLocalContext(); - } + try { + chain.doFilter(request, response); + } finally { + if (sel != null) { + sel.removeLocalContext(); + } + } } - } - public void init(FilterConfig arg0) throws ServletException { - //do nothing - } + public void init(FilterConfig arg0) throws ServletException { + // do nothing + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/AppenderFactoryUsingJoran.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/AppenderFactoryUsingJoran.java index 28eb1ab93c9139f44aa94c74bb1ac2130b260aa8..fb1ed77517ddad0e660c8feb8c0fd23979809934 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/AppenderFactoryUsingJoran.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/AppenderFactoryUsingJoran.java @@ -26,13 +26,12 @@ import ch.qos.logback.core.sift.SiftingJoranConfiguratorBase; */ public class AppenderFactoryUsingJoran extends AbstractAppenderFactoryUsingJoran { + AppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { + super(eventList, key, parentPropertyMap); + } - AppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { - super(eventList, key, parentPropertyMap); - } - - public SiftingJoranConfiguratorBase getSiftingJoranConfigurator(String discriminatingValue) { - return new SiftingJoranConfigurator(key, discriminatingValue, parentPropertyMap); - } + public SiftingJoranConfiguratorBase getSiftingJoranConfigurator(String discriminatingValue) { + return new SiftingJoranConfigurator(key, discriminatingValue, parentPropertyMap); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/ContextBasedDiscriminator.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/ContextBasedDiscriminator.java index 73a3ac83d0fe44c4cf1f3bafe7d9c3a5a8a6cb62..13723658a93ba5644dc1cc7b659ad0c6c4077817 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/ContextBasedDiscriminator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/ContextBasedDiscriminator.java @@ -28,46 +28,45 @@ import ch.qos.logback.core.sift.AbstractDiscriminator; */ public class ContextBasedDiscriminator extends AbstractDiscriminator { - private static final String KEY = "contextName"; - private String defaultValue; + private static final String KEY = "contextName"; + private String defaultValue; - /** - * Return the name of the current context name as found in the logging event. - */ - public String getDiscriminatingValue(ILoggingEvent event) { - String contextName = event.getLoggerContextVO().getName(); + /** + * Return the name of the current context name as found in the logging event. + */ + public String getDiscriminatingValue(ILoggingEvent event) { + String contextName = event.getLoggerContextVO().getName(); - if (contextName == null) { - return defaultValue; - } else { - return contextName; + if (contextName == null) { + return defaultValue; + } else { + return contextName; + } } - } - public String getKey() { - return KEY; - } + public String getKey() { + return KEY; + } - public void setKey(String key) { - throw new UnsupportedOperationException( - "Key cannot be set. Using fixed key " + KEY); - } + public void setKey(String key) { + throw new UnsupportedOperationException("Key cannot be set. Using fixed key " + KEY); + } - /** - * @see #setDefaultValue(String) - * @return - */ - public String getDefaultValue() { - return defaultValue; - } + /** + * @see #setDefaultValue(String) + * @return + */ + public String getDefaultValue() { + return defaultValue; + } - /** - * The default context name in case the context name is not set for the - * current logging event. - * - * @param defaultValue - */ - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } + /** + * The default context name in case the context name is not set for the + * current logging event. + * + * @param defaultValue + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/JNDIBasedContextDiscriminator.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/JNDIBasedContextDiscriminator.java index e6003b62e6c2b22e671e5a13a0f52b37a648b183..81d39ce51707b467282c2b814b5ef0b7ba1796da 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/JNDIBasedContextDiscriminator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/JNDIBasedContextDiscriminator.java @@ -31,52 +31,50 @@ import ch.qos.logback.core.sift.AbstractDiscriminator; */ public class JNDIBasedContextDiscriminator extends AbstractDiscriminator { - private static final String KEY = "contextName"; - private String defaultValue; + private static final String KEY = "contextName"; + private String defaultValue; - /** - * Return the name of the current context name as found in the logging event. - */ - public String getDiscriminatingValue(ILoggingEvent event) { - ContextSelector selector = ContextSelectorStaticBinder.getSingleton() - .getContextSelector(); + /** + * Return the name of the current context name as found in the logging event. + */ + public String getDiscriminatingValue(ILoggingEvent event) { + ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); - if (selector == null) { - return defaultValue; - } + if (selector == null) { + return defaultValue; + } - LoggerContext lc = selector.getLoggerContext(); - if (lc == null) { - return defaultValue; - } + LoggerContext lc = selector.getLoggerContext(); + if (lc == null) { + return defaultValue; + } - return lc.getName(); - } + return lc.getName(); + } - public String getKey() { - return KEY; - } + public String getKey() { + return KEY; + } - public void setKey(String key) { - throw new UnsupportedOperationException( - "Key cannot be set. Using fixed key " + KEY); - } + public void setKey(String key) { + throw new UnsupportedOperationException("Key cannot be set. Using fixed key " + KEY); + } - /** - * @see #setDefaultValue(String) - * @return - */ - public String getDefaultValue() { - return defaultValue; - } + /** + * @see #setDefaultValue(String) + * @return + */ + public String getDefaultValue() { + return defaultValue; + } - /** - * The default context name in case the context name is not set for the - * current logging event. - * - * @param defaultValue - */ - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } + /** + * The default context name in case the context name is not set for the + * current logging event. + * + * @param defaultValue + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/MDCBasedDiscriminator.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/MDCBasedDiscriminator.java index 370788d833f6a4c4f3f32016d00f2845ff86c725..d65f1b1070c1f93f762c0c0f61e95a216fff7639 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/MDCBasedDiscriminator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/MDCBasedDiscriminator.java @@ -29,71 +29,71 @@ import java.util.Map; */ public class MDCBasedDiscriminator extends AbstractDiscriminator { - private String key; - private String defaultValue; + private String key; + private String defaultValue; - /** - * Return the value associated with an MDC entry designated by the Key - * property. If that value is null, then return the value assigned to the - * DefaultValue property. - */ - public String getDiscriminatingValue(ILoggingEvent event) { - // http://jira.qos.ch/browse/LBCLASSIC-213 - Map mdcMap = event.getMDCPropertyMap(); - if (mdcMap == null) { - return defaultValue; + /** + * Return the value associated with an MDC entry designated by the Key + * property. If that value is null, then return the value assigned to the + * DefaultValue property. + */ + public String getDiscriminatingValue(ILoggingEvent event) { + // http://jira.qos.ch/browse/LBCLASSIC-213 + Map mdcMap = event.getMDCPropertyMap(); + if (mdcMap == null) { + return defaultValue; + } + String mdcValue = mdcMap.get(key); + if (mdcValue == null) { + return defaultValue; + } else { + return mdcValue; + } } - String mdcValue = mdcMap.get(key); - if (mdcValue == null) { - return defaultValue; - } else { - return mdcValue; - } - } - @Override - public void start() { - int errors = 0; - if (OptionHelper.isEmpty(key)) { - errors++; - addError("The \"Key\" property must be set"); - } - if (OptionHelper.isEmpty(defaultValue)) { - errors++; - addError("The \"DefaultValue\" property must be set"); + @Override + public void start() { + int errors = 0; + if (OptionHelper.isEmpty(key)) { + errors++; + addError("The \"Key\" property must be set"); + } + if (OptionHelper.isEmpty(defaultValue)) { + errors++; + addError("The \"DefaultValue\" property must be set"); + } + if (errors == 0) { + started = true; + } } - if (errors == 0) { - started = true; - } - } - public String getKey() { - return key; - } + public String getKey() { + return key; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - /** - * @return - * @see #setDefaultValue(String) - */ - public String getDefaultValue() { - return defaultValue; - } + /** + * @return + * @see #setDefaultValue(String) + */ + public String getDefaultValue() { + return defaultValue; + } - /** - * The default MDC value in case the MDC is not set for - * {@link #setKey(String) mdcKey}. - *

- *

For example, if {@link #setKey(String) Key} is set to the value - * "someKey", and the MDC is not set for "someKey", then this appender will - * use the default value, which you can set with the help of this method. - * - * @param defaultValue - */ - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } + /** + * The default MDC value in case the MDC is not set for + * {@link #setKey(String) mdcKey}. + *

+ *

For example, if {@link #setKey(String) Key} is set to the value + * "someKey", and the MDC is not set for "someKey", then this appender will + * use the default value, which you can set with the help of this method. + * + * @param defaultValue + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftAction.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftAction.java index 6eccc72c356012eb92d2ea586f5f71bca07f8c72..02bf4b4d079db766223488dcf9ce3ef5eeec84cf 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftAction.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftAction.java @@ -26,34 +26,32 @@ import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; public class SiftAction extends Action implements InPlayListener { - List seList; - - @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { - seList = new ArrayList(); - ic.addInPlayListener(this); - } - - @Override - public void end(InterpretationContext ic, String name) throws ActionException { - ic.removeInPlayListener(this); - Object o = ic.peekObject(); - if (o instanceof SiftingAppender) { - SiftingAppender sa = (SiftingAppender) o; - Map propertyMap = ic.getCopyOfPropertyMap(); - AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, sa - .getDiscriminatorKey(), propertyMap); - sa.setAppenderFactory(appenderFactory); + List seList; + + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { + seList = new ArrayList(); + ic.addInPlayListener(this); } - } - public void inPlay(SaxEvent event) { - seList.add(event); - } + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + ic.removeInPlayListener(this); + Object o = ic.peekObject(); + if (o instanceof SiftingAppender) { + SiftingAppender sa = (SiftingAppender) o; + Map propertyMap = ic.getCopyOfPropertyMap(); + AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, sa.getDiscriminatorKey(), propertyMap); + sa.setAppenderFactory(appenderFactory); + } + } - public List getSeList() { - return seList; - } + public void inPlay(SaxEvent event) { + seList.add(event); + } + + public List getSeList() { + return seList; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingAppender.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingAppender.java index 1e8e5c33b4a73a630982ca839e7303c255782748..5ef985efb2866facd965610803eddc60dbe96377 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingAppender.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingAppender.java @@ -32,23 +32,22 @@ import org.slf4j.Marker; */ public class SiftingAppender extends SiftingAppenderBase { - @Override - protected long getTimestamp(ILoggingEvent event) { - return event.getTimeStamp(); - } - + @Override + protected long getTimestamp(ILoggingEvent event) { + return event.getTimeStamp(); + } - @Override - @DefaultClass(MDCBasedDiscriminator.class) - public void setDiscriminator(Discriminator discriminator) { - super.setDiscriminator(discriminator); - } + @Override + @DefaultClass(MDCBasedDiscriminator.class) + public void setDiscriminator(Discriminator discriminator) { + super.setDiscriminator(discriminator); + } - protected boolean eventMarksEndOfLife(ILoggingEvent event) { - Marker marker = event.getMarker(); - if(marker == null) - return false; + protected boolean eventMarksEndOfLife(ILoggingEvent event) { + Marker marker = event.getMarker(); + if (marker == null) + return false; - return marker.contains(ClassicConstants.FINALIZE_SESSION_MARKER); - } + return marker.contains(ClassicConstants.FINALIZE_SESSION_MARKER); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingJoranConfigurator.java b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingJoranConfigurator.java index 5a83a37149b38e777c3430999832fa85e05f1b29..0d90a3c3b5a898731dbb62870d9096a24dcdc58b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingJoranConfigurator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/sift/SiftingJoranConfigurator.java @@ -28,52 +28,49 @@ import ch.qos.logback.core.joran.spi.ElementSelector; import ch.qos.logback.core.joran.spi.RuleStore; import ch.qos.logback.core.sift.SiftingJoranConfiguratorBase; -public class SiftingJoranConfigurator extends SiftingJoranConfiguratorBase { +public class SiftingJoranConfigurator extends SiftingJoranConfiguratorBase { + SiftingJoranConfigurator(String key, String value, Map parentPropertyMap) { + super(key, value, parentPropertyMap); + } + + @Override + protected ElementPath initialElementPath() { + return new ElementPath("configuration"); + } - SiftingJoranConfigurator(String key, String value, Map parentPropertyMap) { - super(key, value, parentPropertyMap); - } - - @Override - protected ElementPath initialElementPath() { - return new ElementPath("configuration"); - } - - @Override - protected void addInstanceRules(RuleStore rs) { - super.addInstanceRules(rs); - rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); - } + @Override + protected void addInstanceRules(RuleStore rs) { + super.addInstanceRules(rs); + rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); + } + @Override + protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + DefaultNestedComponentRules.addDefaultNestedComponentRegistryRules(registry); + } - @Override - protected void addDefaultNestedComponentRegistryRules( - DefaultNestedComponentRegistry registry) { - DefaultNestedComponentRules.addDefaultNestedComponentRegistryRules(registry); - } - - @Override - protected void buildInterpreter() { - super.buildInterpreter(); - Map omap = interpreter.getInterpretationContext().getObjectMap(); - omap.put(ActionConst.APPENDER_BAG, new HashMap()); - omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); - Map propertiesMap = new HashMap(); - propertiesMap.putAll(parentPropertyMap); - propertiesMap.put(key, value); - interpreter.setInterpretationContextPropertiesMap(propertiesMap); - } + @Override + protected void buildInterpreter() { + super.buildInterpreter(); + Map omap = interpreter.getInterpretationContext().getObjectMap(); + omap.put(ActionConst.APPENDER_BAG, new HashMap()); + omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); + Map propertiesMap = new HashMap(); + propertiesMap.putAll(parentPropertyMap); + propertiesMap.put(key, value); + interpreter.setInterpretationContextPropertiesMap(propertiesMap); + } - @SuppressWarnings("unchecked") - public Appender getAppender() { - Map omap = interpreter.getInterpretationContext().getObjectMap(); - HashMap appenderMap = (HashMap) omap.get(ActionConst.APPENDER_BAG); - oneAndOnlyOneCheck(appenderMap); - Collection values = appenderMap.values(); - if(values.size() == 0) { - return null; + @SuppressWarnings("unchecked") + public Appender getAppender() { + Map omap = interpreter.getInterpretationContext().getObjectMap(); + HashMap appenderMap = (HashMap) omap.get(ActionConst.APPENDER_BAG); + oneAndOnlyOneCheck(appenderMap); + Collection values = appenderMap.values(); + if (values.size() == 0) { + return null; + } + return (Appender) values.iterator().next(); } - return (Appender) values.iterator().next(); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/CallerData.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/CallerData.java index df70a9c7b242052b2757a6dcb9cea990c2741728..c566be7b41bc1fb83b7396632fa7f9422125d54e 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/CallerData.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/CallerData.java @@ -25,107 +25,101 @@ import java.util.List; */ public class CallerData { + /** + * When caller information is not available this constant is used for file + * name, method name, etc. + */ + public static final String NA = "?"; + + // All logger call's in log4j-over-slf4j use the Category class + private static final String LOG4J_CATEGORY = "org.apache.log4j.Category"; + private static final String SLF4J_BOUNDARY = "org.slf4j.Logger"; + + /** + * When caller information is not available this constant is used for the line + * number. + */ + public static final int LINE_NA = -1; + + public static final String CALLER_DATA_NA = "?#?:?" + CoreConstants.LINE_SEPARATOR; + + /** + * This value is returned in case no caller data could be extracted. + */ + public static final StackTraceElement[] EMPTY_CALLER_DATA_ARRAY = new StackTraceElement[0]; + + /** + * Extract caller data information as an array based on a Throwable passed as + * parameter + */ + public static StackTraceElement[] extract(Throwable t, String fqnOfInvokingClass, final int maxDepth, List frameworkPackageList) { + if (t == null) { + return null; + } - /** - * When caller information is not available this constant is used for file - * name, method name, etc. - */ - public static final String NA = "?"; - - // All logger call's in log4j-over-slf4j use the Category class - private static final String LOG4J_CATEGORY = "org.apache.log4j.Category"; - private static final String SLF4J_BOUNDARY = "org.slf4j.Logger"; - - /** - * When caller information is not available this constant is used for the line - * number. - */ - public static final int LINE_NA = -1; - - public static final String CALLER_DATA_NA = "?#?:?" + CoreConstants.LINE_SEPARATOR; - - /** - * This value is returned in case no caller data could be extracted. - */ - public static final StackTraceElement[] EMPTY_CALLER_DATA_ARRAY = new StackTraceElement[0]; - - - /** - * Extract caller data information as an array based on a Throwable passed as - * parameter - */ - public static StackTraceElement[] extract(Throwable t, - String fqnOfInvokingClass, final int maxDepth, - List frameworkPackageList) { - if (t == null) { - return null; - } + StackTraceElement[] steArray = t.getStackTrace(); + StackTraceElement[] callerDataArray; + + int found = LINE_NA; + for (int i = 0; i < steArray.length; i++) { + if (isInFrameworkSpace(steArray[i].getClassName(), fqnOfInvokingClass, frameworkPackageList)) { + // the caller is assumed to be the next stack frame, hence the +1. + found = i + 1; + } else { + if (found != LINE_NA) { + break; + } + } + } + + // we failed to extract caller data + if (found == LINE_NA) { + return EMPTY_CALLER_DATA_ARRAY; + } - StackTraceElement[] steArray = t.getStackTrace(); - StackTraceElement[] callerDataArray; - - int found = LINE_NA; - for (int i = 0; i < steArray.length; i++) { - if (isInFrameworkSpace(steArray[i].getClassName(), - fqnOfInvokingClass, frameworkPackageList)) { - // the caller is assumed to be the next stack frame, hence the +1. - found = i + 1; - } else { - if (found != LINE_NA) { - break; + int availableDepth = steArray.length - found; + int desiredDepth = maxDepth < (availableDepth) ? maxDepth : availableDepth; + + callerDataArray = new StackTraceElement[desiredDepth]; + for (int i = 0; i < desiredDepth; i++) { + callerDataArray[i] = steArray[found + i]; } - } + return callerDataArray; } - // we failed to extract caller data - if (found == LINE_NA) { - return EMPTY_CALLER_DATA_ARRAY; + static boolean isInFrameworkSpace(String currentClass, String fqnOfInvokingClass, List frameworkPackageList) { + // the check for org.apache.log4j.Category class is intended to support + // log4j-over-slf4j. it solves http://bugzilla.slf4j.org/show_bug.cgi?id=66 + if (currentClass.equals(fqnOfInvokingClass) || currentClass.equals(LOG4J_CATEGORY) || currentClass.startsWith(SLF4J_BOUNDARY) + || isInFrameworkSpaceList(currentClass, frameworkPackageList)) { + return true; + } else { + return false; + } } - int availableDepth = steArray.length - found; - int desiredDepth = maxDepth < (availableDepth) ? maxDepth : availableDepth; + /** + * Is currentClass present in the list of packages considered part of the logging framework? + */ + private static boolean isInFrameworkSpaceList(String currentClass, List frameworkPackageList) { + if (frameworkPackageList == null) + return false; - callerDataArray = new StackTraceElement[desiredDepth]; - for (int i = 0; i < desiredDepth; i++) { - callerDataArray[i] = steArray[found + i]; - } - return callerDataArray; - } - - static boolean isInFrameworkSpace(String currentClass, - String fqnOfInvokingClass, List frameworkPackageList) { - // the check for org.apache.log4j.Category class is intended to support - // log4j-over-slf4j. it solves http://bugzilla.slf4j.org/show_bug.cgi?id=66 - if (currentClass.equals(fqnOfInvokingClass) || currentClass.equals(LOG4J_CATEGORY) - || currentClass.startsWith(SLF4J_BOUNDARY) || isInFrameworkSpaceList(currentClass, frameworkPackageList)) { - return true; - } else { - return false; + for (String s : frameworkPackageList) { + if (currentClass.startsWith(s)) + return true; + } + return false; } - } - - /** - * Is currentClass present in the list of packages considered part of the logging framework? - */ - private static boolean isInFrameworkSpaceList(String currentClass, List frameworkPackageList) { - if (frameworkPackageList == null) - return false; - - for (String s : frameworkPackageList) { - if (currentClass.startsWith(s)) - return true; + + /** + * Returns a StackTraceElement where all string fields are set to {@link #NA} and line number is set to {@link #LINE_NA}. + * + * @return StackTraceElement with values set to NA constants. + * @since 1.0.10 + */ + public static StackTraceElement naInstance() { + return new StackTraceElement(NA, NA, NA, LINE_NA); } - return false; - } - - /** - * Returns a StackTraceElement where all string fields are set to {@link #NA} and line number is set to {@link #LINE_NA}. - * - * @return StackTraceElement with values set to NA constants. - * @since 1.0.10 - */ - public static StackTraceElement naInstance() { - return new StackTraceElement(NA, NA, NA, LINE_NA); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ClassPackagingData.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ClassPackagingData.java index 36a2e477c07d994fa083c8562e119b84c53a8b6a..1482c9fd3ba877bf0b06e67084a0125ec6c239d0 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ClassPackagingData.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ClassPackagingData.java @@ -17,65 +17,65 @@ import java.io.Serializable; public class ClassPackagingData implements Serializable { - private static final long serialVersionUID = -804643281218337001L; - final String codeLocation; - final String version; - private final boolean exact; - - public ClassPackagingData(String codeLocation, String version) { - this.codeLocation = codeLocation; - this.version = version; - this.exact = true; - } + private static final long serialVersionUID = -804643281218337001L; + final String codeLocation; + final String version; + private final boolean exact; - public ClassPackagingData(String classLocation, String version, boolean exact) { - this.codeLocation = classLocation; - this.version = version; - this.exact = exact; - } - - public String getCodeLocation() { - return codeLocation; - } + public ClassPackagingData(String codeLocation, String version) { + this.codeLocation = codeLocation; + this.version = version; + this.exact = true; + } - public String getVersion() { - return version; - } + public ClassPackagingData(String classLocation, String version, boolean exact) { + this.codeLocation = classLocation; + this.version = version; + this.exact = exact; + } - public boolean isExact() { - return exact; - } + public String getCodeLocation() { + return codeLocation; + } - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((codeLocation == null) ? 0 : codeLocation.hashCode()); - return result; - } + public String getVersion() { + return version; + } + + public boolean isExact() { + return exact; + } + + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + ((codeLocation == null) ? 0 : codeLocation.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final ClassPackagingData other = (ClassPackagingData) obj; + if (codeLocation == null) { + if (other.codeLocation != null) + return false; + } else if (!codeLocation.equals(other.codeLocation)) + return false; + if (exact != other.exact) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final ClassPackagingData other = (ClassPackagingData) obj; - if (codeLocation == null) { - if (other.codeLocation != null) - return false; - } else if (!codeLocation.equals(other.codeLocation)) - return false; - if (exact != other.exact) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/Configurator.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/Configurator.java index a382fed29e45000d249a543de7db4447f5e65d6d..1714e238ec9acea6ed00c0b8dd918d540df925b7 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/Configurator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/Configurator.java @@ -24,10 +24,10 @@ import ch.qos.logback.core.spi.ContextAware; */ public interface Configurator extends ContextAware { - /** - * The context will also be set before this method is called via - * {@link ContextAware#setContext(ch.qos.logback.core.Context)}. - */ - public void configure(LoggerContext loggerContext); + /** + * The context will also be set before this method is called via + * {@link ContextAware#setContext(ch.qos.logback.core.Context)}. + */ + public void configure(LoggerContext loggerContext); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/EventArgUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/EventArgUtil.java index 6ab217df57d293c396eb2727e845813891cb4ab0..058a150005491343899c6be5d8a2e5fe06ed4f5c 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/EventArgUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/EventArgUtil.java @@ -15,40 +15,39 @@ package ch.qos.logback.classic.spi; public class EventArgUtil { + public static final Throwable extractThrowable(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + return null; + } - public static final Throwable extractThrowable(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - return null; + final Object lastEntry = argArray[argArray.length - 1]; + if (lastEntry instanceof Throwable) { + return (Throwable) lastEntry; + } + return null; } - final Object lastEntry = argArray[argArray.length - 1]; - if (lastEntry instanceof Throwable) { - return (Throwable) lastEntry; + /** + * This method should be called only if {@link #successfulExtraction(Throwable)} returns true. + * + * @param argArray + * @return + */ + public static Object[] trimmedCopy(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + throw new IllegalStateException("non-sensical empty or null argument array"); + } + final int trimemdLen = argArray.length - 1; + Object[] trimmed = new Object[trimemdLen]; + System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); + return trimmed; } - return null; - } - /** - * This method should be called only if {@link #successfulExtraction(Throwable)} returns true. - * - * @param argArray - * @return - */ - public static Object[] trimmedCopy(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - throw new IllegalStateException("non-sensical empty or null argument array"); + public static Object[] arrangeArguments(Object[] argArray) { + return argArray; } - final int trimemdLen = argArray.length - 1; - Object[] trimmed = new Object[trimemdLen]; - System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); - return trimmed; - } - public static Object[] arrangeArguments(Object[] argArray) { - return argArray; - } - - public static boolean successfulExtraction(Throwable throwable) { - return throwable != null; - } + public static boolean successfulExtraction(Throwable throwable) { + return throwable != null; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ILoggingEvent.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ILoggingEvent.java index 0da9e921a3b0af1ed336abc7a77c11a2bfd7b850..e2959f31ca28c848237e96c5a11bb9b8ec3da32d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ILoggingEvent.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ILoggingEvent.java @@ -29,58 +29,59 @@ import ch.qos.logback.core.spi.DeferredProcessingAware; */ public interface ILoggingEvent extends DeferredProcessingAware { - String getThreadName(); + String getThreadName(); - Level getLevel(); + Level getLevel(); - String getMessage(); + String getMessage(); - Object[] getArgumentArray(); + Object[] getArgumentArray(); - String getFormattedMessage(); + String getFormattedMessage(); - String getLoggerName(); + String getLoggerName(); - LoggerContextVO getLoggerContextVO(); + LoggerContextVO getLoggerContextVO(); - IThrowableProxy getThrowableProxy(); + IThrowableProxy getThrowableProxy(); - /** - * Return caller data associated with this event. Note that calling this event - * may trigger the computation of caller data. - * - * @return the caller data associated with this event. - * - * @see #hasCallerData() - */ - StackTraceElement[] getCallerData(); + /** + * Return caller data associated with this event. Note that calling this event + * may trigger the computation of caller data. + * + * @return the caller data associated with this event. + * + * @see #hasCallerData() + */ + StackTraceElement[] getCallerData(); - /** - * If this event has caller data, then true is returned. Otherwise the - * returned value is null. - * - *

Logback components wishing to use caller data if available without - * causing it to be computed can invoke this method before invoking - * {@link #getCallerData()}. - * - * @return whether this event has caller data - */ - boolean hasCallerData(); + /** + * If this event has caller data, then true is returned. Otherwise the + * returned value is null. + * + *

Logback components wishing to use caller data if available without + * causing it to be computed can invoke this method before invoking + * {@link #getCallerData()}. + * + * @return whether this event has caller data + */ + boolean hasCallerData(); - Marker getMarker(); + Marker getMarker(); - /** - * Returns the MDC map. The returned value can be an empty map but not null. - */ - Map getMDCPropertyMap(); + /** + * Returns the MDC map. The returned value can be an empty map but not null. + */ + Map getMDCPropertyMap(); - /** - * Synonym for [@link #getMDCPropertyMap}. - * @deprecated Replaced by [@link #getMDCPropertyMap} - */ - Map getMdc(); - long getTimeStamp(); + /** + * Synonym for [@link #getMDCPropertyMap}. + * @deprecated Replaced by [@link #getMDCPropertyMap} + */ + Map getMdc(); - void prepareForDeferredProcessing(); + long getTimeStamp(); + + void prepareForDeferredProcessing(); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/IThrowableProxy.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/IThrowableProxy.java index 17c95a541e63f42b71653c9048846804d22154c4..a5cc4de2de2a4051636f14adb7530c20f8582647 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/IThrowableProxy.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/IThrowableProxy.java @@ -14,10 +14,15 @@ package ch.qos.logback.classic.spi; public interface IThrowableProxy { - String getMessage(); - String getClassName(); - StackTraceElementProxy[] getStackTraceElementProxyArray(); - int getCommonFrames(); - IThrowableProxy getCause(); - IThrowableProxy[] getSuppressed(); + String getMessage(); + + String getClassName(); + + StackTraceElementProxy[] getStackTraceElementProxyArray(); + + int getCommonFrames(); + + IThrowableProxy getCause(); + + IThrowableProxy[] getSuppressed(); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerComparator.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerComparator.java index 19a5aa1af8e544965cc849f109199268507ada5e..153a1514e54965714b6aa50fc76f609ea5395bd1 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerComparator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerComparator.java @@ -19,17 +19,17 @@ import ch.qos.logback.classic.Logger; public class LoggerComparator implements Comparator { - public int compare(Logger l1, Logger l2) { - if (l1.getName().equals(l2.getName())) { - return 0; + public int compare(Logger l1, Logger l2) { + if (l1.getName().equals(l2.getName())) { + return 0; + } + if (l1.getName().equals(Logger.ROOT_LOGGER_NAME)) { + return -1; + } + if (l2.getName().equals(Logger.ROOT_LOGGER_NAME)) { + return 1; + } + return l1.getName().compareTo(l2.getName()); } - if (l1.getName().equals(Logger.ROOT_LOGGER_NAME)) { - return -1; - } - if (l2.getName().equals(Logger.ROOT_LOGGER_NAME)) { - return 1; - } - return l1.getName().compareTo(l2.getName()); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAware.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAware.java index 692f210e6731cc3746d32fffa90002674694cedf..af85f90c304b91c76b2334bddef83fb5f6de5ca0 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAware.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAware.java @@ -16,18 +16,16 @@ package ch.qos.logback.classic.spi; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.spi.ContextAware; - public interface LoggerContextAware extends ContextAware { + /** + * Set owning logger context for this component. This operation can + * only be performed once. Once set, the owning context cannot be changed. + * + * @param context The context where this component is attached. + * @throws IllegalStateException If you try to change the context after it + * has been set. + **/ + void setLoggerContext(LoggerContext context); - /** - * Set owning logger context for this component. This operation can - * only be performed once. Once set, the owning context cannot be changed. - * - * @param context The context where this component is attached. - * @throws IllegalStateException If you try to change the context after it - * has been set. - **/ - void setLoggerContext(LoggerContext context); - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAwareBase.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAwareBase.java index 8c7d3782fe328a601c5b1c91ba7f3d88918f86ff..b94ac0ec324d780c76836106d14949bd49e6608f 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAwareBase.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextAwareBase.java @@ -17,34 +17,33 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.Context; import ch.qos.logback.core.spi.ContextAwareBase; - public class LoggerContextAwareBase extends ContextAwareBase implements LoggerContextAware { - - /** - * Set the owning context. The owning context cannot be set more than - * once. - */ - public void setLoggerContext(LoggerContext context) { - super.setContext(context); - } - public void setContext(Context context) { - // check that the context is of type LoggerContext. Otherwise, throw an exception - // Context == null is a degenerate case but nonetheless permitted. - if(context instanceof LoggerContext || context == null) { - super.setContext(context); - } else { - throw new IllegalArgumentException("LoggerContextAwareBase only accepts contexts of type c.l.classic.LoggerContext"); + /** + * Set the owning context. The owning context cannot be set more than + * once. + */ + public void setLoggerContext(LoggerContext context) { + super.setContext(context); + } + + public void setContext(Context context) { + // check that the context is of type LoggerContext. Otherwise, throw an exception + // Context == null is a degenerate case but nonetheless permitted. + if (context instanceof LoggerContext || context == null) { + super.setContext(context); + } else { + throw new IllegalArgumentException("LoggerContextAwareBase only accepts contexts of type c.l.classic.LoggerContext"); + } + } + + /** + * Return the {@link LoggerContext} this component is attached to. + * + * @return The owning LoggerContext + */ + public LoggerContext getLoggerContext() { + return (LoggerContext) context; } - } - /** - * Return the {@link LoggerContext} this component is attached to. - * - * @return The owning LoggerContext - */ - public LoggerContext getLoggerContext() { - return (LoggerContext) context; - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextListener.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextListener.java index f2a53e86e8406bba27f53493a887178f30dd6c6c..9871109583a90d82a59735244a8d0d09c3a7346b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextListener.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextListener.java @@ -18,16 +18,19 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; public interface LoggerContextListener { - - /** - * Some listeners should not be removed when the LoggerContext is - * reset. Such listeners are said to be reset resistant. - * @return whether this listener is reset resistant or not. - */ - boolean isResetResistant(); - void onStart(LoggerContext context); - void onReset(LoggerContext context); - void onStop(LoggerContext context); - void onLevelChange(Logger logger, Level level); + /** + * Some listeners should not be removed when the LoggerContext is + * reset. Such listeners are said to be reset resistant. + * @return whether this listener is reset resistant or not. + */ + boolean isResetResistant(); + + void onStart(LoggerContext context); + + void onReset(LoggerContext context); + + void onStop(LoggerContext context); + + void onLevelChange(Logger logger, Level level); } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextVO.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextVO.java index 5bbe757d3bba01f685403bc5aa8bac0fe49179e8..f9ae5337a8f3c072767bc81290293f50592b7f90 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextVO.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerContextVO.java @@ -35,65 +35,66 @@ import ch.qos.logback.classic.LoggerContext; */ public class LoggerContextVO implements Serializable { - private static final long serialVersionUID = 5488023392483144387L; - - final String name; - final Map propertyMap; - final long birthTime; - - public LoggerContextVO(LoggerContext lc) { - this.name = lc.getName(); - this.propertyMap = lc.getCopyOfPropertyMap(); - this.birthTime = lc.getBirthTime(); - } - - public LoggerContextVO(String name, Map propertyMap, long birthTime) { - this.name = name; - this.propertyMap = propertyMap; - this.birthTime = birthTime; - } - - public String getName() { - return name; - } - - public Map getPropertyMap() { - return propertyMap; - } - - public long getBirthTime() { - return birthTime; - } - - - @Override - public String toString() { - return "LoggerContextVO{" + - "name='" + name + '\'' + - ", propertyMap=" + propertyMap + - ", birthTime=" + birthTime + - '}'; - } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof LoggerContextVO)) return false; - - LoggerContextVO that = (LoggerContextVO) o; - - if (birthTime != that.birthTime) return false; - if (name != null ? !name.equals(that.name) : that.name != null) return false; - if (propertyMap != null ? !propertyMap.equals(that.propertyMap) : that.propertyMap != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = name != null ? name.hashCode() : 0; - result = 31 * result + (propertyMap != null ? propertyMap.hashCode() : 0); - result = 31 * result + (int) (birthTime ^ (birthTime >>> 32)); - - return result; - } + private static final long serialVersionUID = 5488023392483144387L; + + final String name; + final Map propertyMap; + final long birthTime; + + public LoggerContextVO(LoggerContext lc) { + this.name = lc.getName(); + this.propertyMap = lc.getCopyOfPropertyMap(); + this.birthTime = lc.getBirthTime(); + } + + public LoggerContextVO(String name, Map propertyMap, long birthTime) { + this.name = name; + this.propertyMap = propertyMap; + this.birthTime = birthTime; + } + + public String getName() { + return name; + } + + public Map getPropertyMap() { + return propertyMap; + } + + public long getBirthTime() { + return birthTime; + } + + @Override + public String toString() { + return "LoggerContextVO{" + "name='" + name + '\'' + ", propertyMap=" + propertyMap + ", birthTime=" + birthTime + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof LoggerContextVO)) + return false; + + LoggerContextVO that = (LoggerContextVO) o; + + if (birthTime != that.birthTime) + return false; + if (name != null ? !name.equals(that.name) : that.name != null) + return false; + if (propertyMap != null ? !propertyMap.equals(that.propertyMap) : that.propertyMap != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (propertyMap != null ? propertyMap.hashCode() : 0); + result = 31 * result + (int) (birthTime ^ (birthTime >>> 32)); + + return result; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerRemoteView.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerRemoteView.java index 93e693173b15068bde6020d1efcfb0b5edbf241a..3c556c1828e4ecee0b7ec7d02d0311ad30988b7b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerRemoteView.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggerRemoteView.java @@ -28,24 +28,23 @@ import ch.qos.logback.classic.LoggerContext; */ public class LoggerRemoteView implements Serializable { - private static final long serialVersionUID = 5028223666108713696L; + private static final long serialVersionUID = 5028223666108713696L; - final LoggerContextVO loggerContextView; - final String name; + final LoggerContextVO loggerContextView; + final String name; - public LoggerRemoteView(String name, LoggerContext lc) { - this.name = name; - assert lc.getLoggerContextRemoteView() != null; - loggerContextView = lc.getLoggerContextRemoteView(); - } + public LoggerRemoteView(String name, LoggerContext lc) { + this.name = name; + assert lc.getLoggerContextRemoteView() != null; + loggerContextView = lc.getLoggerContextRemoteView(); + } - public LoggerContextVO getLoggerContextView() { - return loggerContextView; - } + public LoggerContextVO getLoggerContextView() { + return loggerContextView; + } - public String getName() { - return name; - } - + public String getName() { + return name; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEvent.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEvent.java index 528c959be80cc8ce9f56ab111556f99d11182b01..135455690849cb6f74d496e9397c6e4656138363 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEvent.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEvent.java @@ -47,320 +47,314 @@ import org.slf4j.spi.MDCAdapter; */ public class LoggingEvent implements ILoggingEvent { - /** - * Fully qualified name of the calling Logger class. This field does not - * survive serialization. - *

- *

- * Note that the getCallerInformation() method relies on this fact. - */ - transient String fqnOfLoggerClass; + /** + * Fully qualified name of the calling Logger class. This field does not + * survive serialization. + *

+ *

+ * Note that the getCallerInformation() method relies on this fact. + */ + transient String fqnOfLoggerClass; + + /** + * The name of thread in which this logging event was generated. + */ + private String threadName; + + private String loggerName; + private LoggerContext loggerContext; + private LoggerContextVO loggerContextVO; + + /** + * Level of logging event. + *

+ *

+ * This field should not be accessed directly. You should use the + * {@link #getLevel} method instead. + *

+ */ + private transient Level level; + + private String message; + + // we gain significant space at serialization time by marking + // formattedMessage as transient and constructing it lazily in + // getFormattedMessage() + transient String formattedMessage; + + private transient Object[] argumentArray; + + private ThrowableProxy throwableProxy; + + private StackTraceElement[] callerDataArray; + + private Marker marker; + + private Map mdcPropertyMap; + + /** + * The number of milliseconds elapsed from 1/1/1970 until logging event was + * created. + */ + private long timeStamp; + + public LoggingEvent() { + } + + public LoggingEvent(String fqcn, Logger logger, Level level, String message, Throwable throwable, Object[] argArray) { + this.fqnOfLoggerClass = fqcn; + this.loggerName = logger.getName(); + this.loggerContext = logger.getLoggerContext(); + this.loggerContextVO = loggerContext.getLoggerContextRemoteView(); + this.level = level; + + this.message = message; + this.argumentArray = argArray; + + if (throwable == null) { + throwable = extractThrowableAnRearrangeArguments(argArray); + } + + if (throwable != null) { + this.throwableProxy = new ThrowableProxy(throwable); + LoggerContext lc = logger.getLoggerContext(); + if (lc.isPackagingDataEnabled()) { + this.throwableProxy.calculatePackagingData(); + } + } + + timeStamp = System.currentTimeMillis(); + } + + private Throwable extractThrowableAnRearrangeArguments(Object[] argArray) { + Throwable extractedThrowable = EventArgUtil.extractThrowable(argArray); + if (EventArgUtil.successfulExtraction(extractedThrowable)) { + this.argumentArray = EventArgUtil.trimmedCopy(argArray); + } + return extractedThrowable; + } + + public void setArgumentArray(Object[] argArray) { + if (this.argumentArray != null) { + throw new IllegalStateException("argArray has been already set"); + } + this.argumentArray = argArray; + } + + public Object[] getArgumentArray() { + return this.argumentArray; + } + + public Level getLevel() { + return level; + } + + public String getLoggerName() { + return loggerName; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + + public String getThreadName() { + if (threadName == null) { + threadName = (Thread.currentThread()).getName(); + } + return threadName; + } + + /** + * @param threadName The threadName to set. + * @throws IllegalStateException If threadName has been already set. + */ + public void setThreadName(String threadName) throws IllegalStateException { + if (this.threadName != null) { + throw new IllegalStateException("threadName has been already set"); + } + this.threadName = threadName; + } + + /** + * Returns the throwable information contained within this event. May be + * null if there is no such information. + */ + public IThrowableProxy getThrowableProxy() { + return throwableProxy; + } + + /** + * Set this event's throwable information. + */ + public void setThrowableProxy(ThrowableProxy tp) { + if (throwableProxy != null) { + throw new IllegalStateException("ThrowableProxy has been already set."); + } else { + throwableProxy = tp; + } + } + + /** + * This method should be called prior to serializing an event. It should also + * be called when using asynchronous or deferred logging. + *

+ *

+ * Note that due to performance concerns, this method does NOT extract caller + * data. It is the responsibility of the caller to extract caller information. + */ + public void prepareForDeferredProcessing() { + this.getFormattedMessage(); + this.getThreadName(); + // fixes http://jira.qos.ch/browse/LBCLASSIC-104 + this.getMDCPropertyMap(); + } + + public LoggerContextVO getLoggerContextVO() { + return loggerContextVO; + } + + public void setLoggerContextRemoteView(LoggerContextVO loggerContextVO) { + this.loggerContextVO = loggerContextVO; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + if (this.message != null) { + throw new IllegalStateException("The message for this event has been set already."); + } + this.message = message; + } + + public long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; + } + + public void setLevel(Level level) { + if (this.level != null) { + throw new IllegalStateException("The level has been already set for this event."); + } + this.level = level; + } + + /** + * Get the caller information for this logging event. If caller information is + * null at the time of its invocation, this method extracts location + * information. The collected information is cached for future use. + *

+ *

+ * Note that after serialization it is impossible to correctly extract caller + * information. + *

+ */ + public StackTraceElement[] getCallerData() { + if (callerDataArray == null) { + callerDataArray = CallerData + .extract(new Throwable(), fqnOfLoggerClass, loggerContext.getMaxCallerDataDepth(), loggerContext.getFrameworkPackages()); + } + return callerDataArray; + } + + public boolean hasCallerData() { + return (callerDataArray != null); + } + + public void setCallerData(StackTraceElement[] callerDataArray) { + this.callerDataArray = callerDataArray; + } - /** - * The name of thread in which this logging event was generated. - */ - private String threadName; + public Marker getMarker() { + return marker; + } + + public void setMarker(Marker marker) { + if (this.marker != null) { + throw new IllegalStateException("The marker has been already set for this event."); + } + this.marker = marker; + } + + public long getContextBirthTime() { + return loggerContextVO.getBirthTime(); + } + + // lazy computation as suggested in LOGBACK-495 + public String getFormattedMessage() { + if (formattedMessage != null) { + return formattedMessage; + } + if (argumentArray != null) { + formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage(); + } else { + formattedMessage = message; + } + + return formattedMessage; + } - private String loggerName; - private LoggerContext loggerContext; - private LoggerContextVO loggerContextVO; + public Map getMDCPropertyMap() { + // populate mdcPropertyMap if null + if (mdcPropertyMap == null) { + MDCAdapter mdc = MDC.getMDCAdapter(); + if (mdc instanceof LogbackMDCAdapter) + mdcPropertyMap = ((LogbackMDCAdapter) mdc).getPropertyMap(); + else + mdcPropertyMap = mdc.getCopyOfContextMap(); + } + // mdcPropertyMap still null, use emptyMap() + if (mdcPropertyMap == null) + mdcPropertyMap = Collections.emptyMap(); + + return mdcPropertyMap; + } - /** - * Level of logging event. - *

- *

- * This field should not be accessed directly. You should use the - * {@link #getLevel} method instead. - *

- */ - private transient Level level; - - private String message; + /** + * Set the MDC map for this event. + * + * @param map + * @since 1.0.8 + */ + public void setMDCPropertyMap(Map map) { + if (mdcPropertyMap != null) { + throw new IllegalStateException("The MDCPropertyMap has been already set for this event."); + } + this.mdcPropertyMap = map; - // we gain significant space at serialization time by marking - // formattedMessage as transient and constructing it lazily in - // getFormattedMessage() - transient String formattedMessage; - - private transient Object[] argumentArray; - - private ThrowableProxy throwableProxy; - - private StackTraceElement[] callerDataArray; - - private Marker marker; - - private Map mdcPropertyMap; - - /** - * The number of milliseconds elapsed from 1/1/1970 until logging event was - * created. - */ - private long timeStamp; - - public LoggingEvent() { - } - - public LoggingEvent(String fqcn, Logger logger, Level level, String message, - Throwable throwable, Object[] argArray) { - this.fqnOfLoggerClass = fqcn; - this.loggerName = logger.getName(); - this.loggerContext = logger.getLoggerContext(); - this.loggerContextVO = loggerContext.getLoggerContextRemoteView(); - this.level = level; - - this.message = message; - this.argumentArray = argArray; - - if(throwable == null) { - throwable = extractThrowableAnRearrangeArguments(argArray); - } - - if (throwable != null) { - this.throwableProxy = new ThrowableProxy(throwable); - LoggerContext lc = logger.getLoggerContext(); - if (lc.isPackagingDataEnabled()) { - this.throwableProxy.calculatePackagingData(); - } - } - - timeStamp = System.currentTimeMillis(); - } - - private Throwable extractThrowableAnRearrangeArguments(Object[] argArray) { - Throwable extractedThrowable = EventArgUtil.extractThrowable(argArray); - if(EventArgUtil.successfulExtraction(extractedThrowable)) { - this.argumentArray = EventArgUtil.trimmedCopy(argArray); - } - return extractedThrowable; - } - - public void setArgumentArray(Object[] argArray) { - if (this.argumentArray != null) { - throw new IllegalStateException("argArray has been already set"); - } - this.argumentArray = argArray; - } - - public Object[] getArgumentArray() { - return this.argumentArray; - } - - public Level getLevel() { - return level; - } - - public String getLoggerName() { - return loggerName; - } - - public void setLoggerName(String loggerName) { - this.loggerName = loggerName; - } - - public String getThreadName() { - if (threadName == null) { - threadName = (Thread.currentThread()).getName(); - } - return threadName; - } - - /** - * @param threadName The threadName to set. - * @throws IllegalStateException If threadName has been already set. - */ - public void setThreadName(String threadName) throws IllegalStateException { - if (this.threadName != null) { - throw new IllegalStateException("threadName has been already set"); - } - this.threadName = threadName; - } - - /** - * Returns the throwable information contained within this event. May be - * null if there is no such information. - */ - public IThrowableProxy getThrowableProxy() { - return throwableProxy; - } - - /** - * Set this event's throwable information. - */ - public void setThrowableProxy(ThrowableProxy tp) { - if (throwableProxy != null) { - throw new IllegalStateException("ThrowableProxy has been already set."); - } else { - throwableProxy = tp; - } - } - - /** - * This method should be called prior to serializing an event. It should also - * be called when using asynchronous or deferred logging. - *

- *

- * Note that due to performance concerns, this method does NOT extract caller - * data. It is the responsibility of the caller to extract caller information. - */ - public void prepareForDeferredProcessing() { - this.getFormattedMessage(); - this.getThreadName(); - // fixes http://jira.qos.ch/browse/LBCLASSIC-104 - this.getMDCPropertyMap(); - } - - public LoggerContextVO getLoggerContextVO() { - return loggerContextVO; - } - - public void setLoggerContextRemoteView(LoggerContextVO loggerContextVO) { - this.loggerContextVO = loggerContextVO; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - if (this.message != null) { - throw new IllegalStateException( - "The message for this event has been set already."); - } - this.message = message; - } - - public long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(long timeStamp) { - this.timeStamp = timeStamp; - } - - public void setLevel(Level level) { - if (this.level != null) { - throw new IllegalStateException( - "The level has been already set for this event."); - } - this.level = level; - } - - /** - * Get the caller information for this logging event. If caller information is - * null at the time of its invocation, this method extracts location - * information. The collected information is cached for future use. - *

- *

- * Note that after serialization it is impossible to correctly extract caller - * information. - *

- */ - public StackTraceElement[] getCallerData() { - if (callerDataArray == null) { - callerDataArray = CallerData.extract(new Throwable(), fqnOfLoggerClass, - loggerContext.getMaxCallerDataDepth(), loggerContext.getFrameworkPackages()); - } - return callerDataArray; - } - - public boolean hasCallerData() { - return (callerDataArray != null); - } - - public void setCallerData(StackTraceElement[] callerDataArray) { - this.callerDataArray = callerDataArray; - } - - public Marker getMarker() { - return marker; - } - - public void setMarker(Marker marker) { - if (this.marker != null) { - throw new IllegalStateException( - "The marker has been already set for this event."); - } - this.marker = marker; - } - - public long getContextBirthTime() { - return loggerContextVO.getBirthTime(); - } - - // lazy computation as suggested in LOGBACK-495 - public String getFormattedMessage() { - if (formattedMessage != null) { - return formattedMessage; - } - if (argumentArray != null) { - formattedMessage = MessageFormatter.arrayFormat(message, argumentArray) - .getMessage(); - } else { - formattedMessage = message; - } - - return formattedMessage; - } - - public Map getMDCPropertyMap() { - // populate mdcPropertyMap if null - if (mdcPropertyMap == null) { - MDCAdapter mdc = MDC.getMDCAdapter(); - if (mdc instanceof LogbackMDCAdapter) - mdcPropertyMap = ((LogbackMDCAdapter) mdc).getPropertyMap(); - else - mdcPropertyMap = mdc.getCopyOfContextMap(); - } - // mdcPropertyMap still null, use emptyMap() - if (mdcPropertyMap == null) - mdcPropertyMap = Collections.emptyMap(); - - return mdcPropertyMap; - } - - /** - * Set the MDC map for this event. - * - * @param map - * @since 1.0.8 - */ - public void setMDCPropertyMap(Map map) { - if (mdcPropertyMap != null) { - throw new IllegalStateException( - "The MDCPropertyMap has been already set for this event."); - } - this.mdcPropertyMap = map; - - } - - /** - * Synonym for [@link #getMDCPropertyMap}. - * - * @deprecated Replaced by [@link #getMDCPropertyMap} - */ - public Map getMdc() { - return getMDCPropertyMap(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append('['); - sb.append(level).append("] "); - sb.append(getFormattedMessage()); - return sb.toString(); - } - - /** - * LoggerEventVO instances should be used for serialization. Use - * {@link LoggingEventVO#build(ILoggingEvent) build} method to create the LoggerEventVO instance. - * - * @since 1.0.11 - */ - private void writeObject(ObjectOutputStream out) throws IOException { - throw new UnsupportedOperationException(this.getClass() + " does not support serialization. " + - "Use LoggerEventVO instance instead. See also LoggerEventVO.build method."); - } + } + + /** + * Synonym for [@link #getMDCPropertyMap}. + * + * @deprecated Replaced by [@link #getMDCPropertyMap} + */ + public Map getMdc() { + return getMDCPropertyMap(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('['); + sb.append(level).append("] "); + sb.append(getFormattedMessage()); + return sb.toString(); + } + + /** + * LoggerEventVO instances should be used for serialization. Use + * {@link LoggingEventVO#build(ILoggingEvent) build} method to create the LoggerEventVO instance. + * + * @since 1.0.11 + */ + private void writeObject(ObjectOutputStream out) throws IOException { + throw new UnsupportedOperationException(this.getClass() + " does not support serialization. " + + "Use LoggerEventVO instance instead. See also LoggerEventVO.build method."); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEventVO.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEventVO.java index f166e67b4514d5afacf0cb71b20676737c3255c4..e21350b2cc5520b624e1c6b3c5af9f45db87754f 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEventVO.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/LoggingEventVO.java @@ -34,216 +34,214 @@ import ch.qos.logback.classic.Level; */ public class LoggingEventVO implements ILoggingEvent, Serializable { - private static final long serialVersionUID = 6553722650255690312L; - - private static final int NULL_ARGUMENT_ARRAY = -1; - private static final String NULL_ARGUMENT_ARRAY_ELEMENT = "NULL_ARGUMENT_ARRAY_ELEMENT"; - - private String threadName; - private String loggerName; - private LoggerContextVO loggerContextVO; - - private transient Level level; - private String message; - - // we gain significant space at serialization time by marking - // formattedMessage as transient and constructing it lazily in - // getFormattedMessage() - private transient String formattedMessage; - - private transient Object[] argumentArray; - - private ThrowableProxyVO throwableProxy; - private StackTraceElement[] callerDataArray; - private Marker marker; - private Map mdcPropertyMap; - private long timeStamp; - - public static LoggingEventVO build(ILoggingEvent le) { - LoggingEventVO ledo = new LoggingEventVO(); - ledo.loggerName = le.getLoggerName(); - ledo.loggerContextVO = le.getLoggerContextVO(); - ledo.threadName = le.getThreadName(); - ledo.level = (le.getLevel()); - ledo.message = (le.getMessage()); - ledo.argumentArray = (le.getArgumentArray()); - ledo.marker = le.getMarker(); - ledo.mdcPropertyMap = le.getMDCPropertyMap(); - ledo.timeStamp = le.getTimeStamp(); - ledo.throwableProxy = ThrowableProxyVO.build(le.getThrowableProxy()); - // add caller data only if it is there already - // fixes http://jira.qos.ch/browse/LBCLASSIC-145 - if (le.hasCallerData()) { - ledo.callerDataArray = le.getCallerData(); - } - return ledo; - } - - public String getThreadName() { - return threadName; - } - - public LoggerContextVO getLoggerContextVO() { - return loggerContextVO; - } - - public String getLoggerName() { - return loggerName; - } - - public Level getLevel() { - return level; - } - - public String getMessage() { - return message; - } - - public String getFormattedMessage() { - if (formattedMessage != null) { - return formattedMessage; - } - - if (argumentArray != null) { - formattedMessage = MessageFormatter.arrayFormat(message, argumentArray) - .getMessage(); - } else { - formattedMessage = message; - } - - return formattedMessage; - } - - public Object[] getArgumentArray() { - return argumentArray; - } - - public IThrowableProxy getThrowableProxy() { - return throwableProxy; - } - - public StackTraceElement[] getCallerData() { - return callerDataArray; - } - - public boolean hasCallerData() { - return callerDataArray != null; - } - - public Marker getMarker() { - return marker; - } - - public long getTimeStamp() { - return timeStamp; - } - - public long getContextBirthTime() { - return loggerContextVO.getBirthTime(); - } - - public LoggerContextVO getContextLoggerRemoteView() { - return loggerContextVO; - } - - public Map getMDCPropertyMap() { - return mdcPropertyMap; - } - public Map getMdc() { - return mdcPropertyMap; - } - - public void prepareForDeferredProcessing() { - } - - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeInt(level.levelInt); - if (argumentArray != null) { - int len = argumentArray.length; - out.writeInt(len); - for (int i = 0; i < argumentArray.length; i++) { - if (argumentArray[i] != null) { - out.writeObject(argumentArray[i].toString()); + private static final long serialVersionUID = 6553722650255690312L; + + private static final int NULL_ARGUMENT_ARRAY = -1; + private static final String NULL_ARGUMENT_ARRAY_ELEMENT = "NULL_ARGUMENT_ARRAY_ELEMENT"; + + private String threadName; + private String loggerName; + private LoggerContextVO loggerContextVO; + + private transient Level level; + private String message; + + // we gain significant space at serialization time by marking + // formattedMessage as transient and constructing it lazily in + // getFormattedMessage() + private transient String formattedMessage; + + private transient Object[] argumentArray; + + private ThrowableProxyVO throwableProxy; + private StackTraceElement[] callerDataArray; + private Marker marker; + private Map mdcPropertyMap; + private long timeStamp; + + public static LoggingEventVO build(ILoggingEvent le) { + LoggingEventVO ledo = new LoggingEventVO(); + ledo.loggerName = le.getLoggerName(); + ledo.loggerContextVO = le.getLoggerContextVO(); + ledo.threadName = le.getThreadName(); + ledo.level = (le.getLevel()); + ledo.message = (le.getMessage()); + ledo.argumentArray = (le.getArgumentArray()); + ledo.marker = le.getMarker(); + ledo.mdcPropertyMap = le.getMDCPropertyMap(); + ledo.timeStamp = le.getTimeStamp(); + ledo.throwableProxy = ThrowableProxyVO.build(le.getThrowableProxy()); + // add caller data only if it is there already + // fixes http://jira.qos.ch/browse/LBCLASSIC-145 + if (le.hasCallerData()) { + ledo.callerDataArray = le.getCallerData(); + } + return ledo; + } + + public String getThreadName() { + return threadName; + } + + public LoggerContextVO getLoggerContextVO() { + return loggerContextVO; + } + + public String getLoggerName() { + return loggerName; + } + + public Level getLevel() { + return level; + } + + public String getMessage() { + return message; + } + + public String getFormattedMessage() { + if (formattedMessage != null) { + return formattedMessage; + } + + if (argumentArray != null) { + formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage(); + } else { + formattedMessage = message; + } + + return formattedMessage; + } + + public Object[] getArgumentArray() { + return argumentArray; + } + + public IThrowableProxy getThrowableProxy() { + return throwableProxy; + } + + public StackTraceElement[] getCallerData() { + return callerDataArray; + } + + public boolean hasCallerData() { + return callerDataArray != null; + } + + public Marker getMarker() { + return marker; + } + + public long getTimeStamp() { + return timeStamp; + } + + public long getContextBirthTime() { + return loggerContextVO.getBirthTime(); + } + + public LoggerContextVO getContextLoggerRemoteView() { + return loggerContextVO; + } + + public Map getMDCPropertyMap() { + return mdcPropertyMap; + } + + public Map getMdc() { + return mdcPropertyMap; + } + + public void prepareForDeferredProcessing() { + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeInt(level.levelInt); + if (argumentArray != null) { + int len = argumentArray.length; + out.writeInt(len); + for (int i = 0; i < argumentArray.length; i++) { + if (argumentArray[i] != null) { + out.writeObject(argumentArray[i].toString()); + } else { + out.writeObject(NULL_ARGUMENT_ARRAY_ELEMENT); + } + } } else { - out.writeObject(NULL_ARGUMENT_ARRAY_ELEMENT); + out.writeInt(NULL_ARGUMENT_ARRAY); } - } - } else { - out.writeInt(NULL_ARGUMENT_ARRAY); - } - - } - - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - int levelInt = in.readInt(); - level = Level.toLevel(levelInt); - - int argArrayLen = in.readInt(); - if (argArrayLen != NULL_ARGUMENT_ARRAY) { - argumentArray = new String[argArrayLen]; - for (int i = 0; i < argArrayLen; i++) { - Object val = in.readObject(); - if (!NULL_ARGUMENT_ARRAY_ELEMENT.equals(val)) { - argumentArray[i] = val; + + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + int levelInt = in.readInt(); + level = Level.toLevel(levelInt); + + int argArrayLen = in.readInt(); + if (argArrayLen != NULL_ARGUMENT_ARRAY) { + argumentArray = new String[argArrayLen]; + for (int i = 0; i < argArrayLen; i++) { + Object val = in.readObject(); + if (!NULL_ARGUMENT_ARRAY_ELEMENT.equals(val)) { + argumentArray[i] = val; + } + } } - } - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result - + ((threadName == null) ? 0 : threadName.hashCode()); - result = prime * result + (int) (timeStamp ^ (timeStamp >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final LoggingEventVO other = (LoggingEventVO) obj; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - - if (loggerName == null) { - if (other.loggerName != null) - return false; - } else if (!loggerName.equals(other.loggerName)) - return false; - - if (threadName == null) { - if (other.threadName != null) - return false; - } else if (!threadName.equals(other.threadName)) - return false; - if (timeStamp != other.timeStamp) - return false; - - if (marker == null) { - if (other.marker != null) - return false; - } else if (!marker.equals(other.marker)) - return false; - - if (mdcPropertyMap == null) { - if (other.mdcPropertyMap != null) - return false; - } else if (!mdcPropertyMap.equals(other.mdcPropertyMap)) - return false; - return true; - } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((threadName == null) ? 0 : threadName.hashCode()); + result = prime * result + (int) (timeStamp ^ (timeStamp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final LoggingEventVO other = (LoggingEventVO) obj; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + + if (loggerName == null) { + if (other.loggerName != null) + return false; + } else if (!loggerName.equals(other.loggerName)) + return false; + + if (threadName == null) { + if (other.threadName != null) + return false; + } else if (!threadName.equals(other.threadName)) + return false; + if (timeStamp != other.timeStamp) + return false; + + if (marker == null) { + if (other.marker != null) + return false; + } else if (!marker.equals(other.marker)) + return false; + + if (mdcPropertyMap == null) { + if (other.mdcPropertyMap != null) + return false; + } else if (!mdcPropertyMap.equals(other.mdcPropertyMap)) + return false; + return true; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java index ffd4d74bc522b3bcb42a63d39c47d2acf61cda68..e5cd7f82496def44a709dd88a9203f26305a0c67 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java @@ -18,6 +18,7 @@ import java.security.CodeSource; import java.util.HashMap; import sun.reflect.Reflection; + // import java.security.AccessControlException; import java.security.AccessController;import java.security.PrivilegedAction; /** * Given a classname locate associated PackageInfo (jar name, version name). @@ -27,224 +28,219 @@ import sun.reflect.Reflection; */ public class PackagingDataCalculator { - final static StackTraceElementProxy[] STEP_ARRAY_TEMPLATE = new StackTraceElementProxy[0]; - - HashMap cache = new HashMap(); - - private static boolean GET_CALLER_CLASS_METHOD_AVAILABLE = false; //private static boolean HAS_GET_CLASS_LOADER_PERMISSION = false; - - static { - // if either the Reflection class or the getCallerClass method - // are unavailable, then we won't invoke Reflection.getCallerClass() - // This approach ensures that this class will *run* on JDK's lacking - // sun.reflect.Reflection class. However, this class will *not compile* - // on JDKs lacking sun.reflect.Reflection. - try { - Reflection.getCallerClass(2); - GET_CALLER_CLASS_METHOD_AVAILABLE = true; - } catch (NoClassDefFoundError e) { - } catch (NoSuchMethodError e) { - } catch (UnsupportedOperationException e) { - } catch (Throwable e) { - System.err.println("Unexpected exception"); - e.printStackTrace(); + final static StackTraceElementProxy[] STEP_ARRAY_TEMPLATE = new StackTraceElementProxy[0]; + + HashMap cache = new HashMap(); + + private static boolean GET_CALLER_CLASS_METHOD_AVAILABLE = false; // private static boolean + // HAS_GET_CLASS_LOADER_PERMISSION = false; + + static { + // if either the Reflection class or the getCallerClass method + // are unavailable, then we won't invoke Reflection.getCallerClass() + // This approach ensures that this class will *run* on JDK's lacking + // sun.reflect.Reflection class. However, this class will *not compile* + // on JDKs lacking sun.reflect.Reflection. + try { + Reflection.getCallerClass(2); + GET_CALLER_CLASS_METHOD_AVAILABLE = true; + } catch (NoClassDefFoundError e) { + } catch (NoSuchMethodError e) { + } catch (UnsupportedOperationException e) { + } catch (Throwable e) { + System.err.println("Unexpected exception"); + e.printStackTrace(); + } } - } - - public void calculate(IThrowableProxy tp) { - while (tp != null) { - populateFrames(tp.getStackTraceElementProxyArray()); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current:suppressed) { - populateFrames(current.getStackTraceElementProxyArray()); + public void calculate(IThrowableProxy tp) { + while (tp != null) { + populateFrames(tp.getStackTraceElementProxyArray()); + IThrowableProxy[] suppressed = tp.getSuppressed(); + if (suppressed != null) { + for (IThrowableProxy current : suppressed) { + populateFrames(current.getStackTraceElementProxyArray()); + } + } + tp = tp.getCause(); } - } - tp = tp.getCause(); - } - } - - void populateFrames(StackTraceElementProxy[] stepArray) { - // in the initial part of this method we populate package information for - // common stack frames - final Throwable t = new Throwable("local stack reference"); - final StackTraceElement[] localteSTEArray = t.getStackTrace(); - final int commonFrames = STEUtil.findNumberOfCommonFrames(localteSTEArray, - stepArray); - final int localFirstCommon = localteSTEArray.length - commonFrames; - final int stepFirstCommon = stepArray.length - commonFrames; - - ClassLoader lastExactClassLoader = null; - ClassLoader firsExactClassLoader = null; - - int missfireCount = 0; - for (int i = 0; i < commonFrames; i++) { - Class callerClass = null; - if (GET_CALLER_CLASS_METHOD_AVAILABLE) { - callerClass = Reflection.getCallerClass(localFirstCommon + i - - missfireCount + 1); - } - StackTraceElementProxy step = stepArray[stepFirstCommon + i]; - String stepClassname = step.ste.getClassName(); - - if (callerClass != null && stepClassname.equals(callerClass.getName())) { - // see also LBCLASSIC-263 - lastExactClassLoader = callerClass.getClassLoader(); - if (firsExactClassLoader == null) { - firsExactClassLoader = lastExactClassLoader; - } - ClassPackagingData pi = calculateByExactType(callerClass); - step.setClassPackagingData(pi); - } else { - missfireCount++; - ClassPackagingData pi = computeBySTEP(step, lastExactClassLoader); - step.setClassPackagingData(pi); - } } - populateUncommonFrames(commonFrames, stepArray, firsExactClassLoader); - } - - void populateUncommonFrames(int commonFrames, - StackTraceElementProxy[] stepArray, ClassLoader firstExactClassLoader) { - int uncommonFrames = stepArray.length - commonFrames; - for (int i = 0; i < uncommonFrames; i++) { - StackTraceElementProxy step = stepArray[i]; - ClassPackagingData pi = computeBySTEP(step, firstExactClassLoader); - step.setClassPackagingData(pi); - } - } - private ClassPackagingData calculateByExactType(Class type) { - String className = type.getName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; + void populateFrames(StackTraceElementProxy[] stepArray) { + // in the initial part of this method we populate package information for + // common stack frames + final Throwable t = new Throwable("local stack reference"); + final StackTraceElement[] localteSTEArray = t.getStackTrace(); + final int commonFrames = STEUtil.findNumberOfCommonFrames(localteSTEArray, stepArray); + final int localFirstCommon = localteSTEArray.length - commonFrames; + final int stepFirstCommon = stepArray.length - commonFrames; + + ClassLoader lastExactClassLoader = null; + ClassLoader firsExactClassLoader = null; + + int missfireCount = 0; + for (int i = 0; i < commonFrames; i++) { + Class callerClass = null; + if (GET_CALLER_CLASS_METHOD_AVAILABLE) { + callerClass = Reflection.getCallerClass(localFirstCommon + i - missfireCount + 1); + } + StackTraceElementProxy step = stepArray[stepFirstCommon + i]; + String stepClassname = step.ste.getClassName(); + + if (callerClass != null && stepClassname.equals(callerClass.getName())) { + // see also LBCLASSIC-263 + lastExactClassLoader = callerClass.getClassLoader(); + if (firsExactClassLoader == null) { + firsExactClassLoader = lastExactClassLoader; + } + ClassPackagingData pi = calculateByExactType(callerClass); + step.setClassPackagingData(pi); + } else { + missfireCount++; + ClassPackagingData pi = computeBySTEP(step, lastExactClassLoader); + step.setClassPackagingData(pi); + } + } + populateUncommonFrames(commonFrames, stepArray, firsExactClassLoader); } - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version); - cache.put(className, cpd); - return cpd; - } - - private ClassPackagingData computeBySTEP(StackTraceElementProxy step, - ClassLoader lastExactClassLoader) { - String className = step.ste.getClassName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; + + void populateUncommonFrames(int commonFrames, StackTraceElementProxy[] stepArray, ClassLoader firstExactClassLoader) { + int uncommonFrames = stepArray.length - commonFrames; + for (int i = 0; i < uncommonFrames; i++) { + StackTraceElementProxy step = stepArray[i]; + ClassPackagingData pi = computeBySTEP(step, firstExactClassLoader); + step.setClassPackagingData(pi); + } } - Class type = bestEffortLoadClass(lastExactClassLoader, className); - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version, false); - cache.put(className, cpd); - return cpd; - } - - String getImplementationVersion(Class type) { - if (type == null) { - return "na"; + + private ClassPackagingData calculateByExactType(Class type) { + String className = type.getName(); + ClassPackagingData cpd = cache.get(className); + if (cpd != null) { + return cpd; + } + String version = getImplementationVersion(type); + String codeLocation = getCodeLocation(type); + cpd = new ClassPackagingData(codeLocation, version); + cache.put(className, cpd); + return cpd; + } + + private ClassPackagingData computeBySTEP(StackTraceElementProxy step, ClassLoader lastExactClassLoader) { + String className = step.ste.getClassName(); + ClassPackagingData cpd = cache.get(className); + if (cpd != null) { + return cpd; + } + Class type = bestEffortLoadClass(lastExactClassLoader, className); + String version = getImplementationVersion(type); + String codeLocation = getCodeLocation(type); + cpd = new ClassPackagingData(codeLocation, version, false); + cache.put(className, cpd); + return cpd; } - Package aPackage = type.getPackage(); - if (aPackage != null) { - String v = aPackage.getImplementationVersion(); - if (v == null) { + + String getImplementationVersion(Class type) { + if (type == null) { + return "na"; + } + Package aPackage = type.getPackage(); + if (aPackage != null) { + String v = aPackage.getImplementationVersion(); + if (v == null) { + return "na"; + } else { + return v; + } + } return "na"; - } else { - return v; - } + } - return "na"; - - } - - String getCodeLocation(Class type) { - try { - if (type != null) { - // file:/C:/java/maven-2.0.8/repo/com/icegreen/greenmail/1.3/greenmail-1.3.jar - CodeSource codeSource = type.getProtectionDomain().getCodeSource(); - if (codeSource != null) { - URL resource = codeSource.getLocation(); - if (resource != null) { - String locationStr = resource.toString(); - // now lets remove all but the file name - String result = getCodeLocation(locationStr, '/'); - if (result != null) { - return result; + + String getCodeLocation(Class type) { + try { + if (type != null) { + // file:/C:/java/maven-2.0.8/repo/com/icegreen/greenmail/1.3/greenmail-1.3.jar + CodeSource codeSource = type.getProtectionDomain().getCodeSource(); + if (codeSource != null) { + URL resource = codeSource.getLocation(); + if (resource != null) { + String locationStr = resource.toString(); + // now lets remove all but the file name + String result = getCodeLocation(locationStr, '/'); + if (result != null) { + return result; + } + return getCodeLocation(locationStr, '\\'); + } + } } - return getCodeLocation(locationStr, '\\'); - } + } catch (Exception e) { + // ignore } - } - } catch (Exception e) { - // ignore - } - return "na"; - } - - private String getCodeLocation(String locationStr, char separator) { - int idx = locationStr.lastIndexOf(separator); - if (isFolder(idx, locationStr)) { - idx = locationStr.lastIndexOf(separator, idx - 1); - return locationStr.substring(idx + 1); - } else if (idx > 0) { - return locationStr.substring(idx + 1); + return "na"; } - return null; - } - private boolean isFolder(int idx, String text) { - return (idx != -1 && idx + 1 == text.length()); - } - - private Class loadClass(ClassLoader cl, String className) { - if (cl == null) { - return null; - } - try { - return cl.loadClass(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; + private String getCodeLocation(String locationStr, char separator) { + int idx = locationStr.lastIndexOf(separator); + if (isFolder(idx, locationStr)) { + idx = locationStr.lastIndexOf(separator, idx - 1); + return locationStr.substring(idx + 1); + } else if (idx > 0) { + return locationStr.substring(idx + 1); + } + return null; } - } - - /** - * @param lastGuaranteedClassLoader may be null - * @param className - * @return - */ - private Class bestEffortLoadClass(ClassLoader lastGuaranteedClassLoader, - String className) { - Class result = loadClass(lastGuaranteedClassLoader, className); - if (result != null) { - return result; - } - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl != lastGuaranteedClassLoader) { - result = loadClass(tccl, className); + private boolean isFolder(int idx, String text) { + return (idx != -1 && idx + 1 == text.length()); } - if (result != null) { - return result; + + private Class loadClass(ClassLoader cl, String className) { + if (cl == null) { + return null; + } + try { + return cl.loadClass(className); + } catch (ClassNotFoundException e1) { + return null; + } catch (NoClassDefFoundError e1) { + return null; + } catch (Exception e) { + e.printStackTrace(); // this is unexpected + return null; + } + } - try { - return Class.forName(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; + /** + * @param lastGuaranteedClassLoader may be null + * @param className + * @return + */ + private Class bestEffortLoadClass(ClassLoader lastGuaranteedClassLoader, String className) { + Class result = loadClass(lastGuaranteedClassLoader, className); + if (result != null) { + return result; + } + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + if (tccl != lastGuaranteedClassLoader) { + result = loadClass(tccl, className); + } + if (result != null) { + return result; + } + + try { + return Class.forName(className); + } catch (ClassNotFoundException e1) { + return null; + } catch (NoClassDefFoundError e1) { + return null; + } catch (Exception e) { + e.printStackTrace(); // this is unexpected + return null; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PlatformInfo.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PlatformInfo.java index 5d01ab18ebd056b216bbc8b1b26ac61e91abbd52..3c89f7d6adf105a82bd24c9424c01b7349958fca 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PlatformInfo.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PlatformInfo.java @@ -20,19 +20,19 @@ package ch.qos.logback.classic.spi; * */ public class PlatformInfo { - private static final int UNINITIALIZED = -1; + private static final int UNINITIALIZED = -1; - private static int hasJMXObjectName = UNINITIALIZED; - - public static boolean hasJMXObjectName() { - if (hasJMXObjectName == UNINITIALIZED) { - try { - Class.forName("javax.management.ObjectName"); - hasJMXObjectName = 1; - } catch (Throwable e) { - hasJMXObjectName = 0; - } + private static int hasJMXObjectName = UNINITIALIZED; + + public static boolean hasJMXObjectName() { + if (hasJMXObjectName == UNINITIALIZED) { + try { + Class.forName("javax.management.ObjectName"); + hasJMXObjectName = 1; + } catch (Throwable e) { + hasJMXObjectName = 0; + } + } + return (hasJMXObjectName == 1); } - return (hasJMXObjectName == 1); - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/STEUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/STEUtil.java index 8d52c975846f6f8721054646307bf8abb7e45528..94b408f2d5a4b7df61378823efa2c57ab0a0ab9b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/STEUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/STEUtil.java @@ -15,47 +15,43 @@ package ch.qos.logback.classic.spi; public class STEUtil { - - static int UNUSED_findNumberOfCommonFrames(StackTraceElement[] steArray, - StackTraceElement[] otherSTEArray) { - if (otherSTEArray == null) { - return 0; - } + static int UNUSED_findNumberOfCommonFrames(StackTraceElement[] steArray, StackTraceElement[] otherSTEArray) { + if (otherSTEArray == null) { + return 0; + } - int steIndex = steArray.length - 1; - int parentIndex = otherSTEArray.length - 1; - int count = 0; - while (steIndex >= 0 && parentIndex >= 0) { - if (steArray[steIndex].equals(otherSTEArray[parentIndex])) { - count++; - } else { - break; - } - steIndex--; - parentIndex--; - } - return count; - } - - - static int findNumberOfCommonFrames(StackTraceElement[] steArray, - StackTraceElementProxy[] otherSTEPArray) { - if (otherSTEPArray == null) { - return 0; + int steIndex = steArray.length - 1; + int parentIndex = otherSTEArray.length - 1; + int count = 0; + while (steIndex >= 0 && parentIndex >= 0) { + if (steArray[steIndex].equals(otherSTEArray[parentIndex])) { + count++; + } else { + break; + } + steIndex--; + parentIndex--; + } + return count; } - int steIndex = steArray.length - 1; - int parentIndex = otherSTEPArray.length - 1; - int count = 0; - while (steIndex >= 0 && parentIndex >= 0) { - if (steArray[steIndex].equals(otherSTEPArray[parentIndex].ste)) { - count++; - } else { - break; - } - steIndex--; - parentIndex--; + static int findNumberOfCommonFrames(StackTraceElement[] steArray, StackTraceElementProxy[] otherSTEPArray) { + if (otherSTEPArray == null) { + return 0; + } + + int steIndex = steArray.length - 1; + int parentIndex = otherSTEPArray.length - 1; + int count = 0; + while (steIndex >= 0 && parentIndex >= 0) { + if (steArray[steIndex].equals(otherSTEPArray[parentIndex].ste)) { + count++; + } else { + break; + } + steIndex--; + parentIndex--; + } + return count; } - return count; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/StackTraceElementProxy.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/StackTraceElementProxy.java index f64832d4dc05f2d1bc42b34af536ea4d615b89c2..f1f38768774cbc63a4fe9e49fba14e6ab1c2df56 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/StackTraceElementProxy.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/StackTraceElementProxy.java @@ -17,74 +17,73 @@ import java.io.Serializable; public class StackTraceElementProxy implements Serializable { - private static final long serialVersionUID = -2374374378980555982L; - - final StackTraceElement ste; - // save a byte or two during serialization, as we can - // reconstruct this field from 'ste' - transient private String steAsString; - private ClassPackagingData cpd; + private static final long serialVersionUID = -2374374378980555982L; - public StackTraceElementProxy(StackTraceElement ste) { - if (ste == null) { - throw new IllegalArgumentException("ste cannot be null"); - } - this.ste = ste; - } + final StackTraceElement ste; + // save a byte or two during serialization, as we can + // reconstruct this field from 'ste' + transient private String steAsString; + private ClassPackagingData cpd; - - public String getSTEAsString() { - if (steAsString == null) { - steAsString = "at " + ste.toString(); + public StackTraceElementProxy(StackTraceElement ste) { + if (ste == null) { + throw new IllegalArgumentException("ste cannot be null"); + } + this.ste = ste; } - return steAsString; - } - - public StackTraceElement getStackTraceElement() { - return ste; - } - - public void setClassPackagingData(ClassPackagingData cpd) { - if(this.cpd != null) { - throw new IllegalStateException("Packaging data has been already set"); + + public String getSTEAsString() { + if (steAsString == null) { + steAsString = "at " + ste.toString(); + } + return steAsString; } - this.cpd = cpd; - } - public ClassPackagingData getClassPackagingData() { - return cpd; - } + public StackTraceElement getStackTraceElement() { + return ste; + } - @Override - public int hashCode() { - return ste.hashCode(); - } + public void setClassPackagingData(ClassPackagingData cpd) { + if (this.cpd != null) { + throw new IllegalStateException("Packaging data has been already set"); + } + this.cpd = cpd; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final StackTraceElementProxy other = (StackTraceElementProxy) obj; + public ClassPackagingData getClassPackagingData() { + return cpd; + } - if (!ste.equals(other.ste)) { - return false; + @Override + public int hashCode() { + return ste.hashCode(); } - if (cpd == null) { - if (other.cpd != null) { - return false; - } - } else if (!cpd.equals(other.cpd)) { - return false; + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final StackTraceElementProxy other = (StackTraceElementProxy) obj; + + if (!ste.equals(other.ste)) { + return false; + } + if (cpd == null) { + if (other.cpd != null) { + return false; + } + } else if (!cpd.equals(other.cpd)) { + return false; + } + return true; } - return true; - } - @Override - public String toString() { - return getSTEAsString(); - } + @Override + public String toString() { + return getSTEAsString(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxy.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxy.java index e288a04b162111354f93beee86e931f438233702..93775a28b0a46aa42b24042bc47689a0bae12b16 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxy.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxy.java @@ -20,146 +20,138 @@ import java.lang.reflect.Method; public class ThrowableProxy implements IThrowableProxy { - private Throwable throwable; - private String className; - private String message; - // package-private because of ThrowableProxyUtil - StackTraceElementProxy[] stackTraceElementProxyArray; - // package-private because of ThrowableProxyUtil - int commonFrames; - private ThrowableProxy cause; - private ThrowableProxy[] suppressed=NO_SUPPRESSED; - - private transient PackagingDataCalculator packagingDataCalculator; - private boolean calculatedPackageData = false; - - private static final Method GET_SUPPRESSED_METHOD; - - static { - Method method = null; - try { - method = Throwable.class.getMethod("getSuppressed"); - } catch (NoSuchMethodException e) { - // ignore, will get thrown in Java < 7 - } - GET_SUPPRESSED_METHOD = method; - } - - private static final ThrowableProxy[] NO_SUPPRESSED=new ThrowableProxy[0]; - - public ThrowableProxy(Throwable throwable) { - - this.throwable = throwable; - this.className = throwable.getClass().getName(); - this.message = throwable.getMessage(); - this.stackTraceElementProxyArray = ThrowableProxyUtil.steArrayToStepArray(throwable - .getStackTrace()); - - Throwable nested = throwable.getCause(); - - if (nested != null) { - this.cause = new ThrowableProxy(nested); - this.cause.commonFrames = ThrowableProxyUtil - .findNumberOfCommonFrames(nested.getStackTrace(), - stackTraceElementProxyArray); + private Throwable throwable; + private String className; + private String message; + // package-private because of ThrowableProxyUtil + StackTraceElementProxy[] stackTraceElementProxyArray; + // package-private because of ThrowableProxyUtil + int commonFrames; + private ThrowableProxy cause; + private ThrowableProxy[] suppressed = NO_SUPPRESSED; + + private transient PackagingDataCalculator packagingDataCalculator; + private boolean calculatedPackageData = false; + + private static final Method GET_SUPPRESSED_METHOD; + + static { + Method method = null; + try { + method = Throwable.class.getMethod("getSuppressed"); + } catch (NoSuchMethodException e) { + // ignore, will get thrown in Java < 7 + } + GET_SUPPRESSED_METHOD = method; } - if(GET_SUPPRESSED_METHOD != null) { - // this will only execute on Java 7 - try { - Object obj = GET_SUPPRESSED_METHOD.invoke(throwable); - if(obj instanceof Throwable[]) { - Throwable[] throwableSuppressed = (Throwable[]) obj; - if(throwableSuppressed.length > 0) { - suppressed = new ThrowableProxy[throwableSuppressed.length]; - for(int i=0;i 0) { + suppressed = new ThrowableProxy[throwableSuppressed.length]; + for (int i = 0; i < throwableSuppressed.length; i++) { + this.suppressed[i] = new ThrowableProxy(throwableSuppressed[i]); + this.suppressed[i].commonFrames = ThrowableProxyUtil.findNumberOfCommonFrames(throwableSuppressed[i].getStackTrace(), + stackTraceElementProxyArray); + } + } + } + } catch (IllegalAccessException e) { + // ignore + } catch (InvocationTargetException e) { + // ignore } - } } - } catch (IllegalAccessException e) { - // ignore - } catch (InvocationTargetException e) { - // ignore - } + } - } - - - public Throwable getThrowable() { - return throwable; - } - - public String getMessage() { - return message; - } - - /* - * (non-Javadoc) - * - * @see ch.qos.logback.classic.spi.IThrowableProxy#getClassName() - */ - public String getClassName() { - return className; - } - - public StackTraceElementProxy[] getStackTraceElementProxyArray() { - return stackTraceElementProxyArray; - } - - public int getCommonFrames() { - return commonFrames; - } - - /* - * (non-Javadoc) - * - * @see ch.qos.logback.classic.spi.IThrowableProxy#getCause() - */ - public IThrowableProxy getCause() { - return cause; - } - - public IThrowableProxy[] getSuppressed() { - return suppressed; - } - - public PackagingDataCalculator getPackagingDataCalculator() { - // if original instance (non-deserialized), and packagingDataCalculator - // is not already initialized, then create an instance. - // here we assume that (throwable == null) for deserialized instances - if (throwable != null && packagingDataCalculator == null) { - packagingDataCalculator = new PackagingDataCalculator(); + public Throwable getThrowable() { + return throwable; } - return packagingDataCalculator; - } - public void calculatePackagingData() { - if (calculatedPackageData) { - return; + public String getMessage() { + return message; } - PackagingDataCalculator pdc = this.getPackagingDataCalculator(); - if (pdc != null) { - calculatedPackageData = true; - pdc.calculate(this); + + /* + * (non-Javadoc) + * + * @see ch.qos.logback.classic.spi.IThrowableProxy#getClassName() + */ + public String getClassName() { + return className; } - } + public StackTraceElementProxy[] getStackTraceElementProxyArray() { + return stackTraceElementProxyArray; + } + public int getCommonFrames() { + return commonFrames; + } - public void fullDump() { - StringBuilder builder = new StringBuilder(); - for (StackTraceElementProxy step : stackTraceElementProxyArray) { - String string = step.toString(); - builder.append(CoreConstants.TAB).append(string); - ThrowableProxyUtil.subjoinPackagingData(builder, step); - builder.append(CoreConstants.LINE_SEPARATOR); + /* + * (non-Javadoc) + * + * @see ch.qos.logback.classic.spi.IThrowableProxy#getCause() + */ + public IThrowableProxy getCause() { + return cause; } - System.out.println(builder.toString()); - } + public IThrowableProxy[] getSuppressed() { + return suppressed; + } + + public PackagingDataCalculator getPackagingDataCalculator() { + // if original instance (non-deserialized), and packagingDataCalculator + // is not already initialized, then create an instance. + // here we assume that (throwable == null) for deserialized instances + if (throwable != null && packagingDataCalculator == null) { + packagingDataCalculator = new PackagingDataCalculator(); + } + return packagingDataCalculator; + } + + public void calculatePackagingData() { + if (calculatedPackageData) { + return; + } + PackagingDataCalculator pdc = this.getPackagingDataCalculator(); + if (pdc != null) { + calculatedPackageData = true; + pdc.calculate(this); + } + } + + public void fullDump() { + StringBuilder builder = new StringBuilder(); + for (StackTraceElementProxy step : stackTraceElementProxyArray) { + String string = step.toString(); + builder.append(CoreConstants.TAB).append(string); + ThrowableProxyUtil.subjoinPackagingData(builder, step); + builder.append(CoreConstants.LINE_SEPARATOR); + } + System.out.println(builder.toString()); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyUtil.java index 58eb34273b1ac79bb3775a47591d75288b65cf4a..007c64407ee4e2f8fd2db87f9e0dc1217cdd2b7a 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyUtil.java @@ -23,167 +23,162 @@ import ch.qos.logback.core.CoreConstants; */ public class ThrowableProxyUtil { - public static final int REGULAR_EXCEPTION_INDENT = 1; - public static final int SUPPRESSED_EXCEPTION_INDENT = 1; - private static final int BUILDER_CAPACITY = 2048; + public static final int REGULAR_EXCEPTION_INDENT = 1; + public static final int SUPPRESSED_EXCEPTION_INDENT = 1; + private static final int BUILDER_CAPACITY = 2048; - public static void build(ThrowableProxy nestedTP, Throwable nestedThrowable, - ThrowableProxy parentTP) { + public static void build(ThrowableProxy nestedTP, Throwable nestedThrowable, ThrowableProxy parentTP) { - StackTraceElement[] nestedSTE = nestedThrowable.getStackTrace(); + StackTraceElement[] nestedSTE = nestedThrowable.getStackTrace(); - int commonFramesCount = -1; - if (parentTP != null) { - commonFramesCount = findNumberOfCommonFrames(nestedSTE, parentTP - .getStackTraceElementProxyArray()); - } - - nestedTP.commonFrames = commonFramesCount; - nestedTP.stackTraceElementProxyArray = steArrayToStepArray(nestedSTE); - } + int commonFramesCount = -1; + if (parentTP != null) { + commonFramesCount = findNumberOfCommonFrames(nestedSTE, parentTP.getStackTraceElementProxyArray()); + } - static StackTraceElementProxy[] steArrayToStepArray(StackTraceElement[] stea) { - if(stea == null) { - return new StackTraceElementProxy[0]; - } - StackTraceElementProxy[] stepa = new StackTraceElementProxy[stea.length]; - for (int i = 0; i < stepa.length; i++) { - stepa[i] = new StackTraceElementProxy(stea[i]); + nestedTP.commonFrames = commonFramesCount; + nestedTP.stackTraceElementProxyArray = steArrayToStepArray(nestedSTE); } - return stepa; - } - static int findNumberOfCommonFrames(StackTraceElement[] steArray, - StackTraceElementProxy[] parentSTEPArray) { - if (parentSTEPArray == null || steArray == null) { - return 0; + static StackTraceElementProxy[] steArrayToStepArray(StackTraceElement[] stea) { + if (stea == null) { + return new StackTraceElementProxy[0]; + } + StackTraceElementProxy[] stepa = new StackTraceElementProxy[stea.length]; + for (int i = 0; i < stepa.length; i++) { + stepa[i] = new StackTraceElementProxy(stea[i]); + } + return stepa; } - int steIndex = steArray.length - 1; - int parentIndex = parentSTEPArray.length - 1; - int count = 0; - while (steIndex >= 0 && parentIndex >= 0) { - StackTraceElement ste = steArray[steIndex]; - StackTraceElement otherSte = parentSTEPArray[parentIndex].ste; - if (ste.equals(otherSte)) { - count++; - } else { - break; - } - steIndex--; - parentIndex--; + static int findNumberOfCommonFrames(StackTraceElement[] steArray, StackTraceElementProxy[] parentSTEPArray) { + if (parentSTEPArray == null || steArray == null) { + return 0; + } + + int steIndex = steArray.length - 1; + int parentIndex = parentSTEPArray.length - 1; + int count = 0; + while (steIndex >= 0 && parentIndex >= 0) { + StackTraceElement ste = steArray[steIndex]; + StackTraceElement otherSte = parentSTEPArray[parentIndex].ste; + if (ste.equals(otherSte)) { + count++; + } else { + break; + } + steIndex--; + parentIndex--; + } + return count; } - return count; - } - - public static String asString(IThrowableProxy tp) { - StringBuilder sb = new StringBuilder(BUILDER_CAPACITY); - - recursiveAppend(sb, null, REGULAR_EXCEPTION_INDENT, tp); - - return sb.toString(); - } - - private static void recursiveAppend(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { - if(tp == null) - return; - subjoinFirstLine(sb, prefix, indent, tp); - sb.append(CoreConstants.LINE_SEPARATOR); - subjoinSTEPArray(sb, indent, tp); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current : suppressed) { - recursiveAppend(sb, CoreConstants.SUPPRESSED, indent + SUPPRESSED_EXCEPTION_INDENT, current); - } + + public static String asString(IThrowableProxy tp) { + StringBuilder sb = new StringBuilder(BUILDER_CAPACITY); + + recursiveAppend(sb, null, REGULAR_EXCEPTION_INDENT, tp); + + return sb.toString(); } - recursiveAppend(sb, CoreConstants.CAUSED_BY, indent, tp.getCause()); - } - public static void indent(StringBuilder buf, int indent) { - for(int j = 0; j < indent; j++) { - buf.append(CoreConstants.TAB); + private static void recursiveAppend(StringBuilder sb, String prefix, int indent, IThrowableProxy tp) { + if (tp == null) + return; + subjoinFirstLine(sb, prefix, indent, tp); + sb.append(CoreConstants.LINE_SEPARATOR); + subjoinSTEPArray(sb, indent, tp); + IThrowableProxy[] suppressed = tp.getSuppressed(); + if (suppressed != null) { + for (IThrowableProxy current : suppressed) { + recursiveAppend(sb, CoreConstants.SUPPRESSED, indent + SUPPRESSED_EXCEPTION_INDENT, current); + } + } + recursiveAppend(sb, CoreConstants.CAUSED_BY, indent, tp.getCause()); } - } - private static void subjoinFirstLine(StringBuilder buf, String prefix, int indent, IThrowableProxy tp) { - indent(buf, indent - 1); - if (prefix != null) { - buf.append(prefix); + public static void indent(StringBuilder buf, int indent) { + for (int j = 0; j < indent; j++) { + buf.append(CoreConstants.TAB); + } } - subjoinExceptionMessage(buf, tp); - } - - public static void subjoinPackagingData(StringBuilder builder, StackTraceElementProxy step) { - if (step != null) { - ClassPackagingData cpd = step.getClassPackagingData(); - if (cpd != null) { - if (!cpd.isExact()) { - builder.append(" ~["); - } else { - builder.append(" ["); + + private static void subjoinFirstLine(StringBuilder buf, String prefix, int indent, IThrowableProxy tp) { + indent(buf, indent - 1); + if (prefix != null) { + buf.append(prefix); } + subjoinExceptionMessage(buf, tp); + } - builder.append(cpd.getCodeLocation()).append(':').append( - cpd.getVersion()).append(']'); - } + public static void subjoinPackagingData(StringBuilder builder, StackTraceElementProxy step) { + if (step != null) { + ClassPackagingData cpd = step.getClassPackagingData(); + if (cpd != null) { + if (!cpd.isExact()) { + builder.append(" ~["); + } else { + builder.append(" ["); + } + + builder.append(cpd.getCodeLocation()).append(':').append(cpd.getVersion()).append(']'); + } + } } - } - - public static void subjoinSTEP(StringBuilder sb, StackTraceElementProxy step) { - sb.append(step.toString()); - subjoinPackagingData(sb, step); - } - - /** - * @param sb The StringBuilder the STEPs are appended to. - * @param tp the IThrowableProxy containing the STEPs. - * @deprecated Use subjoinSTEPArray(StringBuilder sb, int indentLevel, IThrowableProxy tp) instead. - */ - public static void subjoinSTEPArray(StringBuilder sb, IThrowableProxy tp) { - // not called anymore - but it is public - subjoinSTEPArray(sb, REGULAR_EXCEPTION_INDENT, tp); - } - - /** - * @param sb The StringBuilder the STEPs are appended to. - * @param indentLevel indentation level used for the STEPs, usually REGULAR_EXCEPTION_INDENT. - * @param tp the IThrowableProxy containing the STEPs. - */ - public static void subjoinSTEPArray(StringBuilder sb, int indentLevel, IThrowableProxy tp) { - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - int commonFrames = tp.getCommonFrames(); - - for (int i = 0; i < stepArray.length - commonFrames; i++) { - StackTraceElementProxy step = stepArray[i]; - indent(sb, indentLevel); - subjoinSTEP(sb, step); - sb.append(CoreConstants.LINE_SEPARATOR); + + public static void subjoinSTEP(StringBuilder sb, StackTraceElementProxy step) { + sb.append(step.toString()); + subjoinPackagingData(sb, step); } - if (commonFrames > 0) { - indent(sb, indentLevel); - sb.append("... ").append(commonFrames).append(" common frames omitted") - .append(CoreConstants.LINE_SEPARATOR); + /** + * @param sb The StringBuilder the STEPs are appended to. + * @param tp the IThrowableProxy containing the STEPs. + * @deprecated Use subjoinSTEPArray(StringBuilder sb, int indentLevel, IThrowableProxy tp) instead. + */ + public static void subjoinSTEPArray(StringBuilder sb, IThrowableProxy tp) { + // not called anymore - but it is public + subjoinSTEPArray(sb, REGULAR_EXCEPTION_INDENT, tp); } - } + /** + * @param sb The StringBuilder the STEPs are appended to. + * @param indentLevel indentation level used for the STEPs, usually REGULAR_EXCEPTION_INDENT. + * @param tp the IThrowableProxy containing the STEPs. + */ + public static void subjoinSTEPArray(StringBuilder sb, int indentLevel, IThrowableProxy tp) { + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + int commonFrames = tp.getCommonFrames(); + + for (int i = 0; i < stepArray.length - commonFrames; i++) { + StackTraceElementProxy step = stepArray[i]; + indent(sb, indentLevel); + subjoinSTEP(sb, step); + sb.append(CoreConstants.LINE_SEPARATOR); + } - public static void subjoinFirstLine(StringBuilder buf, IThrowableProxy tp) { - int commonFrames = tp.getCommonFrames(); - if (commonFrames > 0) { - buf.append(CoreConstants.CAUSED_BY); + if (commonFrames > 0) { + indent(sb, indentLevel); + sb.append("... ").append(commonFrames).append(" common frames omitted").append(CoreConstants.LINE_SEPARATOR); + } + + } + + public static void subjoinFirstLine(StringBuilder buf, IThrowableProxy tp) { + int commonFrames = tp.getCommonFrames(); + if (commonFrames > 0) { + buf.append(CoreConstants.CAUSED_BY); + } + subjoinExceptionMessage(buf, tp); } - subjoinExceptionMessage(buf, tp); - } - public static void subjoinFirstLineRootCauseFirst(StringBuilder buf, IThrowableProxy tp) { - if (tp.getCause() != null) { - buf.append(CoreConstants.WRAPPED_BY); + public static void subjoinFirstLineRootCauseFirst(StringBuilder buf, IThrowableProxy tp) { + if (tp.getCause() != null) { + buf.append(CoreConstants.WRAPPED_BY); + } + subjoinExceptionMessage(buf, tp); } - subjoinExceptionMessage(buf, tp); - } - private static void subjoinExceptionMessage(StringBuilder buf, IThrowableProxy tp) { - buf.append(tp.getClassName()).append(": ").append(tp.getMessage()); - } + private static void subjoinExceptionMessage(StringBuilder buf, IThrowableProxy tp) { + buf.append(tp.getClassName()).append(": ").append(tp.getMessage()); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyVO.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyVO.java index b96cddc40885ee0641eb0db59cedffc4e4a37d7a..d6105c3f5ea831128d6bcdca8d261c2118ba7906 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyVO.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/ThrowableProxyVO.java @@ -18,100 +18,98 @@ import java.util.Arrays; public class ThrowableProxyVO implements IThrowableProxy, Serializable { - private static final long serialVersionUID = -773438177285807139L; - - private String className; - private String message; - private int commonFramesCount; - private StackTraceElementProxy[] stackTraceElementProxyArray; - private IThrowableProxy cause; - private IThrowableProxy[] suppressed; - - - public String getMessage() { - return message; - } - - public String getClassName() { - return className; - } - - public int getCommonFrames() { - return commonFramesCount; - } - - public IThrowableProxy getCause() { - return cause; - } - - public StackTraceElementProxy[] getStackTraceElementProxyArray() { - return stackTraceElementProxyArray; - } - - public IThrowableProxy[] getSuppressed() { - return suppressed; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((className == null) ? 0 : className.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final ThrowableProxyVO other = (ThrowableProxyVO) obj; - - if (className == null) { - if (other.className != null) - return false; - } else if (!className.equals(other.className)) - return false; - - if (!Arrays.equals(stackTraceElementProxyArray, other.stackTraceElementProxyArray)) - return false; - - if (!Arrays.equals(suppressed, other.suppressed)) - return false; - - if (cause == null) { - if (other.cause != null) - return false; - } else if (!cause.equals(other.cause)) - return false; - - return true; - } - - public static ThrowableProxyVO build(IThrowableProxy throwableProxy) { - if(throwableProxy == null) { - return null; + private static final long serialVersionUID = -773438177285807139L; + + private String className; + private String message; + private int commonFramesCount; + private StackTraceElementProxy[] stackTraceElementProxyArray; + private IThrowableProxy cause; + private IThrowableProxy[] suppressed; + + public String getMessage() { + return message; + } + + public String getClassName() { + return className; + } + + public int getCommonFrames() { + return commonFramesCount; } - ThrowableProxyVO tpvo = new ThrowableProxyVO(); - tpvo.className = throwableProxy.getClassName(); - tpvo.message = throwableProxy.getMessage(); - tpvo.commonFramesCount = throwableProxy.getCommonFrames(); - tpvo.stackTraceElementProxyArray = throwableProxy.getStackTraceElementProxyArray(); - IThrowableProxy cause = throwableProxy.getCause(); - if(cause != null) { - tpvo.cause = ThrowableProxyVO.build(cause); + + public IThrowableProxy getCause() { + return cause; + } + + public StackTraceElementProxy[] getStackTraceElementProxyArray() { + return stackTraceElementProxyArray; + } + + public IThrowableProxy[] getSuppressed() { + return suppressed; } - IThrowableProxy[] suppressed = throwableProxy.getSuppressed(); - if(suppressed != null) { - tpvo.suppressed = new IThrowableProxy[suppressed.length]; - for(int i = 0;i { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Loop through the filters in the chain. As soon as a filter decides on - * ACCEPT or DENY, then that value is returned. If all of the filters return - * NEUTRAL, then NEUTRAL is returned. - */ - public FilterReply getTurboFilterChainDecision(final Marker marker, - final Logger logger, final Level level, final String format, - final Object[] params, final Throwable t) { - - - final int size = size(); -// if (size == 0) { -// return FilterReply.NEUTRAL; -// } - if (size == 1) { - try { - TurboFilter tf = get(0); - return tf.decide(marker, logger, level, format, params, t); - } catch (IndexOutOfBoundsException iobe) { + /** + * Loop through the filters in the chain. As soon as a filter decides on + * ACCEPT or DENY, then that value is returned. If all of the filters return + * NEUTRAL, then NEUTRAL is returned. + */ + public FilterReply getTurboFilterChainDecision(final Marker marker, final Logger logger, final Level level, final String format, final Object[] params, + final Throwable t) { + + final int size = size(); + // if (size == 0) { + // return FilterReply.NEUTRAL; + // } + if (size == 1) { + try { + TurboFilter tf = get(0); + return tf.decide(marker, logger, level, format, params, t); + } catch (IndexOutOfBoundsException iobe) { + return FilterReply.NEUTRAL; + } + } + + Object[] tfa = toArray(); + final int len = tfa.length; + for (int i = 0; i < len; i++) { + // for (TurboFilter tf : this) { + final TurboFilter tf = (TurboFilter) tfa[i]; + final FilterReply r = tf.decide(marker, logger, level, format, params, t); + if (r == FilterReply.DENY || r == FilterReply.ACCEPT) { + return r; + } + } return FilterReply.NEUTRAL; - } - } - - Object[] tfa = toArray(); - final int len = tfa.length; - for (int i = 0; i < len; i++) { - //for (TurboFilter tf : this) { - final TurboFilter tf = (TurboFilter) tfa[i]; - final FilterReply r = tf.decide(marker, logger, level, format, params, t); - if (r == FilterReply.DENY || r == FilterReply.ACCEPT) { - return r; - } } - return FilterReply.NEUTRAL; - } - // public boolean remove(TurboFilter turboFilter) { - // return tfList.remove(turboFilter); - // } - // - // public TurboFilter remove(int index) { - // return tfList.remove(index); - // } - // - // final public int size() { - // return tfList.size(); - // } + // public boolean remove(TurboFilter turboFilter) { + // return tfList.remove(turboFilter); + // } + // + // public TurboFilter remove(int index) { + // return tfList.remove(index); + // } + // + // final public int size() { + // return tfList.size(); + // } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DuplicateMessageFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DuplicateMessageFilter.java index 7055374088bbeccdd39e304626bfd0c5e80d3fb2..f023541aaaab8dd084049e6e0c200857f25a9cb8 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DuplicateMessageFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DuplicateMessageFilter.java @@ -29,63 +29,62 @@ import ch.qos.logback.core.spi.FilterReply; */ public class DuplicateMessageFilter extends TurboFilter { - /** - * The default cache size. - */ - public static final int DEFAULT_CACHE_SIZE = 100; - /** - * The default number of allows repetitions. - */ - public static final int DEFAULT_ALLOWED_REPETITIONS = 5; + /** + * The default cache size. + */ + public static final int DEFAULT_CACHE_SIZE = 100; + /** + * The default number of allows repetitions. + */ + public static final int DEFAULT_ALLOWED_REPETITIONS = 5; - public int allowedRepetitions = DEFAULT_ALLOWED_REPETITIONS; - public int cacheSize = DEFAULT_CACHE_SIZE; + public int allowedRepetitions = DEFAULT_ALLOWED_REPETITIONS; + public int cacheSize = DEFAULT_CACHE_SIZE; - private LRUMessageCache msgCache; + private LRUMessageCache msgCache; - @Override - public void start() { - msgCache = new LRUMessageCache(cacheSize); - super.start(); - } + @Override + public void start() { + msgCache = new LRUMessageCache(cacheSize); + super.start(); + } - @Override - public void stop() { - msgCache.clear(); - msgCache = null; - super.stop(); - } + @Override + public void stop() { + msgCache.clear(); + msgCache = null; + super.stop(); + } - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String format, Object[] params, Throwable t) { - int count = msgCache.getMessageCountAndThenIncrement(format); - if (count <= allowedRepetitions) { - return FilterReply.NEUTRAL; - } else { - return FilterReply.DENY; + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + int count = msgCache.getMessageCountAndThenIncrement(format); + if (count <= allowedRepetitions) { + return FilterReply.NEUTRAL; + } else { + return FilterReply.DENY; + } } - } - public int getAllowedRepetitions() { - return allowedRepetitions; - } + public int getAllowedRepetitions() { + return allowedRepetitions; + } - /** - * The allowed number of repetitions before - * - * @param allowedRepetitions - */ - public void setAllowedRepetitions(int allowedRepetitions) { - this.allowedRepetitions = allowedRepetitions; - } + /** + * The allowed number of repetitions before + * + * @param allowedRepetitions + */ + public void setAllowedRepetitions(int allowedRepetitions) { + this.allowedRepetitions = allowedRepetitions; + } - public int getCacheSize() { - return cacheSize; - } + public int getCacheSize() { + return cacheSize; + } - public void setCacheSize(int cacheSize) { - this.cacheSize = cacheSize; - } + public void setCacheSize(int cacheSize) { + this.cacheSize = cacheSize; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DynamicThresholdFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DynamicThresholdFilter.java index 12ff953d409329eaadb1d225dcfd1e844f7a1f19..849c2eb65f28612ad09f82ca8c478b5a8204e8eb 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DynamicThresholdFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/DynamicThresholdFilter.java @@ -125,133 +125,131 @@ import java.util.HashMap; * @author Ceki Gülcü */ public class DynamicThresholdFilter extends TurboFilter { - private Map valueLevelMap = new HashMap(); - private Level defaultThreshold = Level.ERROR; - private String key; - - private FilterReply onHigherOrEqual = FilterReply.NEUTRAL; - private FilterReply onLower = FilterReply.DENY; - - /** - * Get the MDC key whose value will be used as a level threshold - * - * @return the name of the MDC key. - */ - public String getKey() { - return this.key; - } - - /** - * @see setKey - */ - public void setKey(String key) { - this.key = key; - } - - /** - * Get the default threshold value when the MDC key is not set. - * - * @return the default threshold value in the absence of a set MDC key - */ - public Level getDefaultThreshold() { - return defaultThreshold; - } - - public void setDefaultThreshold(Level defaultThreshold) { - this.defaultThreshold = defaultThreshold; - } - - /** - * Get the FilterReply when the effective level is higher or equal to the - * level of current logging request - * - * @return FilterReply - */ - public FilterReply getOnHigherOrEqual() { - return onHigherOrEqual; - } + private Map valueLevelMap = new HashMap(); + private Level defaultThreshold = Level.ERROR; + private String key; + + private FilterReply onHigherOrEqual = FilterReply.NEUTRAL; + private FilterReply onLower = FilterReply.DENY; + + /** + * Get the MDC key whose value will be used as a level threshold + * + * @return the name of the MDC key. + */ + public String getKey() { + return this.key; + } - public void setOnHigherOrEqual(FilterReply onHigherOrEqual) { - this.onHigherOrEqual = onHigherOrEqual; - } + /** + * @see setKey + */ + public void setKey(String key) { + this.key = key; + } - /** - * Get the FilterReply when the effective level is lower than the level of - * current logging request - * - * @return FilterReply - */ - public FilterReply getOnLower() { - return onLower; - } + /** + * Get the default threshold value when the MDC key is not set. + * + * @return the default threshold value in the absence of a set MDC key + */ + public Level getDefaultThreshold() { + return defaultThreshold; + } - public void setOnLower(FilterReply onLower) { - this.onLower = onLower; - } + public void setDefaultThreshold(Level defaultThreshold) { + this.defaultThreshold = defaultThreshold; + } - /** - * Add a new MDCValuePair - */ - public void addMDCValueLevelPair(MDCValueLevelPair mdcValueLevelPair) { - if (valueLevelMap.containsKey(mdcValueLevelPair.getValue())) { - addError(mdcValueLevelPair.getValue() + " has been already set"); - } else { - valueLevelMap.put(mdcValueLevelPair.getValue(), mdcValueLevelPair - .getLevel()); + /** + * Get the FilterReply when the effective level is higher or equal to the + * level of current logging request + * + * @return FilterReply + */ + public FilterReply getOnHigherOrEqual() { + return onHigherOrEqual; } - } - /** - * - */ - @Override - public void start() { - if (this.key == null) { - addError("No key name was specified"); + public void setOnHigherOrEqual(FilterReply onHigherOrEqual) { + this.onHigherOrEqual = onHigherOrEqual; } - super.start(); - } - /** - * This method first finds the MDC value for 'key'. It then finds the level - * threshold associated with this MDC value from the list of MDCValueLevelPair - * passed to this filter. This value is stored in a variable called - * 'levelAssociatedWithMDCValue'. If it null, then it is set to the - * - * @{link #defaultThreshold} value. - * - * If no such value exists, then - * - * - * @param marker - * @param logger - * @param level - * @param s - * @param objects - * @param throwable - * - * @return FilterReply - this filter's decision - */ - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String s, Object[] objects, Throwable throwable) { + /** + * Get the FilterReply when the effective level is lower than the level of + * current logging request + * + * @return FilterReply + */ + public FilterReply getOnLower() { + return onLower; + } - String mdcValue = MDC.get(this.key); - if (!isStarted()) { - return FilterReply.NEUTRAL; + public void setOnLower(FilterReply onLower) { + this.onLower = onLower; } - Level levelAssociatedWithMDCValue = null; - if (mdcValue != null) { - levelAssociatedWithMDCValue = valueLevelMap.get(mdcValue); + /** + * Add a new MDCValuePair + */ + public void addMDCValueLevelPair(MDCValueLevelPair mdcValueLevelPair) { + if (valueLevelMap.containsKey(mdcValueLevelPair.getValue())) { + addError(mdcValueLevelPair.getValue() + " has been already set"); + } else { + valueLevelMap.put(mdcValueLevelPair.getValue(), mdcValueLevelPair.getLevel()); + } } - if (levelAssociatedWithMDCValue == null) { - levelAssociatedWithMDCValue = defaultThreshold; + + /** + * + */ + @Override + public void start() { + if (this.key == null) { + addError("No key name was specified"); + } + super.start(); } - if (level.isGreaterOrEqual(levelAssociatedWithMDCValue)) { - return onHigherOrEqual; - } else { - return onLower; + + /** + * This method first finds the MDC value for 'key'. It then finds the level + * threshold associated with this MDC value from the list of MDCValueLevelPair + * passed to this filter. This value is stored in a variable called + * 'levelAssociatedWithMDCValue'. If it null, then it is set to the + * + * @{link #defaultThreshold} value. + * + * If no such value exists, then + * + * + * @param marker + * @param logger + * @param level + * @param s + * @param objects + * @param throwable + * + * @return FilterReply - this filter's decision + */ + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String s, Object[] objects, Throwable throwable) { + + String mdcValue = MDC.get(this.key); + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + + Level levelAssociatedWithMDCValue = null; + if (mdcValue != null) { + levelAssociatedWithMDCValue = valueLevelMap.get(mdcValue); + } + if (levelAssociatedWithMDCValue == null) { + levelAssociatedWithMDCValue = defaultThreshold; + } + if (level.isGreaterOrEqual(levelAssociatedWithMDCValue)) { + return onHigherOrEqual; + } else { + return onLower; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/LRUMessageCache.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/LRUMessageCache.java index f2280f5b6fa5ac8a5ab3a9ece2adf15aa634fa3c..13c42ae47ffb091bba00ef54a8bfa41247d8853b 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/LRUMessageCache.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/LRUMessageCache.java @@ -22,45 +22,45 @@ import java.util.Map; */ class LRUMessageCache extends LinkedHashMap { - private static final long serialVersionUID = 1L; - final int cacheSize; + private static final long serialVersionUID = 1L; + final int cacheSize; - LRUMessageCache(int cacheSize) { - super((int) (cacheSize * (4.0f / 3)), 0.75f, true); - if (cacheSize < 1) { - throw new IllegalArgumentException("Cache size cannot be smaller than 1"); + LRUMessageCache(int cacheSize) { + super((int) (cacheSize * (4.0f / 3)), 0.75f, true); + if (cacheSize < 1) { + throw new IllegalArgumentException("Cache size cannot be smaller than 1"); + } + this.cacheSize = cacheSize; } - this.cacheSize = cacheSize; - } - int getMessageCountAndThenIncrement(String msg) { - // don't insert null elements - if (msg == null) { - return 0; - } + int getMessageCountAndThenIncrement(String msg) { + // don't insert null elements + if (msg == null) { + return 0; + } - Integer i; - // LinkedHashMap is not LinkedHashMap. See also LBCLASSIC-255 - synchronized (this) { - i = super.get(msg); - if (i == null) { - i = 0; - } else { - i = i + 1; - } - super.put(msg, i); + Integer i; + // LinkedHashMap is not LinkedHashMap. See also LBCLASSIC-255 + synchronized (this) { + i = super.get(msg); + if (i == null) { + i = 0; + } else { + i = i + 1; + } + super.put(msg, i); + } + return i; } - return i; - } - // called indirectly by get() or put() which are already supposed to be - // called from within a synchronized block - protected boolean removeEldestEntry(Map.Entry eldest) { - return (size() > cacheSize); - } + // called indirectly by get() or put() which are already supposed to be + // called from within a synchronized block + protected boolean removeEldestEntry(Map.Entry eldest) { + return (size() > cacheSize); + } - @Override - synchronized public void clear() { - super.clear(); - } + @Override + synchronized public void clear() { + super.clear(); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCFilter.java index 589ba6960a9980cc71c492994d6c75108ac31851..179bb222c747611ed1eaa499d8dcb5bd159d6737 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCFilter.java @@ -45,28 +45,28 @@ import ch.qos.logback.core.spi.FilterReply; */ public class MDCFilter extends MatchingFilter { - String MDCKey; - String value; - - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { - if (MDCKey == null) { - return FilterReply.NEUTRAL; + String MDCKey; + String value; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (MDCKey == null) { + return FilterReply.NEUTRAL; + } + + String value = MDC.get(MDCKey); + if (this.value.equals(value)) { + return onMatch; + } + return onMismatch; } - - String value = MDC.get(MDCKey); - if (this.value.equals(value)) { - return onMatch; + + public void setValue(String value) { + this.value = value; + } + + public void setMDCKey(String MDCKey) { + this.MDCKey = MDCKey; } - return onMismatch; - } - - public void setValue(String value) { - this.value = value; - } - - public void setMDCKey(String MDCKey) { - this.MDCKey = MDCKey; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCValueLevelPair.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCValueLevelPair.java index 196c4acf8293409497a51ea15da5541348486c25..2a23c99a0cde47bbcf793cc96fb299448b63307d 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCValueLevelPair.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MDCValueLevelPair.java @@ -15,7 +15,6 @@ package ch.qos.logback.classic.turbo; import ch.qos.logback.classic.Level; - /** * Bean pairing an MDC value with a log level. * @@ -23,22 +22,22 @@ import ch.qos.logback.classic.Level; * @author Ceki Gülcü */ public class MDCValueLevelPair { - private String value; - private Level level; + private String value; + private Level level; - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public void setValue(String name) { - this.value = name; - } + public void setValue(String name) { + this.value = name; + } - public Level getLevel() { - return level; - } + public Level getLevel() { + return level; + } - public void setLevel(Level level) { - this.level = level; - } + public void setLevel(Level level) { + this.level = level; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MarkerFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MarkerFilter.java index c7f3f7fdf4a35c7fe12287d4a3215c1563dcf234..3158f9e923fe514ecdc9a06a3cd0d3c301497290 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MarkerFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MarkerFilter.java @@ -26,42 +26,42 @@ import ch.qos.logback.core.spi.FilterReply; */ public class MarkerFilter extends MatchingFilter { - Marker markerToMatch; + Marker markerToMatch; - @Override - public void start() { - if(markerToMatch != null) { - super.start(); - } else { - addError("The marker property must be set for ["+getName()+"]"); + @Override + public void start() { + if (markerToMatch != null) { + super.start(); + } else { + addError("The marker property must be set for [" + getName() + "]"); + } } - } - - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { - if(!isStarted()) { - return FilterReply.NEUTRAL; - } - - if(marker == null) { - return onMismatch; - } - - if(marker.contains(markerToMatch)) { - return onMatch; - } else { - return onMismatch; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + + if (marker == null) { + return onMismatch; + } + + if (marker.contains(markerToMatch)) { + return onMatch; + } else { + return onMismatch; + } } - } - /** - * The marker to match in the event. - * - * @param markerStr - */ - public void setMarker(String markerStr) { - if(markerStr != null) { - this.markerToMatch = MarkerFactory.getMarker(markerStr); + /** + * The marker to match in the event. + * + * @param markerStr + */ + public void setMarker(String markerStr) { + if (markerStr != null) { + this.markerToMatch = MarkerFactory.getMarker(markerStr); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MatchingFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MatchingFilter.java index 93cc5f86b87d94ba18f43a5a7e3a0b7a07925e88..c19737d57f5442768e59365bbc02512462cd7361 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MatchingFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/MatchingFilter.java @@ -23,26 +23,26 @@ import ch.qos.logback.core.spi.FilterReply; */ public abstract class MatchingFilter extends TurboFilter { - protected FilterReply onMatch = FilterReply.NEUTRAL; - protected FilterReply onMismatch = FilterReply.NEUTRAL; - - final public void setOnMatch(String action) { - if ("NEUTRAL".equals(action)) { - onMatch = FilterReply.NEUTRAL; - } else if ("ACCEPT".equals(action)) { - onMatch = FilterReply.ACCEPT; - } else if ("DENY".equals(action)) { - onMatch = FilterReply.DENY; + protected FilterReply onMatch = FilterReply.NEUTRAL; + protected FilterReply onMismatch = FilterReply.NEUTRAL; + + final public void setOnMatch(String action) { + if ("NEUTRAL".equals(action)) { + onMatch = FilterReply.NEUTRAL; + } else if ("ACCEPT".equals(action)) { + onMatch = FilterReply.ACCEPT; + } else if ("DENY".equals(action)) { + onMatch = FilterReply.DENY; + } } - } - final public void setOnMismatch(String action) { - if ("NEUTRAL".equals(action)) { - onMismatch = FilterReply.NEUTRAL; - } else if ("ACCEPT".equals(action)) { - onMismatch = FilterReply.ACCEPT; - } else if ("DENY".equals(action)) { - onMismatch = FilterReply.DENY; + final public void setOnMismatch(String action) { + if ("NEUTRAL".equals(action)) { + onMismatch = FilterReply.NEUTRAL; + } else if ("ACCEPT".equals(action)) { + onMismatch = FilterReply.ACCEPT; + } else if ("DENY".equals(action)) { + onMismatch = FilterReply.DENY; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeFilter.java index 1cd1c4a7e6dbb0fa4e0029ce8e7e9de3781f3965..567c31e28ae9108e20b013566529f025bc9c109d 100755 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeFilter.java @@ -42,203 +42,197 @@ import static ch.qos.logback.core.CoreConstants.MILLIS_IN_ONE_SECOND; */ public class ReconfigureOnChangeFilter extends TurboFilter { - /** - * Scan for changes in configuration file once every minute. - */ - // 1 minute - value mentioned in documentation - public final static long DEFAULT_REFRESH_PERIOD = 60 * MILLIS_IN_ONE_SECOND; - - long refreshPeriod = DEFAULT_REFRESH_PERIOD; - URL mainConfigurationURL; - protected volatile long nextCheck; - - ConfigurationWatchList configurationWatchList; - - @Override - public void start() { - configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(context); - if (configurationWatchList != null) { - mainConfigurationURL = configurationWatchList.getMainURL(); - if(mainConfigurationURL == null) { - addWarn("Due to missing top level configuration file, automatic reconfiguration is impossible."); - return; - } - List watchList = configurationWatchList.getCopyOfFileWatchList(); - long inSeconds = refreshPeriod / 1000; - addInfo("Will scan for changes in [" + watchList + "] every " - + inSeconds + " seconds. "); - synchronized (configurationWatchList) { - updateNextCheck(System.currentTimeMillis()); - } - super.start(); - } else { - addWarn("Empty ConfigurationWatchList in context"); - } - } - - @Override - public String toString() { - return "ReconfigureOnChangeFilter{" + - "invocationCounter=" + invocationCounter + - '}'; - } - - // The next fields counts the number of time the decide method is called - // - // IMPORTANT: This field can be updated by multiple threads. It follows that - // its values may *not* be incremented sequentially. However, we don't care - // about the actual value of the field except that from time to time the - // expression (invocationCounter++ & mask) == mask) should be true. - private long invocationCounter = 0; - - private volatile long mask = 0xF; - private volatile long lastMaskCheck = System.currentTimeMillis(); - - - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String format, Object[] params, Throwable t) { - if (!isStarted()) { - return FilterReply.NEUTRAL; + /** + * Scan for changes in configuration file once every minute. + */ + // 1 minute - value mentioned in documentation + public final static long DEFAULT_REFRESH_PERIOD = 60 * MILLIS_IN_ONE_SECOND; + + long refreshPeriod = DEFAULT_REFRESH_PERIOD; + URL mainConfigurationURL; + protected volatile long nextCheck; + + ConfigurationWatchList configurationWatchList; + + @Override + public void start() { + configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(context); + if (configurationWatchList != null) { + mainConfigurationURL = configurationWatchList.getMainURL(); + if (mainConfigurationURL == null) { + addWarn("Due to missing top level configuration file, automatic reconfiguration is impossible."); + return; + } + List watchList = configurationWatchList.getCopyOfFileWatchList(); + long inSeconds = refreshPeriod / 1000; + addInfo("Will scan for changes in [" + watchList + "] every " + inSeconds + " seconds. "); + synchronized (configurationWatchList) { + updateNextCheck(System.currentTimeMillis()); + } + super.start(); + } else { + addWarn("Empty ConfigurationWatchList in context"); + } } - // for performance reasons, skip change detection (MASK-1) times out of MASK. - // Only once every MASK calls is change detection code executed - // Note that MASK is a variable itself. - if (((invocationCounter++) & mask) != mask) { - return FilterReply.NEUTRAL; + @Override + public String toString() { + return "ReconfigureOnChangeFilter{" + "invocationCounter=" + invocationCounter + '}'; } - long now = System.currentTimeMillis(); - - synchronized (configurationWatchList) { - updateMaskIfNecessary(now); - if (changeDetected(now)) { - // Even though reconfiguration involves resetting the loggerContext, - // which clears the list of turbo filters including this instance, it is - // still possible for this instance to be subsequently invoked by another - // thread if it was already executing when the context was reset. - disableSubsequentReconfiguration(); - detachReconfigurationToNewThread(); - } + // The next fields counts the number of time the decide method is called + // + // IMPORTANT: This field can be updated by multiple threads. It follows that + // its values may *not* be incremented sequentially. However, we don't care + // about the actual value of the field except that from time to time the + // expression (invocationCounter++ & mask) == mask) should be true. + private long invocationCounter = 0; + + private volatile long mask = 0xF; + private volatile long lastMaskCheck = System.currentTimeMillis(); + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (!isStarted()) { + return FilterReply.NEUTRAL; + } + + // for performance reasons, skip change detection (MASK-1) times out of MASK. + // Only once every MASK calls is change detection code executed + // Note that MASK is a variable itself. + if (((invocationCounter++) & mask) != mask) { + return FilterReply.NEUTRAL; + } + + long now = System.currentTimeMillis(); + + synchronized (configurationWatchList) { + updateMaskIfNecessary(now); + if (changeDetected(now)) { + // Even though reconfiguration involves resetting the loggerContext, + // which clears the list of turbo filters including this instance, it is + // still possible for this instance to be subsequently invoked by another + // thread if it was already executing when the context was reset. + disableSubsequentReconfiguration(); + detachReconfigurationToNewThread(); + } + } + + return FilterReply.NEUTRAL; } - return FilterReply.NEUTRAL; - } + // experiments indicate that even for CPU intensive applications with 200 or more threads MASK + // values in the order of 0xFFFF is appropriate + private static final int MAX_MASK = 0xFFFF; + + // if less than MASK_INCREASE_THRESHOLD milliseconds elapse between invocations of updateMaskIfNecessary() method, + // then the mask should be increased + private static final long MASK_INCREASE_THRESHOLD = 100; + + // if more than MASK_DECREASE_THRESHOLD milliseconds elapse between invocations of updateMaskIfNecessary() method, + // then the mask should be decreased + private static final long MASK_DECREASE_THRESHOLD = MASK_INCREASE_THRESHOLD * 8; + + // update the mask so as to execute change detection code about once every 100 to 8000 milliseconds. + private void updateMaskIfNecessary(long now) { + final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck; + lastMaskCheck = now; + if (timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && (mask < MAX_MASK)) { + mask = (mask << 1) | 1; + } else if (timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD) { + mask = mask >>> 2; + } + } - // experiments indicate that even for CPU intensive applications with 200 or more threads MASK - // values in the order of 0xFFFF is appropriate - private static final int MAX_MASK = 0xFFFF; + // by detaching reconfiguration to a new thread, we release the various + // locks held by the current thread, in particular, the AppenderAttachable + // reader lock. + void detachReconfigurationToNewThread() { + addInfo("Detected change in [" + configurationWatchList.getCopyOfFileWatchList() + "]"); + context.getExecutorService().submit(new ReconfiguringThread()); + } + void updateNextCheck(long now) { + nextCheck = now + refreshPeriod; + } - // if less than MASK_INCREASE_THRESHOLD milliseconds elapse between invocations of updateMaskIfNecessary() method, - // then the mask should be increased - private static final long MASK_INCREASE_THRESHOLD = 100; + protected boolean changeDetected(long now) { + if (now >= nextCheck) { + updateNextCheck(now); + return configurationWatchList.changeDetected(); + } + return false; + } - // if more than MASK_DECREASE_THRESHOLD milliseconds elapse between invocations of updateMaskIfNecessary() method, - // then the mask should be decreased - private static final long MASK_DECREASE_THRESHOLD = MASK_INCREASE_THRESHOLD*8; + void disableSubsequentReconfiguration() { + nextCheck = Long.MAX_VALUE; + } - // update the mask so as to execute change detection code about once every 100 to 8000 milliseconds. - private void updateMaskIfNecessary(long now) { - final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck; - lastMaskCheck = now; - if (timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && (mask < MAX_MASK)) { - mask = (mask << 1) | 1; - } else if (timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD) { - mask = mask >>> 2; + public long getRefreshPeriod() { + return refreshPeriod; } - } - - // by detaching reconfiguration to a new thread, we release the various - // locks held by the current thread, in particular, the AppenderAttachable - // reader lock. - void detachReconfigurationToNewThread() { - addInfo("Detected change in [" + configurationWatchList.getCopyOfFileWatchList() + "]"); - context.getExecutorService().submit(new ReconfiguringThread()); - } - - void updateNextCheck(long now) { - nextCheck = now + refreshPeriod; - } - - protected boolean changeDetected(long now) { - if (now >= nextCheck) { - updateNextCheck(now); - return configurationWatchList.changeDetected(); + + public void setRefreshPeriod(long refreshPeriod) { + this.refreshPeriod = refreshPeriod; } - return false; - } - - void disableSubsequentReconfiguration() { - nextCheck = Long.MAX_VALUE; - } - - public long getRefreshPeriod() { - return refreshPeriod; - } - - public void setRefreshPeriod(long refreshPeriod) { - this.refreshPeriod = refreshPeriod; - } - - class ReconfiguringThread implements Runnable { - public void run() { - if (mainConfigurationURL == null) { - addInfo("Due to missing top level configuration file, skipping reconfiguration"); - return; - } - LoggerContext lc = (LoggerContext) context; - addInfo(CoreConstants.RESET_MSG_PREFIX + "named [" + context.getName() + "]"); - if (mainConfigurationURL.toString().endsWith("xml")) { - performXMLConfiguration(lc); - } else if (mainConfigurationURL.toString().endsWith("groovy")) { - if (EnvUtil.isGroovyAvailable()) { - lc.reset(); - // avoid directly referring to GafferConfigurator so as to avoid - // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 - GafferUtil.runGafferConfiguratorOn(lc, this, mainConfigurationURL); - } else { - addError("Groovy classes are not available on the class path. ABORTING INITIALIZATION."); + + class ReconfiguringThread implements Runnable { + public void run() { + if (mainConfigurationURL == null) { + addInfo("Due to missing top level configuration file, skipping reconfiguration"); + return; + } + LoggerContext lc = (LoggerContext) context; + addInfo(CoreConstants.RESET_MSG_PREFIX + "named [" + context.getName() + "]"); + if (mainConfigurationURL.toString().endsWith("xml")) { + performXMLConfiguration(lc); + } else if (mainConfigurationURL.toString().endsWith("groovy")) { + if (EnvUtil.isGroovyAvailable()) { + lc.reset(); + // avoid directly referring to GafferConfigurator so as to avoid + // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 + GafferUtil.runGafferConfiguratorOn(lc, this, mainConfigurationURL); + } else { + addError("Groovy classes are not available on the class path. ABORTING INITIALIZATION."); + } + } } - } - } - private void performXMLConfiguration(LoggerContext lc) { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(context); - StatusUtil statusUtil = new StatusUtil(context); - List eventList = jc.recallSafeConfiguration(); - URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(context); - lc.reset(); - long threshold = System.currentTimeMillis(); - try { - jc.doConfigure(mainConfigurationURL); - if (statusUtil.hasXMLParsingErrors(threshold)) { - fallbackConfiguration(lc, eventList, mainURL); + private void performXMLConfiguration(LoggerContext lc) { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + StatusUtil statusUtil = new StatusUtil(context); + List eventList = jc.recallSafeConfiguration(); + URL mainURL = ConfigurationWatchListUtil.getMainWatchURL(context); + lc.reset(); + long threshold = System.currentTimeMillis(); + try { + jc.doConfigure(mainConfigurationURL); + if (statusUtil.hasXMLParsingErrors(threshold)) { + fallbackConfiguration(lc, eventList, mainURL); + } + } catch (JoranException e) { + fallbackConfiguration(lc, eventList, mainURL); + } } - } catch (JoranException e) { - fallbackConfiguration(lc, eventList, mainURL); - } - } - private void fallbackConfiguration(LoggerContext lc, List eventList, URL mainURL) { - JoranConfigurator joranConfigurator = new JoranConfigurator(); - joranConfigurator.setContext(context); - if (eventList != null) { - addWarn("Falling back to previously registered safe configuration."); - try { - lc.reset(); - joranConfigurator.informContextOfURLUsedForConfiguration(context, mainURL); - joranConfigurator.doConfigure(eventList); - addInfo("Re-registering previous fallback configuration once more as a fallback configuration point"); - joranConfigurator.registerSafeConfiguration(); - } catch (JoranException e) { - addError("Unexpected exception thrown by a configuration considered safe.", e); + private void fallbackConfiguration(LoggerContext lc, List eventList, URL mainURL) { + JoranConfigurator joranConfigurator = new JoranConfigurator(); + joranConfigurator.setContext(context); + if (eventList != null) { + addWarn("Falling back to previously registered safe configuration."); + try { + lc.reset(); + joranConfigurator.informContextOfURLUsedForConfiguration(context, mainURL); + joranConfigurator.doConfigure(eventList); + addInfo("Re-registering previous fallback configuration once more as a fallback configuration point"); + joranConfigurator.registerSafeConfiguration(); + } catch (JoranException e) { + addError("Unexpected exception thrown by a configuration considered safe.", e); + } + } else { + addWarn("No previous configuration to fall back on."); + } } - } else { - addWarn("No previous configuration to fall back on."); - } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/TurboFilter.java b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/TurboFilter.java index 1bdda494241dc3d6971e0d467de80a02b7f88d18..d6c4d4cbf97934bd597b72a04da922b156289614 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/turbo/TurboFilter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/turbo/TurboFilter.java @@ -33,44 +33,41 @@ import ch.qos.logback.core.spi.LifeCycle; */ public abstract class TurboFilter extends ContextAwareBase implements LifeCycle { - private String name; - boolean start = false; - - - /** - * Make a decision based on the multiple parameters passed as arguments. - * The returned value should be one of {@link FilterReply#DENY}, - * {@link FilterReply#NEUTRAL}, or {@link FilterReply#ACCEPT}. - - * @param marker - * @param logger - * @param level - * @param format - * @param params - * @param t - * @return - */ - public abstract FilterReply decide(Marker marker, Logger logger, - Level level, String format, Object[] params, Throwable t); + private String name; + boolean start = false; - public void start() { - this.start = true; - } - - public boolean isStarted() { - return this.start; - } - - public void stop() { - this.start = false; - } + /** + * Make a decision based on the multiple parameters passed as arguments. + * The returned value should be one of {@link FilterReply#DENY}, + * {@link FilterReply#NEUTRAL}, or {@link FilterReply#ACCEPT}. + + * @param marker + * @param logger + * @param level + * @param format + * @param params + * @param t + * @return + */ + public abstract FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t); + public void start() { + this.start = true; + } - public String getName() { - return name; - } + public boolean isStarted() { + return this.start; + } - public void setName(String name) { - this.name = name; - } + public void stop() { + this.start = false; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextInitializer.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextInitializer.java index 5a2dd8dbfad1307ef00db81de710c10b5e3fd40b..03bff18c4cb3d38740a618f7f08af0864b235a79 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextInitializer.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextInitializer.java @@ -44,156 +44,149 @@ import ch.qos.logback.core.util.StatusListenerConfigHelper; */ public class ContextInitializer { - final public static String GROOVY_AUTOCONFIG_FILE = "logback.groovy"; - final public static String AUTOCONFIG_FILE = "logback.xml"; - final public static String TEST_AUTOCONFIG_FILE = "logback-test.xml"; - final public static String CONFIG_FILE_PROPERTY = "logback.configurationFile"; + final public static String GROOVY_AUTOCONFIG_FILE = "logback.groovy"; + final public static String AUTOCONFIG_FILE = "logback.xml"; + final public static String TEST_AUTOCONFIG_FILE = "logback-test.xml"; + final public static String CONFIG_FILE_PROPERTY = "logback.configurationFile"; + final LoggerContext loggerContext; - final LoggerContext loggerContext; + public ContextInitializer(LoggerContext loggerContext) { + this.loggerContext = loggerContext; + } - public ContextInitializer(LoggerContext loggerContext) { - this.loggerContext = loggerContext; - } + public void configureByResource(URL url) throws JoranException { + if (url == null) { + throw new IllegalArgumentException("URL argument cannot be null"); + } + final String urlString = url.toString(); + if (urlString.endsWith("groovy")) { + if (EnvUtil.isGroovyAvailable()) { + // avoid directly referring to GafferConfigurator so as to avoid + // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 + GafferUtil.runGafferConfiguratorOn(loggerContext, this, url); + } else { + StatusManager sm = loggerContext.getStatusManager(); + sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", loggerContext)); + } + } else if (urlString.endsWith("xml")) { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(loggerContext); + configurator.doConfigure(url); + } else { + throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml"); + } + } - public void configureByResource(URL url) throws JoranException { - if (url == null) { - throw new IllegalArgumentException("URL argument cannot be null"); + void joranConfigureByResource(URL url) throws JoranException { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(loggerContext); + configurator.doConfigure(url); } - final String urlString = url.toString(); - if (urlString.endsWith("groovy")) { - if (EnvUtil.isGroovyAvailable()) { - // avoid directly referring to GafferConfigurator so as to avoid - // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 - GafferUtil.runGafferConfiguratorOn(loggerContext, this, url); - } else { - StatusManager sm = loggerContext.getStatusManager(); - sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", - loggerContext)); - } - } else if (urlString.endsWith("xml")) { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - configurator.doConfigure(url); - } else { - throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml"); + + private URL findConfigFileURLFromSystemProperties(ClassLoader classLoader, boolean updateStatus) { + String logbackConfigFile = OptionHelper.getSystemProperty(CONFIG_FILE_PROPERTY); + if (logbackConfigFile != null) { + URL result = null; + try { + result = new URL(logbackConfigFile); + return result; + } catch (MalformedURLException e) { + // so, resource is not a URL: + // attempt to get the resource from the class path + result = Loader.getResource(logbackConfigFile, classLoader); + if (result != null) { + return result; + } + File f = new File(logbackConfigFile); + if (f.exists() && f.isFile()) { + try { + result = f.toURI().toURL(); + return result; + } catch (MalformedURLException e1) { + } + } + } finally { + if (updateStatus) { + statusOnResourceSearch(logbackConfigFile, classLoader, result); + } + } + } + return null; } - } - - void joranConfigureByResource(URL url) throws JoranException { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - configurator.doConfigure(url); - } - - private URL findConfigFileURLFromSystemProperties(ClassLoader classLoader, boolean updateStatus) { - String logbackConfigFile = OptionHelper.getSystemProperty(CONFIG_FILE_PROPERTY); - if (logbackConfigFile != null) { - URL result = null; - try { - result = new URL(logbackConfigFile); - return result; - } catch (MalformedURLException e) { - // so, resource is not a URL: - // attempt to get the resource from the class path - result = Loader.getResource(logbackConfigFile, classLoader); - if (result != null) { - return result; + + public URL findURLOfDefaultConfigurationFile(boolean updateStatus) { + ClassLoader myClassLoader = Loader.getClassLoaderOfObject(this); + URL url = findConfigFileURLFromSystemProperties(myClassLoader, updateStatus); + if (url != null) { + return url; } - File f = new File(logbackConfigFile); - if (f.exists() && f.isFile()) { - try { - result = f.toURI().toURL(); - return result; - } catch (MalformedURLException e1) { - } + + url = getResource(GROOVY_AUTOCONFIG_FILE, myClassLoader, updateStatus); + if (url != null) { + return url; } - } finally { - if (updateStatus) { - statusOnResourceSearch(logbackConfigFile, classLoader, result); + + url = getResource(TEST_AUTOCONFIG_FILE, myClassLoader, updateStatus); + if (url != null) { + return url; } - } - } - return null; - } - - public URL findURLOfDefaultConfigurationFile(boolean updateStatus) { - ClassLoader myClassLoader = Loader.getClassLoaderOfObject(this); - URL url = findConfigFileURLFromSystemProperties(myClassLoader, updateStatus); - if (url != null) { - return url; - } - url = getResource(GROOVY_AUTOCONFIG_FILE, myClassLoader, updateStatus); - if (url != null) { - return url; + return getResource(AUTOCONFIG_FILE, myClassLoader, updateStatus); } - url = getResource(TEST_AUTOCONFIG_FILE, myClassLoader, updateStatus); - if (url != null) { - return url; + private URL getResource(String filename, ClassLoader myClassLoader, boolean updateStatus) { + URL url = Loader.getResource(filename, myClassLoader); + if (updateStatus) { + statusOnResourceSearch(filename, myClassLoader, url); + } + return url; } - return getResource(AUTOCONFIG_FILE, myClassLoader, updateStatus); - } + public void autoConfig() throws JoranException { + StatusListenerConfigHelper.installIfAsked(loggerContext); + URL url = findURLOfDefaultConfigurationFile(true); + if (url != null) { + configureByResource(url); + } else { + Configurator c = EnvUtil.loadFromServiceLoader(Configurator.class); + if (c != null) { + try { + c.setContext(loggerContext); + c.configure(loggerContext); + } catch (Exception e) { + throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", c != null ? c.getClass() + .getCanonicalName() : "null"), e); + } + } else { + BasicConfigurator.configure(loggerContext); + } + } + } - private URL getResource(String filename, ClassLoader myClassLoader, boolean updateStatus) { - URL url = Loader.getResource(filename, myClassLoader); - if (updateStatus) { - statusOnResourceSearch(filename, myClassLoader, url); + private void statusOnResourceSearch(String resourceName, ClassLoader classLoader, URL url) { + StatusManager sm = loggerContext.getStatusManager(); + if (url == null) { + sm.add(new InfoStatus("Could NOT find resource [" + resourceName + "]", loggerContext)); + } else { + sm.add(new InfoStatus("Found resource [" + resourceName + "] at [" + url.toString() + "]", loggerContext)); + multiplicityWarning(resourceName, classLoader); + } } - return url; - } - - public void autoConfig() throws JoranException { - StatusListenerConfigHelper.installIfAsked(loggerContext); - URL url = findURLOfDefaultConfigurationFile(true); - if (url != null) { - configureByResource(url); - } else { - Configurator c = EnvUtil.loadFromServiceLoader(Configurator.class); - if (c != null) { + + private void multiplicityWarning(String resourceName, ClassLoader classLoader) { + Set urlSet = null; + StatusManager sm = loggerContext.getStatusManager(); try { - c.setContext(loggerContext); - c.configure(loggerContext); - } catch (Exception e) { - throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", - c != null ? c.getClass().getCanonicalName() : "null"), e); + urlSet = Loader.getResources(resourceName, classLoader); + } catch (IOException e) { + sm.add(new ErrorStatus("Failed to get url list for resource [" + resourceName + "]", loggerContext, e)); } - } else { - BasicConfigurator.configure(loggerContext); - } - } - } - - private void statusOnResourceSearch(String resourceName, ClassLoader classLoader, URL url) { - StatusManager sm = loggerContext.getStatusManager(); - if (url == null) { - sm.add(new InfoStatus("Could NOT find resource [" + resourceName + "]", - loggerContext)); - } else { - sm.add(new InfoStatus("Found resource [" + resourceName + "] at [" + url.toString() + "]", - loggerContext)); - multiplicityWarning(resourceName, classLoader); - } - } - - private void multiplicityWarning(String resourceName, ClassLoader classLoader) { - Set urlSet = null; - StatusManager sm = loggerContext.getStatusManager(); - try { - urlSet = Loader.getResources(resourceName, classLoader); - } catch (IOException e) { - sm.add(new ErrorStatus("Failed to get url list for resource [" + resourceName + "]", - loggerContext, e)); - } - if (urlSet != null && urlSet.size() > 1) { - sm.add(new WarnStatus("Resource [" + resourceName + "] occurs multiple times on the classpath.", - loggerContext)); - for (URL url : urlSet) { - sm.add(new WarnStatus("Resource [" + resourceName + "] occurs at [" + url.toString() + "]", - loggerContext)); + if (urlSet != null && urlSet.size() > 1) { + sm.add(new WarnStatus("Resource [" + resourceName + "] occurs multiple times on the classpath.", loggerContext)); + for (URL url : urlSet) { + sm.add(new WarnStatus("Resource [" + resourceName + "] occurs at [" + url.toString() + "]", loggerContext)); + } } - } } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextSelectorStaticBinder.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextSelectorStaticBinder.java index b02aba941ab16c2f284fda58da2a3ed430d2f08c..35de01cc830a47fcb6d5287dbede80a3611c8473 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextSelectorStaticBinder.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/ContextSelectorStaticBinder.java @@ -32,76 +32,69 @@ import ch.qos.logback.core.util.OptionHelper; */ public class ContextSelectorStaticBinder { - static ContextSelectorStaticBinder singleton = new ContextSelectorStaticBinder(); + static ContextSelectorStaticBinder singleton = new ContextSelectorStaticBinder(); - ContextSelector contextSelector; - Object key; - - public static ContextSelectorStaticBinder getSingleton() { - return singleton; - } + ContextSelector contextSelector; + Object key; - /** - * FOR INTERNAL USE. This method is intended for use by StaticLoggerBinder. - * - * @param defaultLoggerContext - * @throws ClassNotFoundException - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws InvocationTargetException - */ - public void init(LoggerContext defaultLoggerContext, Object key) throws ClassNotFoundException, - NoSuchMethodException, InstantiationException, IllegalAccessException, - InvocationTargetException { - if(this.key == null) { - this.key = key; - } else if (this.key != key) { - throw new IllegalAccessException("Only certain classes can access this method."); + public static ContextSelectorStaticBinder getSingleton() { + return singleton; } - - - String contextSelectorStr = OptionHelper - .getSystemProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR); - if (contextSelectorStr == null) { - contextSelector = new DefaultContextSelector(defaultLoggerContext); - } else if (contextSelectorStr.equals("JNDI")) { - // if jndi is specified, let's use the appropriate class - contextSelector = new ContextJNDISelector(defaultLoggerContext); - } else { - contextSelector = dynamicalContextSelector(defaultLoggerContext, - contextSelectorStr); + + /** + * FOR INTERNAL USE. This method is intended for use by StaticLoggerBinder. + * + * @param defaultLoggerContext + * @throws ClassNotFoundException + * @throws NoSuchMethodException + * @throws InstantiationException + * @throws IllegalAccessException + * @throws InvocationTargetException + */ + public void init(LoggerContext defaultLoggerContext, Object key) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, + IllegalAccessException, InvocationTargetException { + if (this.key == null) { + this.key = key; + } else if (this.key != key) { + throw new IllegalAccessException("Only certain classes can access this method."); + } + + String contextSelectorStr = OptionHelper.getSystemProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR); + if (contextSelectorStr == null) { + contextSelector = new DefaultContextSelector(defaultLoggerContext); + } else if (contextSelectorStr.equals("JNDI")) { + // if jndi is specified, let's use the appropriate class + contextSelector = new ContextJNDISelector(defaultLoggerContext); + } else { + contextSelector = dynamicalContextSelector(defaultLoggerContext, contextSelectorStr); + } + } + + /** + * Instantiate the context selector class designated by the user. The selector + * must have a constructor taking a LoggerContext instance as an argument. + * + * @param defaultLoggerContext + * @param contextSelectorStr + * @return an instance of the designated context selector class + * @throws ClassNotFoundException + * @throws SecurityException + * @throws NoSuchMethodException + * @throws IllegalArgumentException + * @throws InstantiationException + * @throws IllegalAccessException + * @throws InvocationTargetException + */ + static ContextSelector dynamicalContextSelector(LoggerContext defaultLoggerContext, String contextSelectorStr) throws ClassNotFoundException, + SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, + InvocationTargetException { + Class contextSelectorClass = Loader.loadClass(contextSelectorStr); + Constructor cons = contextSelectorClass.getConstructor(new Class[] { LoggerContext.class }); + return (ContextSelector) cons.newInstance(defaultLoggerContext); + } + + public ContextSelector getContextSelector() { + return contextSelector; } - } - - /** - * Instantiate the context selector class designated by the user. The selector - * must have a constructor taking a LoggerContext instance as an argument. - * - * @param defaultLoggerContext - * @param contextSelectorStr - * @return an instance of the designated context selector class - * @throws ClassNotFoundException - * @throws SecurityException - * @throws NoSuchMethodException - * @throws IllegalArgumentException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws InvocationTargetException - */ - static ContextSelector dynamicalContextSelector( - LoggerContext defaultLoggerContext, String contextSelectorStr) - throws ClassNotFoundException, SecurityException, NoSuchMethodException, - IllegalArgumentException, InstantiationException, IllegalAccessException, - InvocationTargetException { - Class contextSelectorClass = Loader.loadClass(contextSelectorStr); - Constructor cons = contextSelectorClass - .getConstructor(new Class[] { LoggerContext.class }); - return (ContextSelector) cons.newInstance(defaultLoggerContext); - } - - public ContextSelector getContextSelector() { - return contextSelector; - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/CopyOnInheritThreadLocal.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/CopyOnInheritThreadLocal.java index c947c82092ca1a27ce2dc52bf2d4f152762bcf9f..fdec49e19658085de6417c2b76ca637d9e56616c 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/CopyOnInheritThreadLocal.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/CopyOnInheritThreadLocal.java @@ -21,20 +21,18 @@ import java.util.HashMap; * * @author Ceki Gülcü */ -public class CopyOnInheritThreadLocal extends - InheritableThreadLocal> { +public class CopyOnInheritThreadLocal extends InheritableThreadLocal> { - /** - * Child threads should get a copy of the parent's hashmap. - */ - @Override - protected HashMap childValue( - HashMap parentValue) { - if (parentValue == null) { - return null; - } else { - return new HashMap(parentValue); + /** + * Child threads should get a copy of the parent's hashmap. + */ + @Override + protected HashMap childValue(HashMap parentValue) { + if (parentValue == null) { + return null; + } else { + return new HashMap(parentValue); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/DefaultNestedComponentRules.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/DefaultNestedComponentRules.java index 571571ac57d5c4bc87a0bc0f3c113a18a10ce47e..ed8337b43cb97a20f52806acea036bba0e9e59c1 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/DefaultNestedComponentRules.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/DefaultNestedComponentRules.java @@ -31,18 +31,16 @@ import ch.qos.logback.core.net.ssl.SSLNestedComponentRegistryRules; */ public class DefaultNestedComponentRules { - static public void addDefaultNestedComponentRegistryRules( - DefaultNestedComponentRegistry registry) { - registry.add(AppenderBase.class, "layout", PatternLayout.class); - registry.add(UnsynchronizedAppenderBase.class, "layout", PatternLayout.class); - - registry.add(AppenderBase.class, "encoder", PatternLayoutEncoder.class); - registry.add(UnsynchronizedAppenderBase.class, "encoder", PatternLayoutEncoder.class); - - registry - .add(EvaluatorFilter.class, "evaluator", JaninoEventEvaluator.class); + static public void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + registry.add(AppenderBase.class, "layout", PatternLayout.class); + registry.add(UnsynchronizedAppenderBase.class, "layout", PatternLayout.class); - SSLNestedComponentRegistryRules.addDefaultNestedComponentRegistryRules(registry); - } + registry.add(AppenderBase.class, "encoder", PatternLayoutEncoder.class); + registry.add(UnsynchronizedAppenderBase.class, "encoder", PatternLayoutEncoder.class); + + registry.add(EvaluatorFilter.class, "evaluator", JaninoEventEvaluator.class); + + SSLNestedComponentRegistryRules.addDefaultNestedComponentRegistryRules(registry); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/EnvUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/EnvUtil.java index d361cdb2f603789b15093f650ad9d1177e49e21e..2e8cbbbab253ec8bc1168418797204cabffef9fb 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/EnvUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/EnvUtil.java @@ -23,37 +23,33 @@ import ch.qos.logback.core.util.Loader; */ public class EnvUtil { + /* + * Used to replace the ClassLoader that the ServiceLoader uses for unit testing. We need this to mock the resources + * the ServiceLoader attempts to load from /META-INF/services thus keeping the projects src/test/resources clean + * (see src/test/resources/README.txt). + */ + static ClassLoader testServiceLoaderClassLoader = null; - /* - * Used to replace the ClassLoader that the ServiceLoader uses for unit testing. - * We need this to mock the resources the ServiceLoader attempts to load from - * /META-INF/services thus keeping the projects src/test/resources clean - * (see src/test/resources/README.txt). - */ - static ClassLoader testServiceLoaderClassLoader = null; - - static public boolean isGroovyAvailable() { - ClassLoader classLoader = Loader.getClassLoaderOfClass(EnvUtil.class); - try { - Class bindingClass = classLoader.loadClass("groovy.lang.Binding"); - return (bindingClass != null); - } catch (ClassNotFoundException e) { - return false; + static public boolean isGroovyAvailable() { + ClassLoader classLoader = Loader.getClassLoaderOfClass(EnvUtil.class); + try { + Class bindingClass = classLoader.loadClass("groovy.lang.Binding"); + return (bindingClass != null); + } catch (ClassNotFoundException e) { + return false; + } + } + + private static ClassLoader getServiceLoaderClassLoader() { + return testServiceLoaderClassLoader == null ? Loader.getClassLoaderOfClass(EnvUtil.class) : testServiceLoaderClassLoader; + } + + public static T loadFromServiceLoader(Class c) { + ServiceLoader loader = ServiceLoader.load(c, getServiceLoaderClassLoader()); + Iterator it = loader.iterator(); + if (it.hasNext()) + return it.next(); + return null; } - } - - - private static ClassLoader getServiceLoaderClassLoader() { - return testServiceLoaderClassLoader == null ? Loader.getClassLoaderOfClass(EnvUtil.class) : testServiceLoaderClassLoader; - } - - public static T loadFromServiceLoader(Class c) { - ServiceLoader loader = ServiceLoader.load(c, getServiceLoaderClassLoader() ); - Iterator it = loader.iterator(); - if (it.hasNext()) - return it.next(); - return null; - } - } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/JNDIUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/JNDIUtil.java index 8a8d3225e612f579e5e4775900a1897efb3a9325..efa5ff169f3b08e946127ef0d78d1ea081177128 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/JNDIUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/JNDIUtil.java @@ -25,20 +25,20 @@ import javax.naming.NamingException; */ public class JNDIUtil { - - public static Context getInitialContext() throws NamingException { - return new InitialContext(); - } - public static String lookup(Context ctx, String name) { - if (ctx == null) { - return null; + public static Context getInitialContext() throws NamingException { + return new InitialContext(); } - try { - Object lookup = ctx.lookup(name); - return lookup == null ? null : lookup.toString(); - } catch (NamingException e) { - return null; + + public static String lookup(Context ctx, String name) { + if (ctx == null) { + return null; + } + try { + Object lookup = ctx.lookup(name); + return lookup == null ? null : lookup.toString(); + } catch (NamingException e) { + return null; + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/LevelToSyslogSeverity.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/LevelToSyslogSeverity.java index 22b466b091eeb065eaf923e64b3d59bd835e4f8c..c5e6c960d1f8a20dbba82e9e6e92c02bb08c53d7 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/LevelToSyslogSeverity.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/LevelToSyslogSeverity.java @@ -19,28 +19,26 @@ import ch.qos.logback.core.net.SyslogConstants; public class LevelToSyslogSeverity { - /* - * Convert a level to equivalent syslog severity. Only levels for printing - * methods i.e TRACE, DEBUG, WARN, INFO and ERROR are converted. - * - */ - static public int convert(ILoggingEvent event) { + /* + * Convert a level to equivalent syslog severity. Only levels for printing methods i.e TRACE, DEBUG, WARN, INFO and + * ERROR are converted. + */ + static public int convert(ILoggingEvent event) { - Level level = event.getLevel(); + Level level = event.getLevel(); - switch (level.levelInt) { - case Level.ERROR_INT: - return SyslogConstants.ERROR_SEVERITY; - case Level.WARN_INT: - return SyslogConstants.WARNING_SEVERITY; - case Level.INFO_INT: - return SyslogConstants.INFO_SEVERITY; - case Level.DEBUG_INT: - case Level.TRACE_INT: - return SyslogConstants.DEBUG_SEVERITY; - default: - throw new IllegalArgumentException("Level " + level - + " is not a valid level for a printing method"); + switch (level.levelInt) { + case Level.ERROR_INT: + return SyslogConstants.ERROR_SEVERITY; + case Level.WARN_INT: + return SyslogConstants.WARNING_SEVERITY; + case Level.INFO_INT: + return SyslogConstants.INFO_SEVERITY; + case Level.DEBUG_INT: + case Level.TRACE_INT: + return SyslogConstants.DEBUG_SEVERITY; + default: + throw new IllegalArgumentException("Level " + level + " is not a valid level for a printing method"); + } } - } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/LogbackMDCAdapter.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/LogbackMDCAdapter.java index d127a8e17f1c4b499774b61b8e4cae9e914f6ed7..34505960d0470406a6760bb704aa8ec0efa07b21 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/LogbackMDCAdapter.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/LogbackMDCAdapter.java @@ -38,165 +38,165 @@ import org.slf4j.spi.MDCAdapter; */ public class LogbackMDCAdapter implements MDCAdapter { - // The internal map is copied so as - - // We wish to avoid unnecessarily copying of the map. To ensure - // efficient/timely copying, we have a variable keeping track of the last - // operation. A copy is necessary on 'put' or 'remove' but only if the last - // operation was a 'get'. Get operations never necessitate a copy nor - // successive 'put/remove' operations, only a get followed by a 'put/remove' - // requires copying the map. - // See http://jira.qos.ch/browse/LOGBACK-620 for the original discussion. - - // We no longer use CopyOnInheritThreadLocal in order to solve LBCLASSIC-183 - // Initially the contents of the thread local in parent and child threads - // reference the same map. However, as soon as a thread invokes the put() - // method, the maps diverge as they should. - final ThreadLocal> copyOnThreadLocal = new ThreadLocal>(); - - private static final int WRITE_OPERATION = 1; - private static final int MAP_COPY_OPERATION = 2; - - // keeps track of the last operation performed - final ThreadLocal lastOperation = new ThreadLocal(); - - private Integer getAndSetLastOperation(int op) { - Integer lastOp = lastOperation.get(); - lastOperation.set(op); - return lastOp; - } - - private boolean wasLastOpReadOrNull(Integer lastOp) { - return lastOp == null || lastOp.intValue() == MAP_COPY_OPERATION; - } - - private Map duplicateAndInsertNewMap(Map oldMap) { - Map newMap = Collections.synchronizedMap(new HashMap()); - if (oldMap != null) { - // we don't want the parent thread modifying oldMap while we are - // iterating over it - synchronized (oldMap) { - newMap.putAll(oldMap); - } + // The internal map is copied so as + + // We wish to avoid unnecessarily copying of the map. To ensure + // efficient/timely copying, we have a variable keeping track of the last + // operation. A copy is necessary on 'put' or 'remove' but only if the last + // operation was a 'get'. Get operations never necessitate a copy nor + // successive 'put/remove' operations, only a get followed by a 'put/remove' + // requires copying the map. + // See http://jira.qos.ch/browse/LOGBACK-620 for the original discussion. + + // We no longer use CopyOnInheritThreadLocal in order to solve LBCLASSIC-183 + // Initially the contents of the thread local in parent and child threads + // reference the same map. However, as soon as a thread invokes the put() + // method, the maps diverge as they should. + final ThreadLocal> copyOnThreadLocal = new ThreadLocal>(); + + private static final int WRITE_OPERATION = 1; + private static final int MAP_COPY_OPERATION = 2; + + // keeps track of the last operation performed + final ThreadLocal lastOperation = new ThreadLocal(); + + private Integer getAndSetLastOperation(int op) { + Integer lastOp = lastOperation.get(); + lastOperation.set(op); + return lastOp; } - copyOnThreadLocal.set(newMap); - return newMap; - } - - /** - * Put a context value (the val parameter) as identified with the - * key parameter into the current thread's context map. Note that - * contrary to log4j, the val parameter can be null. - *

- *

- * If the current thread does not have a context map it is created as a side - * effect of this call. - * - * @throws IllegalArgumentException in case the "key" parameter is null - */ - public void put(String key, String val) throws IllegalArgumentException { - if (key == null) { - throw new IllegalArgumentException("key cannot be null"); + private boolean wasLastOpReadOrNull(Integer lastOp) { + return lastOp == null || lastOp.intValue() == MAP_COPY_OPERATION; } - Map oldMap = copyOnThreadLocal.get(); - Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); + private Map duplicateAndInsertNewMap(Map oldMap) { + Map newMap = Collections.synchronizedMap(new HashMap()); + if (oldMap != null) { + // we don't want the parent thread modifying oldMap while we are + // iterating over it + synchronized (oldMap) { + newMap.putAll(oldMap); + } + } - if (wasLastOpReadOrNull(lastOp) || oldMap == null) { - Map newMap = duplicateAndInsertNewMap(oldMap); - newMap.put(key, val); - } else { - oldMap.put(key, val); + copyOnThreadLocal.set(newMap); + return newMap; } - } - - /** - * Remove the the context identified by the key parameter. - *

- */ - public void remove(String key) { - if (key == null) { - return; + + /** + * Put a context value (the val parameter) as identified with the + * key parameter into the current thread's context map. Note that + * contrary to log4j, the val parameter can be null. + *

+ *

+ * If the current thread does not have a context map it is created as a side + * effect of this call. + * + * @throws IllegalArgumentException in case the "key" parameter is null + */ + public void put(String key, String val) throws IllegalArgumentException { + if (key == null) { + throw new IllegalArgumentException("key cannot be null"); + } + + Map oldMap = copyOnThreadLocal.get(); + Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); + + if (wasLastOpReadOrNull(lastOp) || oldMap == null) { + Map newMap = duplicateAndInsertNewMap(oldMap); + newMap.put(key, val); + } else { + oldMap.put(key, val); + } } - Map oldMap = copyOnThreadLocal.get(); - if (oldMap == null) return; - Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); + /** + * Remove the the context identified by the key parameter. + *

+ */ + public void remove(String key) { + if (key == null) { + return; + } + Map oldMap = copyOnThreadLocal.get(); + if (oldMap == null) + return; + + Integer lastOp = getAndSetLastOperation(WRITE_OPERATION); - if (wasLastOpReadOrNull(lastOp)) { - Map newMap = duplicateAndInsertNewMap(oldMap); - newMap.remove(key); - } else { - oldMap.remove(key); + if (wasLastOpReadOrNull(lastOp)) { + Map newMap = duplicateAndInsertNewMap(oldMap); + newMap.remove(key); + } else { + oldMap.remove(key); + } } - } - - - /** - * Clear all entries in the MDC. - */ - public void clear() { - lastOperation.set(WRITE_OPERATION); - copyOnThreadLocal.remove(); - } - - /** - * Get the context identified by the key parameter. - *

- */ - public String get(String key) { - final Map map = copyOnThreadLocal.get(); - if ((map != null) && (key != null)) { - return map.get(key); - } else { - return null; + + /** + * Clear all entries in the MDC. + */ + public void clear() { + lastOperation.set(WRITE_OPERATION); + copyOnThreadLocal.remove(); } - } - - /** - * Get the current thread's MDC as a map. This method is intended to be used - * internally. - */ - public Map getPropertyMap() { - lastOperation.set(MAP_COPY_OPERATION); - return copyOnThreadLocal.get(); - } - - /** - * Returns the keys in the MDC as a {@link Set}. The returned value can be - * null. - */ - public Set getKeys() { - Map map = getPropertyMap(); - - if (map != null) { - return map.keySet(); - } else { - return null; + + /** + * Get the context identified by the key parameter. + *

+ */ + public String get(String key) { + final Map map = copyOnThreadLocal.get(); + if ((map != null) && (key != null)) { + return map.get(key); + } else { + return null; + } + } + + /** + * Get the current thread's MDC as a map. This method is intended to be used + * internally. + */ + public Map getPropertyMap() { + lastOperation.set(MAP_COPY_OPERATION); + return copyOnThreadLocal.get(); + } + + /** + * Returns the keys in the MDC as a {@link Set}. The returned value can be + * null. + */ + public Set getKeys() { + Map map = getPropertyMap(); + + if (map != null) { + return map.keySet(); + } else { + return null; + } } - } - - /** - * Return a copy of the current thread's context map. Returned value may be - * null. - */ - public Map getCopyOfContextMap() { - Map hashMap = copyOnThreadLocal.get(); - if (hashMap == null) { - return null; - } else { - return new HashMap(hashMap); + + /** + * Return a copy of the current thread's context map. Returned value may be + * null. + */ + public Map getCopyOfContextMap() { + Map hashMap = copyOnThreadLocal.get(); + if (hashMap == null) { + return null; + } else { + return new HashMap(hashMap); + } } - } - public void setContextMap(Map contextMap) { - lastOperation.set(WRITE_OPERATION); + public void setContextMap(Map contextMap) { + lastOperation.set(WRITE_OPERATION); - Map newMap = Collections.synchronizedMap(new HashMap()); - newMap.putAll(contextMap); + Map newMap = Collections.synchronizedMap(new HashMap()); + newMap.putAll(contextMap); - // the newMap replaces the old one for serialisation's sake - copyOnThreadLocal.set(newMap); - } + // the newMap replaces the old one for serialisation's sake + copyOnThreadLocal.set(newMap); + } } diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/util/LoggerNameUtil.java b/logback-classic/src/main/java/ch/qos/logback/classic/util/LoggerNameUtil.java index aa958fc22cd5b7a84e8af9068223b4e5a51380b5..6fb40ebb05cf411a3804c2791023b495660558cd 100644 --- a/logback-classic/src/main/java/ch/qos/logback/classic/util/LoggerNameUtil.java +++ b/logback-classic/src/main/java/ch/qos/logback/classic/util/LoggerNameUtil.java @@ -23,43 +23,45 @@ import java.util.List; */ public class LoggerNameUtil { + public static int getFirstSeparatorIndexOf(String name) { + return getSeparatorIndexOf(name, 0); + } - public static int getFirstSeparatorIndexOf(String name) { - return getSeparatorIndexOf(name, 0); - } - - /** - * Get the position of the separator character, if any, starting at position - * 'fromIndex'. - * - * @param name - * @param fromIndex - * @return - */ - public static int getSeparatorIndexOf(String name, int fromIndex) { - int dotIndex = name.indexOf(CoreConstants.DOT, fromIndex); - int dollarIndex = name.indexOf(CoreConstants.DOLLAR, fromIndex); + /** + * Get the position of the separator character, if any, starting at position + * 'fromIndex'. + * + * @param name + * @param fromIndex + * @return + */ + public static int getSeparatorIndexOf(String name, int fromIndex) { + int dotIndex = name.indexOf(CoreConstants.DOT, fromIndex); + int dollarIndex = name.indexOf(CoreConstants.DOLLAR, fromIndex); - if (dotIndex == -1 && dollarIndex == -1) return -1; - if (dotIndex == -1) return dollarIndex; - if (dollarIndex == -1) return dotIndex; + if (dotIndex == -1 && dollarIndex == -1) + return -1; + if (dotIndex == -1) + return dollarIndex; + if (dollarIndex == -1) + return dotIndex; - return dotIndex < dollarIndex ? dotIndex : dollarIndex; - } + return dotIndex < dollarIndex ? dotIndex : dollarIndex; + } - public static List computeNameParts(String loggerName) { - List partList = new ArrayList(); + public static List computeNameParts(String loggerName) { + List partList = new ArrayList(); - int fromIndex = 0; - while(true) { - int index = getSeparatorIndexOf(loggerName, fromIndex); - if(index == -1) { - partList.add(loggerName.substring(fromIndex)); - break; - } - partList.add(loggerName.substring(fromIndex, index)); - fromIndex = index+1; + int fromIndex = 0; + while (true) { + int index = getSeparatorIndexOf(loggerName, fromIndex); + if (index == -1) { + partList.add(loggerName.substring(fromIndex)); + break; + } + partList.add(loggerName.substring(fromIndex, index)); + fromIndex = index + 1; + } + return partList; } - return partList; - } } diff --git a/logback-classic/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/logback-classic/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 6d4386f3d312a66a4123b99fd2b5da2aac97ac27..d5e78114ce7a13fb3f51681badd667195ae7273a 100644 --- a/logback-classic/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/logback-classic/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -35,83 +35,81 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class StaticLoggerBinder implements LoggerFactoryBinder { - /** - * Declare the version of the SLF4J API this implementation is compiled - * against. The value of this field is usually modified with each release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.7.16"; // !final - - final static String NULL_CS_URL = CoreConstants.CODES_URL + "#null_CS"; - - /** - * The unique instance of this class. - */ - private static StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - private static Object KEY = new Object(); - - static { - SINGLETON.init(); - } - - private boolean initialized = false; - private LoggerContext defaultLoggerContext = new LoggerContext(); - private final ContextSelectorStaticBinder contextSelectorBinder = ContextSelectorStaticBinder.getSingleton(); - - private StaticLoggerBinder() { - defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); - } - - public static StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Package access for testing purposes. - */ - static void reset() { - SINGLETON = new StaticLoggerBinder(); - SINGLETON.init(); - } - - /** - * Package access for testing purposes. - */ - void init() { - try { - try { - new ContextInitializer(defaultLoggerContext).autoConfig(); - } catch (JoranException je) { - Util.report("Failed to auto configure default logger context", je); - } - // logback-292 - if(!StatusUtil.contextHasStatusListener(defaultLoggerContext)) { - StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); - } - contextSelectorBinder.init(defaultLoggerContext, KEY); - initialized = true; - } catch (Throwable t) { - // we should never get here - Util.report("Failed to instantiate [" + LoggerContext.class.getName() - + "]", t); + /** + * Declare the version of the SLF4J API this implementation is compiled + * against. The value of this field is usually modified with each release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.7.16"; // !final + + final static String NULL_CS_URL = CoreConstants.CODES_URL + "#null_CS"; + + /** + * The unique instance of this class. + */ + private static StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + private static Object KEY = new Object(); + + static { + SINGLETON.init(); + } + + private boolean initialized = false; + private LoggerContext defaultLoggerContext = new LoggerContext(); + private final ContextSelectorStaticBinder contextSelectorBinder = ContextSelectorStaticBinder.getSingleton(); + + private StaticLoggerBinder() { + defaultLoggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); } - } - public ILoggerFactory getLoggerFactory() { - if (!initialized) { - return defaultLoggerContext; + public static StaticLoggerBinder getSingleton() { + return SINGLETON; } - if (contextSelectorBinder.getContextSelector() == null) { - throw new IllegalStateException( - "contextSelector cannot be null. See also " + NULL_CS_URL); + /** + * Package access for testing purposes. + */ + static void reset() { + SINGLETON = new StaticLoggerBinder(); + SINGLETON.init(); } - return contextSelectorBinder.getContextSelector().getLoggerContext(); - } - public String getLoggerFactoryClassStr() { - return contextSelectorBinder.getClass().getName(); - } + /** + * Package access for testing purposes. + */ + void init() { + try { + try { + new ContextInitializer(defaultLoggerContext).autoConfig(); + } catch (JoranException je) { + Util.report("Failed to auto configure default logger context", je); + } + // logback-292 + if (!StatusUtil.contextHasStatusListener(defaultLoggerContext)) { + StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); + } + contextSelectorBinder.init(defaultLoggerContext, KEY); + initialized = true; + } catch (Throwable t) { + // we should never get here + Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t); + } + } + + public ILoggerFactory getLoggerFactory() { + if (!initialized) { + return defaultLoggerContext; + } + + if (contextSelectorBinder.getContextSelector() == null) { + throw new IllegalStateException("contextSelector cannot be null. See also " + NULL_CS_URL); + } + return contextSelectorBinder.getContextSelector().getLoggerContext(); + } + + public String getLoggerFactoryClassStr() { + return contextSelectorBinder.getClass().getName(); + } } diff --git a/logback-classic/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/logback-classic/src/main/java/org/slf4j/impl/StaticMDCBinder.java index f6c359722b09579749a0089c8ef9b342304a6324..f5a5777e26dca6bcd9c614308ae0aca6a8dd5c8d 100644 --- a/logback-classic/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/logback-classic/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -17,7 +17,6 @@ import org.slf4j.spi.MDCAdapter; import ch.qos.logback.classic.util.LogbackMDCAdapter; - /** * This implementation is bound to {@link LogbackMDCAdapter}. * @@ -25,24 +24,23 @@ import ch.qos.logback.classic.util.LogbackMDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link StaticMDCBinder}. + */ + public MDCAdapter getMDCA() { + return new LogbackMDCAdapter(); + } - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new LogbackMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return LogbackMDCAdapter.class.getName(); - } + public String getMDCAdapterClassStr() { + return LogbackMDCAdapter.class.getName(); + } } diff --git a/logback-classic/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/logback-classic/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index d560b181131f82c87aa1a3da79f96e71796acf7e..157ba469c59d78f72cdff397400abf2be761b7d0 100644 --- a/logback-classic/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/logback-classic/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -27,31 +27,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ public class StaticMarkerBinder implements MarkerFactoryBinder { - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/AllClassicTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/AllClassicTest.java index 687bb2e58b952813da4b853552695b7f99626ef4..0d7047aa3da2d12eeb9018c07ec0814d311d6715 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/AllClassicTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/AllClassicTest.java @@ -18,25 +18,13 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({org.slf4j.impl.PackageTest.class, - ch.qos.logback.classic.PackageTest.class, - ch.qos.logback.classic.util.PackageTest.class, - ch.qos.logback.classic.control.PackageTest.class, - ch.qos.logback.classic.joran.PackageTest.class, - ch.qos.logback.classic.rolling.PackageTest.class, - ch.qos.logback.classic.jmx.PackageTest.class, - ch.qos.logback.classic.boolex.PackageTest.class, - ch.qos.logback.classic.selector.PackageTest.class, - ch.qos.logback.classic.html.PackageTest.class, - ch.qos.logback.classic.net.PackageTest.class, - ch.qos.logback.classic.pattern.PackageTest.class, - ch.qos.logback.classic.encoder.PackageTest.class, - ch.qos.logback.classic.db.PackageTest.class, - ch.qos.logback.classic.spi.PackageTest.class, - ch.qos.logback.classic.turbo.PackageTest.class, - ch.qos.logback.classic.sift.PackageTest.class, - ch.qos.logback.classic.jul.PackageTest.class, - ch.qos.logback.classic.issue.PackageTest.class}) +@SuiteClasses({ org.slf4j.impl.PackageTest.class, ch.qos.logback.classic.PackageTest.class, ch.qos.logback.classic.util.PackageTest.class, + ch.qos.logback.classic.control.PackageTest.class, ch.qos.logback.classic.joran.PackageTest.class, ch.qos.logback.classic.rolling.PackageTest.class, + ch.qos.logback.classic.jmx.PackageTest.class, ch.qos.logback.classic.boolex.PackageTest.class, ch.qos.logback.classic.selector.PackageTest.class, + ch.qos.logback.classic.html.PackageTest.class, ch.qos.logback.classic.net.PackageTest.class, ch.qos.logback.classic.pattern.PackageTest.class, + ch.qos.logback.classic.encoder.PackageTest.class, ch.qos.logback.classic.db.PackageTest.class, ch.qos.logback.classic.spi.PackageTest.class, + ch.qos.logback.classic.turbo.PackageTest.class, ch.qos.logback.classic.sift.PackageTest.class, ch.qos.logback.classic.jul.PackageTest.class, + ch.qos.logback.classic.issue.PackageTest.class }) public class AllClassicTest { } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/AsyncAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/AsyncAppenderTest.java index cc01ef81866fabbb0bebbb5434b49331df5ceb5f..2711724155bf4396b070ff529177dc6a424eeffb 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/AsyncAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/AsyncAppenderTest.java @@ -31,64 +31,62 @@ import static org.junit.Assert.*; */ public class AsyncAppenderTest { - String thisClassName = this.getClass().getName(); - LoggerContext context = new LoggerContext(); - AsyncAppender asyncAppender = new AsyncAppender(); - ListAppender listAppender = new ListAppender(); - OnConsoleStatusListener onConsoleStatusListener = new OnConsoleStatusListener(); - LoggingEventBuilderInContext builder = new LoggingEventBuilderInContext(context, thisClassName, UnsynchronizedAppenderBase.class.getName()); - int diff = RandomUtil.getPositiveInt(); - - @Before - public void setUp() { - onConsoleStatusListener.setContext(context); - context.getStatusManager().add(onConsoleStatusListener); - onConsoleStatusListener.start(); - - asyncAppender.setContext(context); - listAppender.setContext(context); - listAppender.setName("list"); - listAppender.start(); - } - - @Test - public void eventWasPreparedForDeferredProcessing() { - asyncAppender.addAppender(listAppender); - asyncAppender.start(); - - String k = "k" + diff; - MDC.put(k, "v"); - asyncAppender.doAppend(builder.build(diff)); - MDC.clear(); - - asyncAppender.stop(); - assertFalse(asyncAppender.isStarted()); - - // check the event - assertEquals(1, listAppender.list.size()); - ILoggingEvent e = listAppender.list.get(0); - - // check that MDC values were correctly retained - assertEquals("v", e.getMDCPropertyMap().get(k)); - assertFalse(e.hasCallerData()); - } - - - @Test - public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() { - asyncAppender.addAppender(listAppender); - asyncAppender.setIncludeCallerData(true); - asyncAppender.start(); - - - asyncAppender.doAppend(builder.build(diff)); - asyncAppender.stop(); - - // check the event - assertEquals(1, listAppender.list.size()); - ILoggingEvent e = listAppender.list.get(0); - assertTrue(e.hasCallerData()); - StackTraceElement ste = e.getCallerData()[0]; - assertEquals(thisClassName, ste.getClassName()); - } + String thisClassName = this.getClass().getName(); + LoggerContext context = new LoggerContext(); + AsyncAppender asyncAppender = new AsyncAppender(); + ListAppender listAppender = new ListAppender(); + OnConsoleStatusListener onConsoleStatusListener = new OnConsoleStatusListener(); + LoggingEventBuilderInContext builder = new LoggingEventBuilderInContext(context, thisClassName, UnsynchronizedAppenderBase.class.getName()); + int diff = RandomUtil.getPositiveInt(); + + @Before + public void setUp() { + onConsoleStatusListener.setContext(context); + context.getStatusManager().add(onConsoleStatusListener); + onConsoleStatusListener.start(); + + asyncAppender.setContext(context); + listAppender.setContext(context); + listAppender.setName("list"); + listAppender.start(); + } + + @Test + public void eventWasPreparedForDeferredProcessing() { + asyncAppender.addAppender(listAppender); + asyncAppender.start(); + + String k = "k" + diff; + MDC.put(k, "v"); + asyncAppender.doAppend(builder.build(diff)); + MDC.clear(); + + asyncAppender.stop(); + assertFalse(asyncAppender.isStarted()); + + // check the event + assertEquals(1, listAppender.list.size()); + ILoggingEvent e = listAppender.list.get(0); + + // check that MDC values were correctly retained + assertEquals("v", e.getMDCPropertyMap().get(k)); + assertFalse(e.hasCallerData()); + } + + @Test + public void settingIncludeCallerDataPropertyCausedCallerDataToBeIncluded() { + asyncAppender.addAppender(listAppender); + asyncAppender.setIncludeCallerData(true); + asyncAppender.start(); + + asyncAppender.doAppend(builder.build(diff)); + asyncAppender.stop(); + + // check the event + assertEquals(1, listAppender.list.size()); + ILoggingEvent e = listAppender.list.get(0); + assertTrue(e.hasCallerData()); + StackTraceElement ste = e.getCallerData()[0]; + assertEquals(thisClassName, ste.getClassName()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/ClassicTestConstants.java b/logback-classic/src/test/java/ch/qos/logback/classic/ClassicTestConstants.java index d1ebfefb3a966648f44cd31e8a046b2a3e16546c..61d6280cb717563a35982cf49f7b9cfadd192b66 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/ClassicTestConstants.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/ClassicTestConstants.java @@ -16,15 +16,14 @@ package ch.qos.logback.classic; import ch.qos.logback.core.util.CoreTestConstants; public class ClassicTestConstants { - final static public String ISO_REGEX = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}"; - //pool-1-thread-47 - final static public String NAKED_MAIN_REGEX = "([mM]ain|pool-\\d-)([Tt]hread)?(-\\d{1,3})?"; + final static public String ISO_REGEX = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}"; + // pool-1-thread-47 + final static public String NAKED_MAIN_REGEX = "([mM]ain|pool-\\d-)([Tt]hread)?(-\\d{1,3})?"; - - final static public String MAIN_REGEX = "\\[" + NAKED_MAIN_REGEX + "\\]"; - final static public String INPUT_PREFIX = "src/test/input/"; - final static public String JORAN_INPUT_PREFIX = INPUT_PREFIX + "joran/"; - final static public String ISSUES_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX+"issues/"; - final static public String GAFFER_INPUT_PREFIX = INPUT_PREFIX + "gaffer/"; - final static public String OUTPUT_DIR_PREFIX= CoreTestConstants.OUTPUT_DIR_PREFIX; + final static public String MAIN_REGEX = "\\[" + NAKED_MAIN_REGEX + "\\]"; + final static public String INPUT_PREFIX = "src/test/input/"; + final static public String JORAN_INPUT_PREFIX = INPUT_PREFIX + "joran/"; + final static public String ISSUES_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX + "issues/"; + final static public String GAFFER_INPUT_PREFIX = INPUT_PREFIX + "gaffer/"; + final static public String OUTPUT_DIR_PREFIX = CoreTestConstants.OUTPUT_DIR_PREFIX; } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/Foo.java b/logback-classic/src/test/java/ch/qos/logback/classic/Foo.java index bb88ef7b06a415498ae1a19a0c93357dca156c32..4f2ca09c8cd16f468f207f8f190a9f673420236d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/Foo.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/Foo.java @@ -16,15 +16,14 @@ package ch.qos.logback.classic; import java.io.Serializable; class Foo implements Serializable { - private static final long serialVersionUID = 1L; - final Logger logger; - - Foo(Logger logger) { - this.logger = logger; - } - - void doFoo() { - logger.debug("hello"); - } -} + private static final long serialVersionUID = 1L; + final Logger logger; + + Foo(Logger logger) { + this.logger = logger; + } + void doFoo() { + logger.debug("hello"); + } +} diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/HLogger.java b/logback-classic/src/test/java/ch/qos/logback/classic/HLogger.java index 4cbc3f0a7a546203d6dd72c6bdc0040a70eaf1e4..65aacde8b8fa3c0594dfe2fd81f2c6fd677bdd88 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/HLogger.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/HLogger.java @@ -24,385 +24,379 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.CoreConstants; - public class HLogger extends MarkerIgnoringBase { - private static final long serialVersionUID = 1L; - - static int instanceCount = 0; - - /** - * The name of this logger - */ - private String name; - - // The assigned levelInt of this logger. Can be null. - private Level level; - - // The effective levelInt is the assigned levelInt and if null, a levelInt is - // inherited form a parent. - private Level effectiveLevel; - - /** - * The parent of this category. All categories have at least one ancestor - * which is the root category. - */ - HLogger parent; - - /** - * The children of this logger. A logger may have zero or more children. - */ - Map childrenMap; - - /** - * Array of appenders. - */ - private ArrayList> appenderList; - - /** - * Additivity is set to true by default, that is children inherit the - * appenders of their ancestors by default. If this variable is set to - * false then the appenders located in the ancestors of this - * logger will not be used. However, the children of this logger will inherit - * its appenders, unless the children have their additivity flag set to - * false too. See the user manual for more details. - */ - protected boolean additive = true; - - HLogger(String name, HLogger parent) { - this.name = name; - this.parent = parent; - instanceCount++; - } - - Level getEffectiveLevel() { - return effectiveLevel; - } - - Level getLevel() { - return level; - } - - public String getName() { - return name; - } - - private boolean isRootLogger() { - // only the root logger has a null parent - return parent == null; - } - - /** - * Get a child by its suffix. - * - *

- * IMPORTANT: Calls to this method must be within a syncronized block on this - * logger! - * - * @param suffix - * @return - */ - HLogger getChildBySuffix(final String suffix) { - if (childrenMap == null) { - return null; - } else { - return (HLogger) childrenMap.get(suffix); - } - } - - public synchronized void setLevel(Level newLevel) { - if (level == newLevel) { - // nothing to do; - return; - } - - level = newLevel; - effectiveLevel = newLevel; - if (childrenMap != null) { - for (Iterator i = childrenMap.values().iterator(); i.hasNext();) { - HLogger child = (HLogger) i.next(); - - // tell child to handle parent levelInt change - child.handleParentLevelChange(effectiveLevel); - } - } - } - - /** - * This method is invoked by parent logger to let this logger know that the - * prent's levelInt changed. - * - * @param newParentLevel - */ - private synchronized void handleParentLevelChange(Level newParentLevel) { - // changes in the parent levelInt affect children only if their levelInt is - // null - if (level == null) { - effectiveLevel = newParentLevel; - - // propagate the parent levelInt change to this logger's children - if (childrenMap != null) { - for (Iterator i = childrenMap.values().iterator(); i.hasNext();) { - HLogger child = (HLogger) i.next(); - // tell child to handle parent levelInt change - child.handleParentLevelChange(effectiveLevel); + private static final long serialVersionUID = 1L; + + static int instanceCount = 0; + + /** + * The name of this logger + */ + private String name; + + // The assigned levelInt of this logger. Can be null. + private Level level; + + // The effective levelInt is the assigned levelInt and if null, a levelInt is + // inherited form a parent. + private Level effectiveLevel; + + /** + * The parent of this category. All categories have at least one ancestor + * which is the root category. + */ + HLogger parent; + + /** + * The children of this logger. A logger may have zero or more children. + */ + Map childrenMap; + + /** + * Array of appenders. + */ + private ArrayList> appenderList; + + /** + * Additivity is set to true by default, that is children inherit the + * appenders of their ancestors by default. If this variable is set to + * false then the appenders located in the ancestors of this + * logger will not be used. However, the children of this logger will inherit + * its appenders, unless the children have their additivity flag set to + * false too. See the user manual for more details. + */ + protected boolean additive = true; + + HLogger(String name, HLogger parent) { + this.name = name; + this.parent = parent; + instanceCount++; + } + + Level getEffectiveLevel() { + return effectiveLevel; + } + + Level getLevel() { + return level; + } + + public String getName() { + return name; + } + + private boolean isRootLogger() { + // only the root logger has a null parent + return parent == null; + } + + /** + * Get a child by its suffix. + * + *

+ * IMPORTANT: Calls to this method must be within a syncronized block on this + * logger! + * + * @param suffix + * @return + */ + HLogger getChildBySuffix(final String suffix) { + if (childrenMap == null) { + return null; + } else { + return (HLogger) childrenMap.get(suffix); } - } - } - } - - /** - * Remove all previously added appenders from this logger instance.

This - * is useful when re-reading configuration information. - */ - public synchronized void removeAllAppenders() { - if (appenderList != null) { - int len = appenderList.size(); - for (int i = 0; i < len; i++) { - Appender a = appenderList.get(i); - a.stop(); - } - appenderList.clear(); - appenderList = null; - } - } - - /** - * Invoke all the appenders of this logger. - * - * @param event - * The event to log - */ - public void callAppenders(ILoggingEvent event) { - int writes = 0; - - for (HLogger l = this; l != null; l = l.parent) { - // Protected against simultaneous call to addAppender, removeAppender,... - synchronized (l) { - if (l.appenderList != null) { - writes += l.appendLoopOnAppenders(event); + } + + public synchronized void setLevel(Level newLevel) { + if (level == newLevel) { + // nothing to do; + return; } - if (!l.additive) { - break; + + level = newLevel; + effectiveLevel = newLevel; + if (childrenMap != null) { + for (Iterator i = childrenMap.values().iterator(); i.hasNext();) { + HLogger child = (HLogger) i.next(); + + // tell child to handle parent levelInt change + child.handleParentLevelChange(effectiveLevel); + } + } + } + + /** + * This method is invoked by parent logger to let this logger know that the + * prent's levelInt changed. + * + * @param newParentLevel + */ + private synchronized void handleParentLevelChange(Level newParentLevel) { + // changes in the parent levelInt affect children only if their levelInt is + // null + if (level == null) { + effectiveLevel = newParentLevel; + + // propagate the parent levelInt change to this logger's children + if (childrenMap != null) { + for (Iterator i = childrenMap.values().iterator(); i.hasNext();) { + HLogger child = (HLogger) i.next(); + // tell child to handle parent levelInt change + child.handleParentLevelChange(effectiveLevel); + } + } + } + } + + /** + * Remove all previously added appenders from this logger instance.

This + * is useful when re-reading configuration information. + */ + public synchronized void removeAllAppenders() { + if (appenderList != null) { + int len = appenderList.size(); + for (int i = 0; i < len; i++) { + Appender a = appenderList.get(i); + a.stop(); + } + appenderList.clear(); + appenderList = null; } - } - } - - // No appenders in hierarchy, warn user only once. - // if(!hierarchy.emittedNoAppenderWarning && writes == 0) { - // LogLog.error("No appenders could be found for category (" + - // this.getName() + ")."); - // LogLog.error("Please initialize the log4j system properly."); - // hierarchy.emittedNoAppenderWarning = true; - // } - } - - private int appendLoopOnAppenders(ILoggingEvent event) { - int size = 0; - Appender appender; - - if (appenderList != null) { - size = appenderList.size(); - for (int i = 0; i < size; i++) { - appender = appenderList.get(i); - appender.doAppend(event); - } - } - return size; - } - - /** - * Remove the appender passed as parameter form the list of appenders. - */ - public synchronized void removeAppender(Appender appender) { - if ((appender == null) || (appenderList == null)) { - } - appenderList.remove(appender); - } - - /** - * Create a child of this logger by suffix, that is, the part of the name - * extending this logger. For example, if this logger is named "x.y" and the - * lastPart is "z", then the created child logger will be named "x.y.z". - * - *

- * IMPORTANT: Calls to this method must be within a syncronized block on this - * logger. - * - * @param lastPart - * the suffix (i.e. last part) of the child logger name. This - * parameter may not include dots, i.e. the logger separator - * character. - * @return - */ - HLogger createChildByLastNamePart(final String lastPart) { - int i_index = lastPart.indexOf(CoreConstants.DOT); - if (i_index != -1) { - throw new IllegalArgumentException("Child name [" + lastPart - + " passed as parameter, may not include [" + CoreConstants.DOT - + "]"); - } - - if (childrenMap == null) { - childrenMap = new HashMap(2); - } - HLogger childHLogger; - if (this.isRootLogger()) { - childHLogger = new HLogger(lastPart, this); - } else { - childHLogger = new HLogger(name + CoreConstants.DOT + lastPart, - this); - } - childrenMap.put(lastPart, childHLogger); - childHLogger.effectiveLevel = this.effectiveLevel; - return childHLogger; - } - - public final void trace(String msg) { - if (effectiveLevel.levelInt <= Level.TRACE_INT) { - throw new UnsupportedOperationException("not yet implemented"); - } - } - - public void trace(String msg, Throwable t) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void trace(Object parameterizedMsg, Object param1) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void trace(String parameterizedMsg, Object param1, Object param2) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - - - public final void debug(String msg) { - if (effectiveLevel.levelInt <= Level.DEBUG_INT) { - throw new UnsupportedOperationException("not yet implemented"); - } - } - - public void debug(String msg, Throwable t) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void debug(Object parameterizedMsg, Object param1) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void debug(String parameterizedMsg, Object param1, Object param2) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void error(String msg) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void error(String msg, Throwable t) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void error(String parameterizedMsg, Object param1) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void error(String parameterizedMsg, Object param1, Object param2) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void info(String msg) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void info(String msg, Throwable t) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void info(String parameterizedMsg, Object param1) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void info(String parameterizedMsg, Object param1, Object param2) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public boolean isTraceEnabled() { - return false; - } - - public boolean isDebugEnabled() { - return false; - } - - public boolean isErrorEnabled() { - return false; // To change body of implemented methods use File | Settings | - // File Templates. - } - - public boolean isInfoEnabled() { - return false; // To change body of implemented methods use File | Settings | - // File Templates. - } - - public boolean isWarnEnabled() { - return false; // To change body of implemented methods use File | Settings | - // File Templates. - } - - public void warn(String msg) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void warn(String msg, Throwable t) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void warn(String parameterizedMsg, Object param1) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void warn(String parameterizedMsg, Object param1, Object param2) { - // To change body of implemented methods use File | Settings | File - // Templates. - } - - public void trace(String format, Object arg) { - } - - public void trace(String format, Object[] argArray) { - } - - public void debug(String format, Object arg) { - } - - public void debug(String format, Object[] argArray) { - } - - public void info(String format, Object[] argArray) { - } - - public void warn(String format, Object[] argArray) { - } - - public void error(String format, Object[] argArray) { - } + } + + /** + * Invoke all the appenders of this logger. + * + * @param event + * The event to log + */ + public void callAppenders(ILoggingEvent event) { + int writes = 0; + + for (HLogger l = this; l != null; l = l.parent) { + // Protected against simultaneous call to addAppender, removeAppender,... + synchronized (l) { + if (l.appenderList != null) { + writes += l.appendLoopOnAppenders(event); + } + if (!l.additive) { + break; + } + } + } + + // No appenders in hierarchy, warn user only once. + // if(!hierarchy.emittedNoAppenderWarning && writes == 0) { + // LogLog.error("No appenders could be found for category (" + + // this.getName() + ")."); + // LogLog.error("Please initialize the log4j system properly."); + // hierarchy.emittedNoAppenderWarning = true; + // } + } + + private int appendLoopOnAppenders(ILoggingEvent event) { + int size = 0; + Appender appender; + + if (appenderList != null) { + size = appenderList.size(); + for (int i = 0; i < size; i++) { + appender = appenderList.get(i); + appender.doAppend(event); + } + } + return size; + } + + /** + * Remove the appender passed as parameter form the list of appenders. + */ + public synchronized void removeAppender(Appender appender) { + if ((appender == null) || (appenderList == null)) { + } + appenderList.remove(appender); + } + + /** + * Create a child of this logger by suffix, that is, the part of the name + * extending this logger. For example, if this logger is named "x.y" and the + * lastPart is "z", then the created child logger will be named "x.y.z". + * + *

+ * IMPORTANT: Calls to this method must be within a syncronized block on this + * logger. + * + * @param lastPart + * the suffix (i.e. last part) of the child logger name. This + * parameter may not include dots, i.e. the logger separator + * character. + * @return + */ + HLogger createChildByLastNamePart(final String lastPart) { + int i_index = lastPart.indexOf(CoreConstants.DOT); + if (i_index != -1) { + throw new IllegalArgumentException("Child name [" + lastPart + " passed as parameter, may not include [" + CoreConstants.DOT + "]"); + } + + if (childrenMap == null) { + childrenMap = new HashMap(2); + } + HLogger childHLogger; + if (this.isRootLogger()) { + childHLogger = new HLogger(lastPart, this); + } else { + childHLogger = new HLogger(name + CoreConstants.DOT + lastPart, this); + } + childrenMap.put(lastPart, childHLogger); + childHLogger.effectiveLevel = this.effectiveLevel; + return childHLogger; + } + + public final void trace(String msg) { + if (effectiveLevel.levelInt <= Level.TRACE_INT) { + throw new UnsupportedOperationException("not yet implemented"); + } + } + + public void trace(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void trace(Object parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void trace(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public final void debug(String msg) { + if (effectiveLevel.levelInt <= Level.DEBUG_INT) { + throw new UnsupportedOperationException("not yet implemented"); + } + } + + public void debug(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void debug(Object parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void debug(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void error(String msg) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void error(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void error(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void error(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void info(String msg) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void info(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void info(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void info(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public boolean isTraceEnabled() { + return false; + } + + public boolean isDebugEnabled() { + return false; + } + + public boolean isErrorEnabled() { + return false; // To change body of implemented methods use File | Settings | + // File Templates. + } + + public boolean isInfoEnabled() { + return false; // To change body of implemented methods use File | Settings | + // File Templates. + } + + public boolean isWarnEnabled() { + return false; // To change body of implemented methods use File | Settings | + // File Templates. + } + + public void warn(String msg) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void warn(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void warn(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void warn(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File + // Templates. + } + + public void trace(String format, Object arg) { + } + + public void trace(String format, Object[] argArray) { + } + + public void debug(String format, Object arg) { + } + + public void debug(String format, Object[] argArray) { + } + + public void info(String format, Object[] argArray) { + } + + public void warn(String format, Object[] argArray) { + } + + public void error(String format, Object[] argArray) { + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/HLoggerContext.java b/logback-classic/src/test/java/ch/qos/logback/classic/HLoggerContext.java index 89d94ebf2cbb07b362a99e3fde4b99800669ac1c..5e0937b13035cc0250ebc0d994a2ad446b998180 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/HLoggerContext.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/HLoggerContext.java @@ -15,104 +15,103 @@ package ch.qos.logback.classic; import ch.qos.logback.classic.Level; - - /** * @author ceki */ public class HLoggerContext { - private HLogger root; - private int size; + private HLogger root; + private int size; - public HLoggerContext() { - this.root = new HLogger("root", null); - this.root.setLevel(Level.DEBUG); - size = 1; - } + public HLoggerContext() { + this.root = new HLogger("root", null); + this.root.setLevel(Level.DEBUG); + size = 1; + } - /** - * Return this contexts root logger - * - * @return - */ - public HLogger getRootLogger() { - return root; - } + /** + * Return this contexts root logger + * + * @return + */ + public HLogger getRootLogger() { + return root; + } - public HLogger getLogger(final String name) { + public HLogger getLogger(final String name) { - int i = 0; - HLogger HLogger = root; - HLogger childHLogger = null; - String childName; + int i = 0; + HLogger HLogger = root; + HLogger childHLogger = null; + String childName; - while (true) { - int h = name.indexOf('.', i); - if (h == -1) { - childName = name.substring(i); - } else { - childName = name.substring(i, h); - } - // move i left of the last point - i = h + 1; + while (true) { + int h = name.indexOf('.', i); + if (h == -1) { + childName = name.substring(i); + } else { + childName = name.substring(i, h); + } + // move i left of the last point + i = h + 1; - synchronized (HLogger) { - childHLogger = HLogger.getChildBySuffix(childName); - if (childHLogger == null) { - childHLogger = HLogger.createChildByLastNamePart(childName); - incSize(); + synchronized (HLogger) { + childHLogger = HLogger.getChildBySuffix(childName); + if (childHLogger == null) { + childHLogger = HLogger.createChildByLastNamePart(childName); + incSize(); + } + } + HLogger = childHLogger; + if (h == -1) { + return childHLogger; + } } - } - HLogger = childHLogger; - if (h == -1) { - return childHLogger; - } } - } - private synchronized void incSize() { - size++; - } + private synchronized void incSize() { + size++; + } + + int size() { + return size; + } - int size() { - return size; - } - /** - * Check if the named logger exists in the hierarchy. If so return - * its reference, otherwise returns null. - * - * @param name the name of the logger to search for. - */ - HLogger exists(String name) { - int i = 0; - HLogger HLogger = root; - HLogger childHLogger = null; - String childName; - while (true) { - int h = name.indexOf('.', i); - if (h == -1) { - childName = name.substring(i); - } else { - childName = name.substring(i, h); - } - // move i left of the last point - i = h + 1; + /** + * Check if the named logger exists in the hierarchy. If so return + * its reference, otherwise returns null. + * + * @param name the name of the logger to search for. + */ + HLogger exists(String name) { + int i = 0; + HLogger HLogger = root; + HLogger childHLogger = null; + String childName; + while (true) { + int h = name.indexOf('.', i); + if (h == -1) { + childName = name.substring(i); + } else { + childName = name.substring(i, h); + } + // move i left of the last point + i = h + 1; - synchronized (HLogger) { - childHLogger = HLogger.getChildBySuffix(childName); - if (childHLogger == null) { - return null; - } - } - HLogger = childHLogger; - if (h == -1) { - if (childHLogger.getName().equals(name)) { - return childHLogger; - } else { - return null; + synchronized (HLogger) { + childHLogger = HLogger.getChildBySuffix(childName); + if (childHLogger == null) { + return null; + } + } + HLogger = childHLogger; + if (h == -1) { + if (childHLogger.getName().equals(name)) { + return childHLogger; + } else { + return null; + } + } } - } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextDeadlockTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextDeadlockTest.java index 60760570d50f2bb7177c2578e2eed1df8894b690..ef79216b971c412855b9fe3b49ad052c80d340c5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextDeadlockTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextDeadlockTest.java @@ -24,51 +24,49 @@ import ch.qos.logback.core.joran.spi.JoranException; public class LoggerContextDeadlockTest { - LoggerContext loggerContext = new LoggerContext(); - JoranConfigurator jc = new JoranConfigurator(); - GetLoggerThread getLoggerThread = new GetLoggerThread(loggerContext); + LoggerContext loggerContext = new LoggerContext(); + JoranConfigurator jc = new JoranConfigurator(); + GetLoggerThread getLoggerThread = new GetLoggerThread(loggerContext); - @Before - public void setUp() throws Exception { - jc.setContext(loggerContext); - } - - @After - public void tearDown() throws Exception { - } + @Before + public void setUp() throws Exception { + jc.setContext(loggerContext); + } - @Test(timeout = 20000) - public void testLBCLASSIC_81() throws JoranException { + @After + public void tearDown() throws Exception { + } + @Test(timeout = 20000) + public void testLBCLASSIC_81() throws JoranException { - getLoggerThread.start(); - for (int i = 0; i < 500; i++) { - ByteArrayInputStream baos = new ByteArrayInputStream( - "".getBytes()); - jc.doConfigure(baos); + getLoggerThread.start(); + for (int i = 0; i < 500; i++) { + ByteArrayInputStream baos = new ByteArrayInputStream("".getBytes()); + jc.doConfigure(baos); + } } - } - class GetLoggerThread extends Thread { + class GetLoggerThread extends Thread { - final LoggerContext loggerContext; + final LoggerContext loggerContext; - GetLoggerThread(LoggerContext loggerContext) { - this.loggerContext = loggerContext; - } + GetLoggerThread(LoggerContext loggerContext) { + this.loggerContext = loggerContext; + } - @Override - public void run() { - for (int i = 0; i < 10000; i++) { - if (i % 100 == 0) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - } + @Override + public void run() { + for (int i = 0; i < 10000; i++) { + if (i % 100 == 0) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + } + } + loggerContext.getLogger("a" + i); + } } - loggerContext.getLogger("a" + i); - } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextPerfTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextPerfTest.java index 99e513dfe053e9cab750e7a956d420fbb29ebdbe..e7ca85eba801dff7f494af8ad8a07e4673758c32 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextPerfTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerContextPerfTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic; - import ch.qos.logback.classic.corpus.CorpusModel; import ch.qos.logback.core.contention.*; import org.junit.Before; @@ -24,68 +23,69 @@ import static org.junit.Assert.fail; public class LoggerContextPerfTest { - static int THREAD_COUNT = 10000; - int totalTestDuration = 4000; + static int THREAD_COUNT = 10000; + int totalTestDuration = 4000; + + LoggerContext loggerContext = new LoggerContext(); + + ThreadedThroughputCalculator harness = new ThreadedThroughputCalculator(totalTestDuration); + RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); + + CorpusModel corpusMaker; + + @Before + public void setUp() throws Exception { + } + + private RunnableWithCounterAndDone[] buildRunnableArray() { + RunnableWithCounterAndDone[] runnableArray = new RunnableWithCounterAndDone[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + runnableArray[i] = new GetLoggerRunnable(); + } + return runnableArray; + } - LoggerContext loggerContext = new LoggerContext(); + // Results computed on a Intel i7 + // 1 thread + // 13'107 ops per milli using Hashtable for LoggerContext.loggerCache + // 15'258 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - ThreadedThroughputCalculator harness = new ThreadedThroughputCalculator(totalTestDuration); - RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); + // 10 threads + // 8'468 ops per milli using Hashtable for LoggerContext.loggerCache + // 58'945 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - CorpusModel corpusMaker; + // 100 threads + // 8'863 ops per milli using Hashtable for LoggerContext.loggerCache + // 34'810 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - @Before - public void setUp() throws Exception { - } + // 1'000 threads + // 8'188 ops per milli using Hashtable for LoggerContext.loggerCache + // 24'012 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - private RunnableWithCounterAndDone[] buildRunnableArray() { - RunnableWithCounterAndDone[] runnableArray = new RunnableWithCounterAndDone[THREAD_COUNT]; - for(int i = 0; i < THREAD_COUNT; i++) { - runnableArray[i] = new GetLoggerRunnable(); + // 10'000 threads + // 7'595 ops per milli using Hashtable for LoggerContext.loggerCache + // 8'989 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache + + @Test + public void computeResults() throws InterruptedException { + harness.execute(runnableArray); + harness.printThroughput("getLogger performance: ", true); } - return runnableArray; - } - - // Results computed on a Intel i7 - // 1 thread - // 13'107 ops per milli using Hashtable for LoggerContext.loggerCache - // 15'258 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - - // 10 threads - // 8'468 ops per milli using Hashtable for LoggerContext.loggerCache - // 58'945 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - - // 100 threads - // 8'863 ops per milli using Hashtable for LoggerContext.loggerCache - // 34'810 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - - // 1'000 threads - // 8'188 ops per milli using Hashtable for LoggerContext.loggerCache - // 24'012 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - - // 10'000 threads - // 7'595 ops per milli using Hashtable for LoggerContext.loggerCache - // 8'989 ops per milli using ConcurrentHashMap for LoggerContext.loggerCache - - @Test - public void computeResults() throws InterruptedException { - harness.execute(runnableArray); - harness.printThroughput("getLogger performance: ", true); - } - - private class GetLoggerRunnable extends RunnableWithCounterAndDone { - - final int burstLength = 3; - public void run() { - while (!isDone()) { - long i = counter % burstLength; - - loggerContext.getLogger("a"+i); - counter++; - if(i == 0) { - Thread.yield(); + + private class GetLoggerRunnable extends RunnableWithCounterAndDone { + + final int burstLength = 3; + + public void run() { + while (!isDone()) { + long i = counter % burstLength; + + loggerContext.getLogger("a" + i); + counter++; + if (i == 0) { + Thread.yield(); + } + } } - } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerMessageFormattingTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerMessageFormattingTest.java index f2f8c0068ff4feb9fb11e623dc8aae797d93fc9a..dbc69a8032d0f90e080afe96c7adca53d03afd0e 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerMessageFormattingTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerMessageFormattingTest.java @@ -23,64 +23,62 @@ import ch.qos.logback.core.read.ListAppender; public class LoggerMessageFormattingTest { - LoggerContext lc; - ListAppender listAppender; + LoggerContext lc; + ListAppender listAppender; - @Before - public void setUp() { - lc = new LoggerContext(); - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - listAppender = new ListAppender(); - listAppender.setContext(lc); - listAppender.start(); - logger.addAppender(listAppender); - } + @Before + public void setUp() { + lc = new LoggerContext(); + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + listAppender = new ListAppender(); + listAppender.setContext(lc); + listAppender.start(); + logger.addAppender(listAppender); + } - @Test - public void testFormattingOneArg() { - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - logger.debug("{}", new Integer(12)); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals("12", event.getFormattedMessage()); - } + @Test + public void testFormattingOneArg() { + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + logger.debug("{}", new Integer(12)); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals("12", event.getFormattedMessage()); + } - @Test - public void testFormattingTwoArg() { - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - logger.debug("{}-{}", new Integer(12), new Integer(13)); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals("12-13", event.getFormattedMessage()); - } + @Test + public void testFormattingTwoArg() { + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + logger.debug("{}-{}", new Integer(12), new Integer(13)); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals("12-13", event.getFormattedMessage()); + } - @Test - public void testNoFormatting() { - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - logger.debug("test", new Integer(12), new Integer(13)); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals("test", event.getFormattedMessage()); - } - - @Test - public void testNoFormatting2() { - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - logger.debug("test"); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals("test", event.getFormattedMessage()); - } - - @Test - public void testMessageConverter() { - Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - logger.debug("{}", 12); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - PatternLayout layout = new PatternLayout(); - layout.setContext(lc); - layout.setPattern("%m"); - layout.start(); - String formattedMessage = layout.doLayout(event); - assertEquals("12", formattedMessage); - } + @Test + public void testNoFormatting() { + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + logger.debug("test", new Integer(12), new Integer(13)); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals("test", event.getFormattedMessage()); + } + @Test + public void testNoFormatting2() { + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + logger.debug("test"); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals("test", event.getFormattedMessage()); + } + @Test + public void testMessageConverter() { + Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + logger.debug("{}", 12); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + PatternLayout layout = new PatternLayout(); + layout.setContext(lc); + layout.setPattern("%m"); + layout.start(); + String formattedMessage = layout.doLayout(event); + assertEquals("12", formattedMessage); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerPerfTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerPerfTest.java index dd5fcd806b955a7c1f7713d580bae69cd3d0c5d2..86ca2103a1c88ca862ac8efe8873a87fc5acb579 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerPerfTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerPerfTest.java @@ -27,235 +27,225 @@ import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.UnsynchronizedAppenderBase; import ch.qos.logback.core.helpers.NOPAppender; - @Ignore public class LoggerPerfTest { - static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; - static long NORMAL_RUN_LENGTH = 1 * 1000 * 1000; - static long SHORTENED_RUN_LENGTH = 500 * 1000; - - LoggerContext lc = new LoggerContext(); - Logger lbLogger = lc.getLogger(this.getClass()); - org.slf4j.Logger logger = lbLogger; - - @Before - public void setUp() throws Exception { - } - - // =========================================================================== - @Test - public void durationOfDisabledLogsWith_1_NOPFilter() { - double avg = computeDurationOfDisabledLogsWith_1_NOPFilter(1, - NORMAL_RUN_LENGTH); - System.out.println("durationOfDisabledLogsWith_1_NOPFilter=" + avg); - long referencePerf = 60; - - BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); - } - - double computeDurationOfDisabledLogsWith_1_NOPFilter(int numOfFilters, - long len) { - for (int i = 0; i < numOfFilters; i++) { - lc.addTurboFilter(new NOPTurboFilter()); + static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; + static long NORMAL_RUN_LENGTH = 1 * 1000 * 1000; + static long SHORTENED_RUN_LENGTH = 500 * 1000; + + LoggerContext lc = new LoggerContext(); + Logger lbLogger = lc.getLogger(this.getClass()); + org.slf4j.Logger logger = lbLogger; + + @Before + public void setUp() throws Exception { } - lbLogger.setLevel(Level.OFF); - for (long i = 0; i < len; i++) - logger.debug("Toto"); - - long start = System.nanoTime(); - for (long i = 0; i < len; i++) - logger.debug("Toto"); - - return (System.nanoTime() - start) / len; - } - - // =========================================================================== - @Test - public void durationOfIsDebugEnabled() { - double avg = computedurationOfIsDebugEnabled(10 * NORMAL_RUN_LENGTH); - System.out.println("durationOfIsDebugEnabled=" + avg); - - long referencePerf = 15; - BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); - } - - double computedurationOfIsDebugEnabled(final long len) { - lbLogger.setLevel(Level.OFF); - for (long i = 0; i < len; i++) - logger.isDebugEnabled(); - Thread.yield(); - for (long i = 0; i < len; i++) - logger.isDebugEnabled(); - - long start = System.nanoTime(); - for (long i = 0; i < len; i++) - logger.isDebugEnabled(); - return (System.nanoTime() - start) / len; - } - - // =========================================================================== - @Test - public void durationOfDisabledLog_NoParameters() { - double avg = computeDurationOfDisabledLog_NoParameters(10 * NORMAL_RUN_LENGTH); - System.out.println("durationOfDisabledLog_NoParameters=" + avg); - - long referencePerf = 18; - BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); - } - - double computeDurationOfDisabledLog_NoParameters(final long len) { - lbLogger.setLevel(Level.OFF); - for (long i = 0; i < len; i++) - logger.debug("Toto"); - Thread.yield(); - for (long i = 0; i < len; i++) - logger.debug("Toto"); - Thread.yield(); - - long start = System.nanoTime(); - for (long i = 0; i < len; i++) - logger.debug("Toto"); - return (System.nanoTime() - start) / len; - } - - // =========================================================================== - - @Test - public void durationOfDisabledLog_1_Parameter() { - double avgDuration = computeDurationOfDisabledLog_1_Parameter(NORMAL_RUN_LENGTH); - System.out.println("durationOfDisabledLog_1_Parameter=" + avgDuration); - - long referencePerf = 30; - BogoPerf.assertDuration(avgDuration, referencePerf, - CoreConstants.REFERENCE_BIPS); - } - - double computeDurationOfDisabledLog_1_Parameter(long len) { - lbLogger.setLevel(Level.OFF); - final Object o = new Object(); - for (long i = 0; i < len; i++) - logger.debug("Toto {}", o); - - long start = System.nanoTime(); - for (long i = 0; i < len; i++) - logger.debug("Toto {}", o); - - long end = System.nanoTime(); - return (end - start) / len; - } - - // =========================================================================== - - @Test - public void durationOfEnabledLog() { - if (EnvUtilForTests.isLinux()) { - // the JIT on Linux behaves very differently - return; + + // =========================================================================== + @Test + public void durationOfDisabledLogsWith_1_NOPFilter() { + double avg = computeDurationOfDisabledLogsWith_1_NOPFilter(1, NORMAL_RUN_LENGTH); + System.out.println("durationOfDisabledLogsWith_1_NOPFilter=" + avg); + long referencePerf = 60; + + BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); } - double avgDuration = computeDurationOfEnabledLog(SHORTENED_RUN_LENGTH); - System.out.println("durationOfEnabledLog=" + avgDuration); - - long referencePerf = 800; - BogoPerf.assertDuration(avgDuration, referencePerf, - CoreConstants.REFERENCE_BIPS); - } - - double computeDurationOfEnabledLog(long len) { - lbLogger.setLevel(Level.ALL); - - NOPAppender nopAppender = new NOPAppender(); - nopAppender.start(); - ((ch.qos.logback.classic.Logger) logger).addAppender(nopAppender); - for (long i = 0; i < len; i++) { - logger.debug("Toto"); + + double computeDurationOfDisabledLogsWith_1_NOPFilter(int numOfFilters, long len) { + for (int i = 0; i < numOfFilters; i++) { + lc.addTurboFilter(new NOPTurboFilter()); + } + lbLogger.setLevel(Level.OFF); + for (long i = 0; i < len; i++) + logger.debug("Toto"); + + long start = System.nanoTime(); + for (long i = 0; i < len; i++) + logger.debug("Toto"); + + return (System.nanoTime() - start) / len; + } + + // =========================================================================== + @Test + public void durationOfIsDebugEnabled() { + double avg = computedurationOfIsDebugEnabled(10 * NORMAL_RUN_LENGTH); + System.out.println("durationOfIsDebugEnabled=" + avg); + + long referencePerf = 15; + BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); + } + + double computedurationOfIsDebugEnabled(final long len) { + lbLogger.setLevel(Level.OFF); + for (long i = 0; i < len; i++) + logger.isDebugEnabled(); + Thread.yield(); + for (long i = 0; i < len; i++) + logger.isDebugEnabled(); + + long start = System.nanoTime(); + for (long i = 0; i < len; i++) + logger.isDebugEnabled(); + return (System.nanoTime() - start) / len; } - long start = System.nanoTime(); - for (long i = 0; i < len; i++) { - logger.debug("Toto"); + + // =========================================================================== + @Test + public void durationOfDisabledLog_NoParameters() { + double avg = computeDurationOfDisabledLog_NoParameters(10 * NORMAL_RUN_LENGTH); + System.out.println("durationOfDisabledLog_NoParameters=" + avg); + + long referencePerf = 18; + BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); } - long end = System.nanoTime(); - return (end - start) / len; - } - - // =========================================================================== - - @Test - public void testThreadedLogging() throws InterruptedException { - SleepAppender appender = new SleepAppender(); - - int MILLIS_PER_CALL = 250; - int NANOS_PER_CALL = 250 * 1000 * 1000; - - appender.setDuration(MILLIS_PER_CALL); - appender.start(); - - lbLogger.addAppender(appender); - lbLogger.setLevel(Level.DEBUG); - long start; - long end; - int threadCount = 10; - int iterCount = 5; - TestRunner[] threads = new TestRunner[threadCount]; - for (int i = 0; i < threads.length; ++i) { - threads[i] = new TestRunner(logger, iterCount); + + double computeDurationOfDisabledLog_NoParameters(final long len) { + lbLogger.setLevel(Level.OFF); + for (long i = 0; i < len; i++) + logger.debug("Toto"); + Thread.yield(); + for (long i = 0; i < len; i++) + logger.debug("Toto"); + Thread.yield(); + + long start = System.nanoTime(); + for (long i = 0; i < len; i++) + logger.debug("Toto"); + return (System.nanoTime() - start) / len; } - start = System.nanoTime(); - for (Thread thread : threads) { - thread.start(); + + // =========================================================================== + + @Test + public void durationOfDisabledLog_1_Parameter() { + double avgDuration = computeDurationOfDisabledLog_1_Parameter(NORMAL_RUN_LENGTH); + System.out.println("durationOfDisabledLog_1_Parameter=" + avgDuration); + + long referencePerf = 30; + BogoPerf.assertDuration(avgDuration, referencePerf, CoreConstants.REFERENCE_BIPS); } - for (TestRunner thread : threads) { - thread.join(); + + double computeDurationOfDisabledLog_1_Parameter(long len) { + lbLogger.setLevel(Level.OFF); + final Object o = new Object(); + for (long i = 0; i < len; i++) + logger.debug("Toto {}", o); + + long start = System.nanoTime(); + for (long i = 0; i < len; i++) + logger.debug("Toto {}", o); + + long end = System.nanoTime(); + return (end - start) / len; } - end = System.nanoTime(); - double tolerance = threadCount * .125; // Very little thread contention - // should occur in this test. - double max = ((((double) NANOS_PER_CALL) / NANOS_IN_ONE_SEC) * iterCount) - * tolerance; - double serialized = (((double) NANOS_PER_CALL) / NANOS_IN_ONE_SEC) - * iterCount * threadCount; - double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; - System.out - .printf( - "Sleep duration: %,.4f seconds. Max expected: %,.4f seconds, Serialized: %,.4f\n", - actual, max, serialized); - assertTrue("Exceeded maximum expected time.", actual < max); - } - - // ============================================================ - private static class TestRunner extends Thread { - private org.slf4j.Logger logger; - private long len; - - public TestRunner(org.slf4j.Logger logger, long len) { - this.logger = logger; - this.len = len; + + // =========================================================================== + + @Test + public void durationOfEnabledLog() { + if (EnvUtilForTests.isLinux()) { + // the JIT on Linux behaves very differently + return; + } + double avgDuration = computeDurationOfEnabledLog(SHORTENED_RUN_LENGTH); + System.out.println("durationOfEnabledLog=" + avgDuration); + + long referencePerf = 800; + BogoPerf.assertDuration(avgDuration, referencePerf, CoreConstants.REFERENCE_BIPS); } - public void run() { - Thread.yield(); - for (long i = 0; i < len; i++) { - logger.debug("Toto"); - } + double computeDurationOfEnabledLog(long len) { + lbLogger.setLevel(Level.ALL); + + NOPAppender nopAppender = new NOPAppender(); + nopAppender.start(); + ((ch.qos.logback.classic.Logger) logger).addAppender(nopAppender); + for (long i = 0; i < len; i++) { + logger.debug("Toto"); + } + long start = System.nanoTime(); + for (long i = 0; i < len; i++) { + logger.debug("Toto"); + } + long end = System.nanoTime(); + return (end - start) / len; } - } - // ============================================================ - public static class SleepAppender extends UnsynchronizedAppenderBase { - private static long duration = 500; + // =========================================================================== + + @Test + public void testThreadedLogging() throws InterruptedException { + SleepAppender appender = new SleepAppender(); + + int MILLIS_PER_CALL = 250; + int NANOS_PER_CALL = 250 * 1000 * 1000; + + appender.setDuration(MILLIS_PER_CALL); + appender.start(); + + lbLogger.addAppender(appender); + lbLogger.setLevel(Level.DEBUG); + long start; + long end; + int threadCount = 10; + int iterCount = 5; + TestRunner[] threads = new TestRunner[threadCount]; + for (int i = 0; i < threads.length; ++i) { + threads[i] = new TestRunner(logger, iterCount); + } + start = System.nanoTime(); + for (Thread thread : threads) { + thread.start(); + } + for (TestRunner thread : threads) { + thread.join(); + } + end = System.nanoTime(); + double tolerance = threadCount * .125; // Very little thread contention + // should occur in this test. + double max = ((((double) NANOS_PER_CALL) / NANOS_IN_ONE_SEC) * iterCount) * tolerance; + double serialized = (((double) NANOS_PER_CALL) / NANOS_IN_ONE_SEC) * iterCount * threadCount; + double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; + System.out.printf("Sleep duration: %,.4f seconds. Max expected: %,.4f seconds, Serialized: %,.4f\n", actual, max, serialized); + assertTrue("Exceeded maximum expected time.", actual < max); + } - public void setDuration(long millis) { - duration = millis; + // ============================================================ + private static class TestRunner extends Thread { + private org.slf4j.Logger logger; + private long len; + + public TestRunner(org.slf4j.Logger logger, long len) { + this.logger = logger; + this.len = len; + } + + public void run() { + Thread.yield(); + for (long i = 0; i < len; i++) { + logger.debug("Toto"); + } + } } - @Override - protected void append(E eventObject) { - try { - Thread.sleep(duration); - } catch (InterruptedException ie) { - // Ignore - } + // ============================================================ + public static class SleepAppender extends UnsynchronizedAppenderBase { + private static long duration = 500; + + public void setDuration(long millis) { + duration = millis; + } + + @Override + protected void append(E eventObject) { + try { + Thread.sleep(duration); + } catch (InterruptedException ie) { + // Ignore + } + } } - } - // ============================================================ + // ============================================================ } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerSerializationTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerSerializationTest.java index 82145ab66a4d409a208e881c1c3152d181f33407..ec6cb01d71bfd157ec4e338c529de89a31f19e02 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerSerializationTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerSerializationTest.java @@ -26,129 +26,129 @@ import static org.junit.Assert.assertTrue; public class LoggerSerializationTest { - static final String SERIALIZATION_PREFIX = CoreTestConstants.TEST_INPUT_PREFIX+"/serialization/"; - - // force SLF4J initialization for subsequent Logger readResolce ooperaiton - org.slf4j.Logger unused = LoggerFactory.getLogger(this.getClass()); - LoggerContext lc; - Logger logger; - - ByteArrayOutputStream bos; - ObjectOutputStream oos; - ObjectInputStream inputStream; - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName("testContext"); - logger = lc.getLogger(LoggerSerializationTest.class); - // create the byte output stream - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - } - - @After - public void tearDown() throws Exception { - lc = null; - logger = null; - } - - @Test - public void basicSerialization() throws IOException, ClassNotFoundException { - Foo foo = new Foo(logger); - foo.doFoo(); - Foo fooBack = writeAndRead(foo); - fooBack.doFoo(); - } - - @Test - public void deepTreeSerialization() throws IOException { - // crate a tree of loggers under "aaaaaaaa" - Logger a = lc.getLogger("aaaaaaaa"); - lc.getLogger("aaaaaaaa.a"); - lc.getLogger("aaaaaaaa.a.a"); - lc.getLogger("aaaaaaaa.a.b"); - lc.getLogger("aaaaaaaa.a.c"); - lc.getLogger("aaaaaaaa.a.d"); - - lc.getLogger("aaaaaaaa.b"); - lc.getLogger("aaaaaaaa.b.a"); - lc.getLogger("aaaaaaaa.b.b"); - lc.getLogger("aaaaaaaa.b.c"); - lc.getLogger("aaaaaaaa.b.d"); - - lc.getLogger("aaaaaaaa.c"); - lc.getLogger("aaaaaaaa.c.a"); - lc.getLogger("aaaaaaaa.c.b"); - lc.getLogger("aaaaaaaa.c.c"); - lc.getLogger("aaaaaaaa.c.d"); - - lc.getLogger("aaaaaaaa.d"); - lc.getLogger("aaaaaaaa.d.a"); - lc.getLogger("aaaaaaaa.d.b"); - lc.getLogger("aaaaaaaa.d.c"); - lc.getLogger("aaaaaaaa.d.d"); - - Logger b = lc.getLogger("b"); - - writeObject(oos, a); - oos.close(); - int sizeA = bos.size(); - - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - - writeObject(oos, b); - oos.close(); - int sizeB = bos.size(); - - assertTrue("serialized logger should be less than 100 bytes", sizeA < 100); - // logger tree should not influnce serialization - assertTrue("serialized loggers should be nearly the same size a:" + sizeA + ", sizeB:" + sizeB, (sizeA - sizeB) < 10); - } - - private Foo writeAndRead(Foo foo) throws IOException, - ClassNotFoundException { - writeObject(oos, foo); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - inputStream = new ObjectInputStream(bis); - Foo fooBack = readFooObject(inputStream); - inputStream.close(); - return fooBack; - } - - Foo readFooObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { - return (Foo) readObject(inputStream); - } - private Object readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { - return inputStream.readObject(); - } - - private void writeObject(ObjectOutputStream oos, Object o) throws IOException { - oos.writeObject(o); - oos.flush(); - oos.close(); - } - - @Test - public void testCompatibilityWith_v1_0_11 () throws IOException, ClassNotFoundException { - FileInputStream fis = new FileInputStream(SERIALIZATION_PREFIX+"logger_v1.0.11.ser"); - ObjectInputStream ois = new ObjectInputStream(fis); - Logger a = (Logger) ois.readObject(); - ois.close(); - assertEquals("a", a.getName()); - } - - // interestingly enough, logback 1.0.11 and earlier can also read loggers serialized by 1.0.12. - // fields not serialized are set to their default values and since the fields are not - // used, it works out nicely - @Test - public void testCompatibilityWith_v1_0_12 () throws IOException, ClassNotFoundException { - FileInputStream fis = new FileInputStream(SERIALIZATION_PREFIX+"logger_v1.0.12.ser"); - ObjectInputStream ois = new ObjectInputStream(fis); - Logger a = (Logger) ois.readObject(); - ois.close(); - assertEquals("a", a.getName()); - } + static final String SERIALIZATION_PREFIX = CoreTestConstants.TEST_INPUT_PREFIX + "/serialization/"; + + // force SLF4J initialization for subsequent Logger readResolce ooperaiton + org.slf4j.Logger unused = LoggerFactory.getLogger(this.getClass()); + LoggerContext lc; + Logger logger; + + ByteArrayOutputStream bos; + ObjectOutputStream oos; + ObjectInputStream inputStream; + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + lc.setName("testContext"); + logger = lc.getLogger(LoggerSerializationTest.class); + // create the byte output stream + bos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bos); + } + + @After + public void tearDown() throws Exception { + lc = null; + logger = null; + } + + @Test + public void basicSerialization() throws IOException, ClassNotFoundException { + Foo foo = new Foo(logger); + foo.doFoo(); + Foo fooBack = writeAndRead(foo); + fooBack.doFoo(); + } + + @Test + public void deepTreeSerialization() throws IOException { + // crate a tree of loggers under "aaaaaaaa" + Logger a = lc.getLogger("aaaaaaaa"); + lc.getLogger("aaaaaaaa.a"); + lc.getLogger("aaaaaaaa.a.a"); + lc.getLogger("aaaaaaaa.a.b"); + lc.getLogger("aaaaaaaa.a.c"); + lc.getLogger("aaaaaaaa.a.d"); + + lc.getLogger("aaaaaaaa.b"); + lc.getLogger("aaaaaaaa.b.a"); + lc.getLogger("aaaaaaaa.b.b"); + lc.getLogger("aaaaaaaa.b.c"); + lc.getLogger("aaaaaaaa.b.d"); + + lc.getLogger("aaaaaaaa.c"); + lc.getLogger("aaaaaaaa.c.a"); + lc.getLogger("aaaaaaaa.c.b"); + lc.getLogger("aaaaaaaa.c.c"); + lc.getLogger("aaaaaaaa.c.d"); + + lc.getLogger("aaaaaaaa.d"); + lc.getLogger("aaaaaaaa.d.a"); + lc.getLogger("aaaaaaaa.d.b"); + lc.getLogger("aaaaaaaa.d.c"); + lc.getLogger("aaaaaaaa.d.d"); + + Logger b = lc.getLogger("b"); + + writeObject(oos, a); + oos.close(); + int sizeA = bos.size(); + + bos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bos); + + writeObject(oos, b); + oos.close(); + int sizeB = bos.size(); + + assertTrue("serialized logger should be less than 100 bytes", sizeA < 100); + // logger tree should not influnce serialization + assertTrue("serialized loggers should be nearly the same size a:" + sizeA + ", sizeB:" + sizeB, (sizeA - sizeB) < 10); + } + + private Foo writeAndRead(Foo foo) throws IOException, ClassNotFoundException { + writeObject(oos, foo); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + inputStream = new ObjectInputStream(bis); + Foo fooBack = readFooObject(inputStream); + inputStream.close(); + return fooBack; + } + + Foo readFooObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { + return (Foo) readObject(inputStream); + } + + private Object readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException { + return inputStream.readObject(); + } + + private void writeObject(ObjectOutputStream oos, Object o) throws IOException { + oos.writeObject(o); + oos.flush(); + oos.close(); + } + + @Test + public void testCompatibilityWith_v1_0_11() throws IOException, ClassNotFoundException { + FileInputStream fis = new FileInputStream(SERIALIZATION_PREFIX + "logger_v1.0.11.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + Logger a = (Logger) ois.readObject(); + ois.close(); + assertEquals("a", a.getName()); + } + + // interestingly enough, logback 1.0.11 and earlier can also read loggers serialized by 1.0.12. + // fields not serialized are set to their default values and since the fields are not + // used, it works out nicely + @Test + public void testCompatibilityWith_v1_0_12() throws IOException, ClassNotFoundException { + FileInputStream fis = new FileInputStream(SERIALIZATION_PREFIX + "logger_v1.0.12.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + Logger a = (Logger) ois.readObject(); + ois.close(); + assertEquals("a", a.getName()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTest.java index c174bb1151f28306b61110874ea6eda24caf4d40..4b016cbd4e12f228b9586c509ddc4d7ed442df4a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTest.java @@ -30,198 +30,196 @@ import ch.qos.logback.core.status.Status; public class LoggerTest { - LoggerContext lc = new LoggerContext(); - Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - Logger loggerTest = lc.getLogger(LoggerTest.class); + LoggerContext lc = new LoggerContext(); + Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + Logger loggerTest = lc.getLogger(LoggerTest.class); - ListAppender listAppender = new ListAppender(); - - @Test - public void smoke() { ListAppender listAppender = new ListAppender(); - listAppender.start(); - root.addAppender(listAppender); - Logger logger = lc.getLogger(LoggerTest.class); - assertEquals(0, listAppender.list.size()); - logger.debug("hello"); - assertEquals(1, listAppender.list.size()); - } - - @Test - public void testNoStart() { - // listAppender.start(); - listAppender.setContext(lc); - root.addAppender(listAppender); - Logger logger = lc.getLogger(LoggerTest.class); - logger.debug("hello"); - - List statusList = lc.getStatusManager().getCopyOfStatusList(); - Status s0 = statusList.get(0); - assertEquals(Status.WARN, s0.getLevel()); - assertTrue(s0.getMessage().startsWith("Attempted to append to non started")); - } - - @Test - public void testAdditive() { - listAppender.start(); - root.addAppender(listAppender); - loggerTest.addAppender(listAppender); - loggerTest.setAdditive(false); - loggerTest.debug("hello"); - // 1 instead of two, since logger is not additive - assertEquals(1, listAppender.list.size()); - } - - @Test - public void testRootLogger() { - Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - LoggerContext lc = logger.getLoggerContext(); - - assertNotNull("Returned logger is null", logger); - assertEquals("Return logger isn't named root", logger.getName(), - Logger.ROOT_LOGGER_NAME); - assertTrue("logger instances should be indentical", logger == lc.root); - } - - @Test - public void testBasicFiltering() throws Exception { - listAppender.start(); - root.addAppender(listAppender); - root.setLevel(Level.INFO); - loggerTest.debug("x"); - assertEquals(0, listAppender.list.size()); - loggerTest.info("x"); - loggerTest.warn("x"); - loggerTest.error("x"); - assertEquals(3, listAppender.list.size()); - } - - void checkLevelThreshold(Logger logger, Level threshold) { - - if (Level.ERROR_INT >= threshold.levelInt) { - assertTrue(logger.isErrorEnabled()); - assertTrue(logger.isEnabledFor(Level.ERROR)); - } else { - assertFalse(logger.isErrorEnabled()); - assertFalse(logger.isEnabledFor(Level.ERROR)); - } - - if (Level.WARN_INT >= threshold.levelInt) { - assertTrue(logger.isWarnEnabled()); - assertTrue(logger.isEnabledFor(Level.WARN)); - } else { - assertFalse(logger.isWarnEnabled()); - assertFalse(logger.isEnabledFor(Level.WARN)); - } - if (Level.INFO_INT >= threshold.levelInt) { - assertTrue(logger.isInfoEnabled()); - assertTrue(logger.isEnabledFor(Level.INFO)); - } else { - assertFalse(logger.isInfoEnabled()); - assertFalse(logger.isEnabledFor(Level.INFO)); - } - if (Level.DEBUG_INT >= threshold.levelInt) { - assertTrue(logger.isDebugEnabled()); - assertTrue(logger.isEnabledFor(Level.DEBUG)); - } else { - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isEnabledFor(Level.DEBUG)); - } - if (Level.TRACE_INT >= threshold.levelInt) { - assertTrue(logger.isTraceEnabled()); - assertTrue(logger.isEnabledFor(Level.TRACE)); - } else { - assertFalse(logger.isTraceEnabled()); - assertFalse(logger.isEnabledFor(Level.TRACE)); - } - } - - @Test - public void innerClass_I() { - root.setLevel(Level.DEBUG); - Logger a = lc.getLogger("a"); - a.setLevel(Level.INFO); - Logger a_b = lc.getLogger("a$b"); - assertEquals(Level.INFO, a_b.getEffectiveLevel()); - } - - @Test - public void innerClass_II() { - root.setLevel(Level.DEBUG); - Logger a = lc.getLogger(this.getClass()); - a.setLevel(Level.INFO); - Logger a_b = lc.getLogger(new Inner().getClass()); - assertEquals(Level.INFO, a_b.getEffectiveLevel()); - } - - - class Inner { - } - - @Test - public void testEnabled_All() throws Exception { - root.setLevel(Level.ALL); - checkLevelThreshold(loggerTest, Level.ALL); - } - - @Test - public void testEnabled_Debug() throws Exception { - root.setLevel(Level.DEBUG); - checkLevelThreshold(loggerTest, Level.DEBUG); - } - - @Test - public void testEnabled_Info() throws Exception { - root.setLevel(Level.INFO); - checkLevelThreshold(loggerTest, Level.INFO); - } - - @Test - public void testEnabledX_Warn() throws Exception { - root.setLevel(Level.WARN); - checkLevelThreshold(loggerTest, Level.WARN); - } - - public void testEnabledX_Errror() throws Exception { - root.setLevel(Level.ERROR); - checkLevelThreshold(loggerTest, Level.ERROR); - } - - @Test - public void testEnabledX_Off() throws Exception { - root.setLevel(Level.OFF); - checkLevelThreshold(loggerTest, Level.OFF); - } - - @Test - public void setRootLevelToNull() { - try { - root.setLevel(null); - fail("The level of the root logger should not be settable to null"); - } catch (IllegalArgumentException e) { - } - } - - @Test - public void setLevelToNull_A() { - loggerTest.setLevel(null); - assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); - } - - @Test - public void setLevelToNull_B() { - loggerTest.setLevel(Level.DEBUG); - loggerTest.setLevel(null); - assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); - } - - @Test - public void setLevelToNull_LBCLASSIC_91() { - loggerTest.setLevel(Level.DEBUG); - ch.qos.logback.classic.Logger child = lc.getLogger(loggerTest.getName() + ".child"); - loggerTest.setLevel(null); - assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); - assertEquals(root.getEffectiveLevel(), child.getEffectiveLevel()); - } + + @Test + public void smoke() { + ListAppender listAppender = new ListAppender(); + listAppender.start(); + root.addAppender(listAppender); + Logger logger = lc.getLogger(LoggerTest.class); + assertEquals(0, listAppender.list.size()); + logger.debug("hello"); + assertEquals(1, listAppender.list.size()); + } + + @Test + public void testNoStart() { + // listAppender.start(); + listAppender.setContext(lc); + root.addAppender(listAppender); + Logger logger = lc.getLogger(LoggerTest.class); + logger.debug("hello"); + + List statusList = lc.getStatusManager().getCopyOfStatusList(); + Status s0 = statusList.get(0); + assertEquals(Status.WARN, s0.getLevel()); + assertTrue(s0.getMessage().startsWith("Attempted to append to non started")); + } + + @Test + public void testAdditive() { + listAppender.start(); + root.addAppender(listAppender); + loggerTest.addAppender(listAppender); + loggerTest.setAdditive(false); + loggerTest.debug("hello"); + // 1 instead of two, since logger is not additive + assertEquals(1, listAppender.list.size()); + } + + @Test + public void testRootLogger() { + Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + LoggerContext lc = logger.getLoggerContext(); + + assertNotNull("Returned logger is null", logger); + assertEquals("Return logger isn't named root", logger.getName(), Logger.ROOT_LOGGER_NAME); + assertTrue("logger instances should be indentical", logger == lc.root); + } + + @Test + public void testBasicFiltering() throws Exception { + listAppender.start(); + root.addAppender(listAppender); + root.setLevel(Level.INFO); + loggerTest.debug("x"); + assertEquals(0, listAppender.list.size()); + loggerTest.info("x"); + loggerTest.warn("x"); + loggerTest.error("x"); + assertEquals(3, listAppender.list.size()); + } + + void checkLevelThreshold(Logger logger, Level threshold) { + + if (Level.ERROR_INT >= threshold.levelInt) { + assertTrue(logger.isErrorEnabled()); + assertTrue(logger.isEnabledFor(Level.ERROR)); + } else { + assertFalse(logger.isErrorEnabled()); + assertFalse(logger.isEnabledFor(Level.ERROR)); + } + + if (Level.WARN_INT >= threshold.levelInt) { + assertTrue(logger.isWarnEnabled()); + assertTrue(logger.isEnabledFor(Level.WARN)); + } else { + assertFalse(logger.isWarnEnabled()); + assertFalse(logger.isEnabledFor(Level.WARN)); + } + if (Level.INFO_INT >= threshold.levelInt) { + assertTrue(logger.isInfoEnabled()); + assertTrue(logger.isEnabledFor(Level.INFO)); + } else { + assertFalse(logger.isInfoEnabled()); + assertFalse(logger.isEnabledFor(Level.INFO)); + } + if (Level.DEBUG_INT >= threshold.levelInt) { + assertTrue(logger.isDebugEnabled()); + assertTrue(logger.isEnabledFor(Level.DEBUG)); + } else { + assertFalse(logger.isDebugEnabled()); + assertFalse(logger.isEnabledFor(Level.DEBUG)); + } + if (Level.TRACE_INT >= threshold.levelInt) { + assertTrue(logger.isTraceEnabled()); + assertTrue(logger.isEnabledFor(Level.TRACE)); + } else { + assertFalse(logger.isTraceEnabled()); + assertFalse(logger.isEnabledFor(Level.TRACE)); + } + } + + @Test + public void innerClass_I() { + root.setLevel(Level.DEBUG); + Logger a = lc.getLogger("a"); + a.setLevel(Level.INFO); + Logger a_b = lc.getLogger("a$b"); + assertEquals(Level.INFO, a_b.getEffectiveLevel()); + } + + @Test + public void innerClass_II() { + root.setLevel(Level.DEBUG); + Logger a = lc.getLogger(this.getClass()); + a.setLevel(Level.INFO); + Logger a_b = lc.getLogger(new Inner().getClass()); + assertEquals(Level.INFO, a_b.getEffectiveLevel()); + } + + class Inner { + } + + @Test + public void testEnabled_All() throws Exception { + root.setLevel(Level.ALL); + checkLevelThreshold(loggerTest, Level.ALL); + } + + @Test + public void testEnabled_Debug() throws Exception { + root.setLevel(Level.DEBUG); + checkLevelThreshold(loggerTest, Level.DEBUG); + } + + @Test + public void testEnabled_Info() throws Exception { + root.setLevel(Level.INFO); + checkLevelThreshold(loggerTest, Level.INFO); + } + + @Test + public void testEnabledX_Warn() throws Exception { + root.setLevel(Level.WARN); + checkLevelThreshold(loggerTest, Level.WARN); + } + + public void testEnabledX_Errror() throws Exception { + root.setLevel(Level.ERROR); + checkLevelThreshold(loggerTest, Level.ERROR); + } + + @Test + public void testEnabledX_Off() throws Exception { + root.setLevel(Level.OFF); + checkLevelThreshold(loggerTest, Level.OFF); + } + + @Test + public void setRootLevelToNull() { + try { + root.setLevel(null); + fail("The level of the root logger should not be settable to null"); + } catch (IllegalArgumentException e) { + } + } + + @Test + public void setLevelToNull_A() { + loggerTest.setLevel(null); + assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); + } + + @Test + public void setLevelToNull_B() { + loggerTest.setLevel(Level.DEBUG); + loggerTest.setLevel(null); + assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); + } + + @Test + public void setLevelToNull_LBCLASSIC_91() { + loggerTest.setLevel(Level.DEBUG); + ch.qos.logback.classic.Logger child = lc.getLogger(loggerTest.getName() + ".child"); + loggerTest.setLevel(null); + assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel()); + assertEquals(root.getEffectiveLevel(), child.getEffectiveLevel()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTestHelper.java b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTestHelper.java index 7dab6a74952866075d5058970e1ce79628c46a5a..b46a06143bcfaa6aa9165f959a59a04b62e2a2d9 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTestHelper.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/LoggerTestHelper.java @@ -19,17 +19,17 @@ import junit.framework.*; public class LoggerTestHelper extends TestCase { + static void assertNameEquals(Logger logger, String name) { + assertNotNull(logger); + assertEquals(name, logger.getName()); + } - static void assertNameEquals(Logger logger, String name) { - assertNotNull(logger); - assertEquals(name, logger.getName()); - } - static void assertLevels(Level level, Logger logger, Level effectiveLevel) { - if(level == null) { - assertNull(logger.getLevel()); - } else { - assertEquals(level, logger.getLevel()); + static void assertLevels(Level level, Logger logger, Level effectiveLevel) { + if (level == null) { + assertNull(logger.getLevel()); + } else { + assertEquals(level, logger.getLevel()); + } + assertEquals(effectiveLevel, logger.getEffectiveLevel()); } - assertEquals(effectiveLevel, logger.getEffectiveLevel()); - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/MDCTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/MDCTest.java index 4e37d21b4aa903ae68f649cbb5b769b074e573c0..ae453719788b6b508bc9948233c568de0f15bb49 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/MDCTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/MDCTest.java @@ -23,30 +23,30 @@ import org.slf4j.MDC; public class MDCTest { - @Test - public void test() throws InterruptedException { - MDCTestThread threadA = new MDCTestThread("a"); - threadA.start(); + @Test + public void test() throws InterruptedException { + MDCTestThread threadA = new MDCTestThread("a"); + threadA.start(); - MDCTestThread threadB = new MDCTestThread("b"); - threadB.start(); + MDCTestThread threadB = new MDCTestThread("b"); + threadB.start(); - threadA.join(); - threadB.join(); + threadA.join(); + threadB.join(); - assertNull(threadA.x0); - assertEquals("a", threadA.x1); - assertNull(threadA.x2); + assertNull(threadA.x0); + assertEquals("a", threadA.x1); + assertNull(threadA.x2); - assertNull(threadB.x0); - assertEquals("b", threadB.x1); - assertNull(threadB.x2); + assertNull(threadB.x0); + assertEquals("b", threadB.x1); + assertNull(threadB.x2); - } + } + + @Test + public void testLBCLASSIC_98() { + MDC.setContextMap(new HashMap()); + } - @Test - public void testLBCLASSIC_98() { - MDC.setContextMap(new HashMap()); - } - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/MDCTestThread.java b/logback-classic/src/test/java/ch/qos/logback/classic/MDCTestThread.java index f62c18931836a91b03c7d3eca5c2519e82fd0541..335111446bf1bb68246d6d587cc543b3c435de03 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/MDCTestThread.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/MDCTestThread.java @@ -16,24 +16,24 @@ package ch.qos.logback.classic; import org.slf4j.MDC; public class MDCTestThread extends Thread { - - String val; - - public MDCTestThread(String val) { - super(); - this.val = val; - } - - String x0; - String x1; - String x2; - - public void run() { - x0 = MDC.get("x"); - MDC.put("x", val); - x1 = MDC.get("x"); - MDC.clear(); - x2 = MDC.get("x"); - //System.out.println("Exiting "+val); - } -} \ No newline at end of file + + String val; + + public MDCTestThread(String val) { + super(); + this.val = val; + } + + String x0; + String x1; + String x2; + + public void run() { + x0 = MDC.get("x"); + MDC.put("x", val); + x1 = MDC.get("x"); + MDC.clear(); + x2 = MDC.get("x"); + // System.out.println("Exiting "+val); + } +} \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/PackageTest.java index 51af1315208feb89059c51d4a64d5b30e6ba8cf5..5773949d883000aa74cb351e911194f27d419633 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/PackageTest.java @@ -18,11 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({LoggerContextTest.class, LoggerPerfTest.class, - ScenarioBasedLoggerContextTest.class, PatternLayoutTest.class, - LoggerTest.class, LoggerSerializationTest.class, - LoggerMessageFormattingTest.class, MDCTest.class, - TurboFilteringInLoggerTest.class, - AsyncAppenderTest.class}) +@SuiteClasses({ LoggerContextTest.class, LoggerPerfTest.class, ScenarioBasedLoggerContextTest.class, PatternLayoutTest.class, LoggerTest.class, + LoggerSerializationTest.class, LoggerMessageFormattingTest.class, MDCTest.class, TurboFilteringInLoggerTest.class, AsyncAppenderTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/PatternLayoutTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/PatternLayoutTest.java index 2d2c0ba4413972a3bb5e6f3f859e8661f1d15c8c..85096be90db86b9ae5eeeb8d2138eb97363ce8b7 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/PatternLayoutTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/PatternLayoutTest.java @@ -35,190 +35,183 @@ import static org.junit.Assert.*; public class PatternLayoutTest extends AbstractPatternLayoutBaseTest { - private PatternLayout pl = new PatternLayout(); - private LoggerContext lc = new LoggerContext(); - Logger logger = lc.getLogger(ConverterTest.class); - Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - - ILoggingEvent le; - - public PatternLayoutTest() { - super(); - Exception ex = new Exception("Bogus exception"); - le = makeLoggingEvent(ex); - } - - @Before - public void setUp() { - pl.setContext(lc); - } - - ILoggingEvent makeLoggingEvent(Exception ex) { - return new LoggingEvent( - ch.qos.logback.core.pattern.FormattingConverter.class.getName(), - logger, Level.INFO, "Some message", ex, null); - } - - @Override - public ILoggingEvent getEventObject() { - return makeLoggingEvent(null); - } - - public PatternLayoutBase getPatternLayoutBase() { - return new PatternLayout(); - } - - @Test - public void testOK() { - pl.setPattern("%d %le [%t] %lo{30} - %m%n"); - pl.start(); - String val = pl.doLayout(getEventObject()); - // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some - // message - //2010-12-29 19:04:26,137 INFO [pool-1-thread-47] c.q.l.c.pattern.ConverterTest - Some message - String regex = ISO_REGEX + " INFO " + MAIN_REGEX - + " c.q.l.c.pattern.ConverterTest - Some message\\s*"; - - assertTrue("val="+val, val.matches(regex)); - } - - @Test - public void testNoExeptionHandler() { - pl.setPattern("%m%n"); - pl.start(); - String val = pl.doLayout(le); - assertTrue(val.contains("java.lang.Exception: Bogus exception")); - } - - @Test - public void testCompositePattern() { - pl.setPattern("%-56(%d %lo{20}) - %m%n"); - pl.start(); - String val = pl.doLayout(getEventObject()); - // 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message - String regex = ISO_REGEX - + " c.q.l.c.p.ConverterTest - Some message\\s*"; - assertTrue(val.matches(regex)); - } - - @Test - public void contextProperty() { - pl.setPattern("%property{a}"); - pl.start(); - lc.putProperty("a", "b"); - - String val = pl.doLayout(getEventObject()); - assertEquals("b", val); - } - - @Test - public void testNopExeptionHandler() { - pl.setPattern("%nopex %m%n"); - pl.start(); - String val = pl.doLayout(le); - assertTrue(!val.contains("java.lang.Exception: Bogus exception")); - } - - @Test - public void testWithParenthesis() { - pl.setPattern("\\(%msg:%msg\\) %msg"); - pl.start(); - le = makeLoggingEvent(null); - String val = pl.doLayout(le); - // System.out.println("VAL == " + val); - assertEquals("(Some message:Some message) Some message", val); - } - - @Test - public void testWithLettersComingFromLog4j() { - // Letters: p = level and c = logger - pl.setPattern("%d %p [%t] %c{30} - %m%n"); - pl.start(); - String val = pl.doLayout(getEventObject()); - // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some - // message - String regex = ClassicTestConstants.ISO_REGEX + " INFO " + MAIN_REGEX - + " c.q.l.c.pattern.ConverterTest - Some message\\s*"; - assertTrue(val.matches(regex)); - } - - @Test - public void mdcWithDefaultValue() { - String pattern = "%msg %mdc{foo} %mdc{bar:-[null]}"; - pl.setPattern(OptionHelper.substVars(pattern, lc)); - pl.start(); - MDC.put("foo", "foo"); - try { - String val = pl.doLayout(getEventObject()); - assertEquals("Some message foo [null]", val); - } finally { - MDC.remove("foo"); - } - } - - - @Test - public void contextNameTest() { - pl.setPattern("%contextName"); - lc.setName("aValue"); - pl.start(); - String val = pl.doLayout(getEventObject()); - assertEquals("aValue", val); - } - - @Test - public void cnTest() { - pl.setPattern("%cn"); - lc.setName("aValue"); - pl.start(); - String val = pl.doLayout(getEventObject()); - assertEquals("aValue", val); - } - - @Override - public Context getContext() { - return lc; - } - - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(lc); - jc.doConfigure(file); - } - - @Test - public void testConversionRuleSupportInPatternLayout() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "conversionRule/patternLayout0.xml"); - root.getAppender("LIST"); - String msg = "Simon says"; - logger.debug(msg); - StringListAppender sla = (StringListAppender) root.getAppender("LIST"); - assertNotNull(sla); - assertEquals(1, sla.strList.size()); - assertEquals(SampleConverter.SAMPLE_STR + " - " + msg, sla.strList.get(0)); - } - - @Test - public void somekeReplace() { - pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}"); - pl.start(); - StatusPrinter.print(lc); - String val = pl.doLayout(getEventObject()); - assertEquals("aXXXXb", val); - } - - @Test - public void replaceWithJoran() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "pattern/replace0.xml"); - StatusPrinter.print(lc); - root.getAppender("LIST"); - String msg = "And the number is 4111111111110000, expiring on 12/2010"; - logger.debug(msg); - StringListAppender sla = (StringListAppender) root.getAppender("LIST"); - assertNotNull(sla); - assertEquals(1, sla.strList.size()); - assertEquals("And the number is XXXX, expiring on 12/2010", sla.strList.get(0)); - } + private PatternLayout pl = new PatternLayout(); + private LoggerContext lc = new LoggerContext(); + Logger logger = lc.getLogger(ConverterTest.class); + Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + ILoggingEvent le; + + public PatternLayoutTest() { + super(); + Exception ex = new Exception("Bogus exception"); + le = makeLoggingEvent(ex); + } + + @Before + public void setUp() { + pl.setContext(lc); + } + + ILoggingEvent makeLoggingEvent(Exception ex) { + return new LoggingEvent(ch.qos.logback.core.pattern.FormattingConverter.class.getName(), logger, Level.INFO, "Some message", ex, null); + } + + @Override + public ILoggingEvent getEventObject() { + return makeLoggingEvent(null); + } + + public PatternLayoutBase getPatternLayoutBase() { + return new PatternLayout(); + } + + @Test + public void testOK() { + pl.setPattern("%d %le [%t] %lo{30} - %m%n"); + pl.start(); + String val = pl.doLayout(getEventObject()); + // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some + // message + // 2010-12-29 19:04:26,137 INFO [pool-1-thread-47] c.q.l.c.pattern.ConverterTest - Some message + String regex = ISO_REGEX + " INFO " + MAIN_REGEX + " c.q.l.c.pattern.ConverterTest - Some message\\s*"; + + assertTrue("val=" + val, val.matches(regex)); + } + + @Test + public void testNoExeptionHandler() { + pl.setPattern("%m%n"); + pl.start(); + String val = pl.doLayout(le); + assertTrue(val.contains("java.lang.Exception: Bogus exception")); + } + + @Test + public void testCompositePattern() { + pl.setPattern("%-56(%d %lo{20}) - %m%n"); + pl.start(); + String val = pl.doLayout(getEventObject()); + // 2008-03-18 21:55:54,250 c.q.l.c.pattern.ConverterTest - Some message + String regex = ISO_REGEX + " c.q.l.c.p.ConverterTest - Some message\\s*"; + assertTrue(val.matches(regex)); + } + + @Test + public void contextProperty() { + pl.setPattern("%property{a}"); + pl.start(); + lc.putProperty("a", "b"); + + String val = pl.doLayout(getEventObject()); + assertEquals("b", val); + } + + @Test + public void testNopExeptionHandler() { + pl.setPattern("%nopex %m%n"); + pl.start(); + String val = pl.doLayout(le); + assertTrue(!val.contains("java.lang.Exception: Bogus exception")); + } + + @Test + public void testWithParenthesis() { + pl.setPattern("\\(%msg:%msg\\) %msg"); + pl.start(); + le = makeLoggingEvent(null); + String val = pl.doLayout(le); + // System.out.println("VAL == " + val); + assertEquals("(Some message:Some message) Some message", val); + } + + @Test + public void testWithLettersComingFromLog4j() { + // Letters: p = level and c = logger + pl.setPattern("%d %p [%t] %c{30} - %m%n"); + pl.start(); + String val = pl.doLayout(getEventObject()); + // 2006-02-01 22:38:06,212 INFO [main] c.q.l.pattern.ConverterTest - Some + // message + String regex = ClassicTestConstants.ISO_REGEX + " INFO " + MAIN_REGEX + " c.q.l.c.pattern.ConverterTest - Some message\\s*"; + assertTrue(val.matches(regex)); + } + + @Test + public void mdcWithDefaultValue() { + String pattern = "%msg %mdc{foo} %mdc{bar:-[null]}"; + pl.setPattern(OptionHelper.substVars(pattern, lc)); + pl.start(); + MDC.put("foo", "foo"); + try { + String val = pl.doLayout(getEventObject()); + assertEquals("Some message foo [null]", val); + } finally { + MDC.remove("foo"); + } + } + + @Test + public void contextNameTest() { + pl.setPattern("%contextName"); + lc.setName("aValue"); + pl.start(); + String val = pl.doLayout(getEventObject()); + assertEquals("aValue", val); + } + + @Test + public void cnTest() { + pl.setPattern("%cn"); + lc.setName("aValue"); + pl.start(); + String val = pl.doLayout(getEventObject()); + assertEquals("aValue", val); + } + + @Override + public Context getContext() { + return lc; + } + + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(lc); + jc.doConfigure(file); + } + + @Test + public void testConversionRuleSupportInPatternLayout() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "conversionRule/patternLayout0.xml"); + root.getAppender("LIST"); + String msg = "Simon says"; + logger.debug(msg); + StringListAppender sla = (StringListAppender) root.getAppender("LIST"); + assertNotNull(sla); + assertEquals(1, sla.strList.size()); + assertEquals(SampleConverter.SAMPLE_STR + " - " + msg, sla.strList.get(0)); + } + + @Test + public void somekeReplace() { + pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}"); + pl.start(); + StatusPrinter.print(lc); + String val = pl.doLayout(getEventObject()); + assertEquals("aXXXXb", val); + } + + @Test + public void replaceWithJoran() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "pattern/replace0.xml"); + StatusPrinter.print(lc); + root.getAppender("LIST"); + String msg = "And the number is 4111111111110000, expiring on 12/2010"; + logger.debug(msg); + StringListAppender sla = (StringListAppender) root.getAppender("LIST"); + assertNotNull(sla); + assertEquals(1, sla.strList.size()); + assertEquals("And the number is XXXX, expiring on 12/2010", sla.strList.get(0)); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/ScenarioBasedLoggerContextTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/ScenarioBasedLoggerContextTest.java index 68fbfaa94720152e4c5cc5bf2c019a61152e7e4c..33f66db973c3c799cfa4f19eb55b578f3f701085 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/ScenarioBasedLoggerContextTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/ScenarioBasedLoggerContextTest.java @@ -30,86 +30,84 @@ import ch.qos.logback.classic.control.ScenarioMaker; import ch.qos.logback.classic.control.SetLevel; import ch.qos.logback.classic.control.Scenario; +public class ScenarioBasedLoggerContextTest { + LoggerContext lc; -public class ScenarioBasedLoggerContextTest { - LoggerContext lc; - - - @Test - public void testLen3() { - doScenarioedTest(3); - } - - @Test - public void testLength_30() { - doScenarioedTest(30); - } - - @Test - public void testLength_20000() { - doScenarioedTest(20*1000); - } - - @Test - @Ignore - public void testLengthLong() { - doScenarioedTest(100*1000); - } - - private void doScenarioedTest(int len) { - LoggerContext lc = new LoggerContext(); - ControlLoggerContext controlContext = new ControlLoggerContext(); - Scenario s = ScenarioMaker.makeRealisticCreationScenario(len); - List actionList = s.getActionList(); - int size = actionList.size(); - for (int i = 0; i < size; i++) { - ScenarioAction action = (ScenarioAction) actionList.get(i); - if (action instanceof CreateLogger) { - CreateLogger cl = (CreateLogger) action; - lc.getLogger(cl.getLoggerName()); - controlContext.getLogger(cl.getLoggerName()); - } else if (action instanceof SetLevel) { - SetLevel sl = (SetLevel) action; - Logger l = lc.getLogger(sl.getLoggerName()); - ControlLogger controlLogger = controlContext.getLogger(sl.getLoggerName()); - l.setLevel(sl.getLevel()); - controlLogger.setLevel(sl.getLevel()); - } + @Test + public void testLen3() { + doScenarioedTest(3); } - compareLoggerContexts(controlContext, lc); - } + @Test + public void testLength_30() { + doScenarioedTest(30); + } + + @Test + public void testLength_20000() { + doScenarioedTest(20 * 1000); + } + + @Test + @Ignore + public void testLengthLong() { + doScenarioedTest(100 * 1000); + } + + private void doScenarioedTest(int len) { + LoggerContext lc = new LoggerContext(); + ControlLoggerContext controlContext = new ControlLoggerContext(); + Scenario s = ScenarioMaker.makeRealisticCreationScenario(len); + List actionList = s.getActionList(); + int size = actionList.size(); + for (int i = 0; i < size; i++) { + ScenarioAction action = (ScenarioAction) actionList.get(i); + if (action instanceof CreateLogger) { + CreateLogger cl = (CreateLogger) action; + lc.getLogger(cl.getLoggerName()); + controlContext.getLogger(cl.getLoggerName()); + } else if (action instanceof SetLevel) { + SetLevel sl = (SetLevel) action; + Logger l = lc.getLogger(sl.getLoggerName()); + ControlLogger controlLogger = controlContext.getLogger(sl.getLoggerName()); + l.setLevel(sl.getLevel()); + controlLogger.setLevel(sl.getLevel()); + } + } + + compareLoggerContexts(controlContext, lc); + } + + void compareLoggerContexts(ControlLoggerContext controlLC, LoggerContext lc) { + Map controlLoggerMap = controlLC.getLoggerMap(); - void compareLoggerContexts(ControlLoggerContext controlLC, LoggerContext lc) { - Map controlLoggerMap = controlLC.getLoggerMap(); + assertEquals(controlLoggerMap.size() + 1, lc.size()); - assertEquals(controlLoggerMap.size()+1, lc.size()); + for (String loggerName : controlLoggerMap.keySet()) { - for (String loggerName: controlLoggerMap.keySet()) { - - Logger logger = lc.exists(loggerName); - ControlLogger controlLogger = (ControlLogger) controlLoggerMap.get(loggerName); - if (logger == null) { - throw new IllegalStateException("logger" + loggerName + " should exist"); - } - assertEquals(loggerName, logger.getName()); - assertEquals(loggerName, controlLogger.getName()); + Logger logger = lc.exists(loggerName); + ControlLogger controlLogger = (ControlLogger) controlLoggerMap.get(loggerName); + if (logger == null) { + throw new IllegalStateException("logger" + loggerName + " should exist"); + } + assertEquals(loggerName, logger.getName()); + assertEquals(loggerName, controlLogger.getName()); - compareLoggers(controlLogger, logger); + compareLoggers(controlLogger, logger); + } } - } - void compareLoggers(ControlLogger controlLogger, Logger logger) { - assertEquals(controlLogger.getName(), logger.getName()); - assertEquals(controlLogger.getEffectiveLevel(), logger.getEffectiveLevel()); + void compareLoggers(ControlLogger controlLogger, Logger logger) { + assertEquals(controlLogger.getName(), logger.getName()); + assertEquals(controlLogger.getEffectiveLevel(), logger.getEffectiveLevel()); - Level controlLevel = controlLogger.getLevel(); - Level level = logger.getLevel(); + Level controlLevel = controlLogger.getLevel(); + Level level = logger.getLevel(); - if (controlLevel == null) { - assertNull(level); - } else { - assertEquals(controlLevel, level); + if (controlLevel == null) { + assertNull(level); + } else { + assertEquals(controlLevel, level); + } } - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/TurboFilteringInLoggerTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/TurboFilteringInLoggerTest.java index 076af6b93d4aa7939bdb7d742cf2d1e8c4a6077d..775245de76d14aa87af7be1ccff2de50f583291f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/TurboFilteringInLoggerTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/TurboFilteringInLoggerTest.java @@ -27,157 +27,153 @@ import ch.qos.logback.classic.turbo.MarkerFilter; import ch.qos.logback.classic.turbo.TurboFilter; import ch.qos.logback.core.spi.FilterReply; - -public class TurboFilteringInLoggerTest { - - static final String BLUE = "BLUE"; - LoggerContext context; - Logger logger; - Marker blueMarker = MarkerFactory.getMarker(BLUE); - - @Before - public void setUp() throws Exception { - context = new LoggerContext(); - context.setName("test"); - context.start(); - logger = context.getLogger(TurboFilteringInLoggerTest.class); - } - - - private void addYesFilter() { - YesFilter filter = new YesFilter(); - filter.start(); - context.addTurboFilter(filter); - } - - private void addNoFilter() { - NoFilter filter = new NoFilter(); - filter.start(); - context.addTurboFilter(filter); - } - - private void addAcceptBLUEFilter() { - MarkerFilter filter = new MarkerFilter(); - filter.setMarker(BLUE); - filter.setOnMatch("ACCEPT"); - filter.start(); - context.addTurboFilter(filter); - } - - private void addDenyBLUEFilter() { - MarkerFilter filter = new MarkerFilter(); - filter.setMarker(BLUE); - filter.setOnMatch("DENY"); - filter.start(); - context.addTurboFilter(filter); - } - - @Test - public void testIsDebugEnabledWithYesFilter() { - addYesFilter(); - logger.setLevel(Level.INFO); - assertTrue(logger.isDebugEnabled()); - } - - @Test - public void testIsInfoEnabledWithYesFilter() { - addYesFilter(); - logger.setLevel(Level.WARN); - assertTrue(logger.isInfoEnabled()); - } - - @Test - public void testIsWarnEnabledWithYesFilter() { - addYesFilter(); - logger.setLevel(Level.ERROR); - assertTrue(logger.isWarnEnabled()); - } - - @Test - public void testIsErrorEnabledWithYesFilter() { - addYesFilter(); - logger.setLevel(Level.OFF); - assertTrue(logger.isErrorEnabled()); - } - - @Test - public void testIsEnabledForWithYesFilter() { - addYesFilter(); - logger.setLevel(Level.ERROR); - assertTrue(logger.isEnabledFor(Level.INFO)); - } - - @Test - public void testIsEnabledForWithNoFilter() { - addNoFilter(); - logger.setLevel(Level.DEBUG); - assertFalse(logger.isEnabledFor(Level.INFO)); - } - - @Test - public void testIsDebugEnabledWithNoFilter() { - addNoFilter(); - logger.setLevel(Level.DEBUG); - assertFalse(logger.isDebugEnabled()); - } - - @Test - public void testIsInfoEnabledWithNoFilter() { - addNoFilter(); - logger.setLevel(Level.DEBUG); - assertFalse(logger.isInfoEnabled()); - } - - @Test - public void testIsWarnEnabledWithNoFilter() { - addNoFilter(); - logger.setLevel(Level.DEBUG); - assertFalse(logger.isWarnEnabled()); - } - - @Test - public void testIsErrorEnabledWithNoFilter() { - addNoFilter(); - logger.setLevel(Level.DEBUG); - assertFalse(logger.isErrorEnabled()); - } - - @Test - public void testIsErrorEnabledWithAcceptBlueFilter() { - addAcceptBLUEFilter(); - logger.setLevel(Level.ERROR); - assertTrue(logger.isDebugEnabled(blueMarker)); - } - - @Test - public void testIsErrorEnabledWithDenyBlueFilter() { - addDenyBLUEFilter(); - logger.setLevel(Level.ALL); - assertFalse(logger.isDebugEnabled(blueMarker)); - } - - @Test - public void testLoggingContextReset() { - addYesFilter(); - assertNotNull(context.getTurboFilterList().get(0)); - context.reset(); - assertEquals(0, context.getTurboFilterList().size()); - } +public class TurboFilteringInLoggerTest { + + static final String BLUE = "BLUE"; + LoggerContext context; + Logger logger; + Marker blueMarker = MarkerFactory.getMarker(BLUE); + + @Before + public void setUp() throws Exception { + context = new LoggerContext(); + context.setName("test"); + context.start(); + logger = context.getLogger(TurboFilteringInLoggerTest.class); + } + + private void addYesFilter() { + YesFilter filter = new YesFilter(); + filter.start(); + context.addTurboFilter(filter); + } + + private void addNoFilter() { + NoFilter filter = new NoFilter(); + filter.start(); + context.addTurboFilter(filter); + } + + private void addAcceptBLUEFilter() { + MarkerFilter filter = new MarkerFilter(); + filter.setMarker(BLUE); + filter.setOnMatch("ACCEPT"); + filter.start(); + context.addTurboFilter(filter); + } + + private void addDenyBLUEFilter() { + MarkerFilter filter = new MarkerFilter(); + filter.setMarker(BLUE); + filter.setOnMatch("DENY"); + filter.start(); + context.addTurboFilter(filter); + } + + @Test + public void testIsDebugEnabledWithYesFilter() { + addYesFilter(); + logger.setLevel(Level.INFO); + assertTrue(logger.isDebugEnabled()); + } + + @Test + public void testIsInfoEnabledWithYesFilter() { + addYesFilter(); + logger.setLevel(Level.WARN); + assertTrue(logger.isInfoEnabled()); + } + + @Test + public void testIsWarnEnabledWithYesFilter() { + addYesFilter(); + logger.setLevel(Level.ERROR); + assertTrue(logger.isWarnEnabled()); + } + + @Test + public void testIsErrorEnabledWithYesFilter() { + addYesFilter(); + logger.setLevel(Level.OFF); + assertTrue(logger.isErrorEnabled()); + } + + @Test + public void testIsEnabledForWithYesFilter() { + addYesFilter(); + logger.setLevel(Level.ERROR); + assertTrue(logger.isEnabledFor(Level.INFO)); + } + + @Test + public void testIsEnabledForWithNoFilter() { + addNoFilter(); + logger.setLevel(Level.DEBUG); + assertFalse(logger.isEnabledFor(Level.INFO)); + } + + @Test + public void testIsDebugEnabledWithNoFilter() { + addNoFilter(); + logger.setLevel(Level.DEBUG); + assertFalse(logger.isDebugEnabled()); + } + + @Test + public void testIsInfoEnabledWithNoFilter() { + addNoFilter(); + logger.setLevel(Level.DEBUG); + assertFalse(logger.isInfoEnabled()); + } + + @Test + public void testIsWarnEnabledWithNoFilter() { + addNoFilter(); + logger.setLevel(Level.DEBUG); + assertFalse(logger.isWarnEnabled()); + } + + @Test + public void testIsErrorEnabledWithNoFilter() { + addNoFilter(); + logger.setLevel(Level.DEBUG); + assertFalse(logger.isErrorEnabled()); + } + + @Test + public void testIsErrorEnabledWithAcceptBlueFilter() { + addAcceptBLUEFilter(); + logger.setLevel(Level.ERROR); + assertTrue(logger.isDebugEnabled(blueMarker)); + } + + @Test + public void testIsErrorEnabledWithDenyBlueFilter() { + addDenyBLUEFilter(); + logger.setLevel(Level.ALL); + assertFalse(logger.isDebugEnabled(blueMarker)); + } + + @Test + public void testLoggingContextReset() { + addYesFilter(); + assertNotNull(context.getTurboFilterList().get(0)); + context.reset(); + assertEquals(0, context.getTurboFilterList().size()); + } } class YesFilter extends TurboFilter { - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String format, Object[] params, Throwable t) { - return FilterReply.ACCEPT; - } + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + return FilterReply.ACCEPT; + } } class NoFilter extends TurboFilter { - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String format, Object[] params, Throwable t) { - return FilterReply.DENY; - } + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + return FilterReply.DENY; + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/ConditionalWithoutJanino.java b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/ConditionalWithoutJanino.java index 15216c80dad0a3dc6a7096b3db91530ad8badc8e..b4e1c9b4cd8969330c62762234758b7e854fd06d 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/ConditionalWithoutJanino.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/ConditionalWithoutJanino.java @@ -31,31 +31,30 @@ import static org.junit.Assert.*; */ public class ConditionalWithoutJanino { - LoggerContext loggerContext = new LoggerContext(); - Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(file); - } - - // assume that janino.jar ia NOT on the classpath - @Test - public void conditionalWithoutJanino() throws JoranException { - String configFile = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/withoutJanino.xml"; - String currentDir = System.getProperty("user.dir"); - if(!currentDir.contains("logback-classic")) { - configFile = "logback-classic/"+configFile; + LoggerContext loggerContext = new LoggerContext(); + Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(file); } - configure(configFile); - StatusPrinter.print(loggerContext); - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertContainsMatch(IfAction.MISSING_JANINO_MSG); - assertSame(Level.WARN, loggerContext.getLogger("a").getLevel()); - assertSame(Level.WARN, root.getLevel()); - } + // assume that janino.jar ia NOT on the classpath + @Test + public void conditionalWithoutJanino() throws JoranException { + String configFile = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/withoutJanino.xml"; + String currentDir = System.getProperty("user.dir"); + if (!currentDir.contains("logback-classic")) { + configFile = "logback-classic/" + configFile; + } + configure(configFile); + StatusPrinter.print(loggerContext); + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertContainsMatch(IfAction.MISSING_JANINO_MSG); + + assertSame(Level.WARN, loggerContext.getLogger("a").getLevel()); + assertSame(Level.WARN, root.getLevel()); + } } - diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/GEventEvaluatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/GEventEvaluatorTest.java index 706affb03c64b555a9913ffefa8ad891830e544a..7b8e5a334b821e8e2efa15eca06e345ede0208ab 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/GEventEvaluatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/GEventEvaluatorTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.boolex; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; @@ -41,136 +40,133 @@ import static org.junit.Assert.assertTrue; public class GEventEvaluatorTest { - LoggerContext context = new LoggerContext(); - StatusChecker statusChecker = new StatusChecker(context); - int LEN = 100 * 1000; - - Logger logger = context.getLogger(this.getClass()); - Marker markerA = MarkerFactory.getMarker("A"); - - GEventEvaluator gee = new GEventEvaluator(); - - @Before - public void setUp() { - gee.setContext(context); - } - - LoggingEvent makeEvent(String msg) { - return makeEvent(Level.DEBUG, msg, null, null); - } - - LoggingEvent makeEvent(Level level, String msg, Throwable t, Object[] argArray) { - return new LoggingEvent(this.getClass().getName(), logger, level, msg, t, argArray); - } - - void doEvaluateAndCheck(String expression, ILoggingEvent event, boolean expected) throws EvaluationException { - gee.setExpression(expression); - gee.start(); - - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - assertTrue(statusChecker.isErrorFree(0)); - - ContextUtil contextUtil = new ContextUtil(context); - contextUtil.addGroovyPackages(context.getFrameworkPackages()); - contextUtil.addFrameworkPackage(context.getFrameworkPackages(), "ch.qos.logback.classic.boolex"); - - boolean result = gee.evaluate(event); - assertEquals(expected, result); - } - - @Test - public void smoke() throws EvaluationException { - doEvaluateAndCheck("1==1", null, true); - } - - @Test - public void event() throws EvaluationException { - ILoggingEvent event = makeEvent("x"); - event.getLoggerContextVO(); - doEvaluateAndCheck("e.message == 'x'", event, true); - } - - @Test - public void msgRegex() throws EvaluationException { - LoggingEvent event = makeEvent("Hello world"); - // partial match - doEvaluateAndCheck("e.message =~ /xyz|wor/", event, true); - // full match - doEvaluateAndCheck("e.message ==~ /xyz|wor/", event, false); - } - - @Test - public void level() throws EvaluationException { - LoggingEvent event = makeEvent("x"); - doEvaluateAndCheck("e.level == DEBUG", event, true); - } - - - @Test - public void nullMarker() throws EvaluationException { - LoggingEvent event = makeEvent("x"); - doEvaluateAndCheck("e.marker?.name == 'YELLOW'", event, false); - } - - @Test - public void marker() throws EvaluationException { - LoggingEvent event = makeEvent("x"); - event.setMarker(markerA); - doEvaluateAndCheck("e.marker?.name == 'A'", event, true); - } - - @Test - public void nullMDC() throws EvaluationException { - LoggingEvent event = makeEvent("x"); - doEvaluateAndCheck("e.mdc?.get('key') == 'val'", event, false); - } - - @Test - public void mdc() throws EvaluationException { - MDC.put("key", "val"); - LoggingEvent event = makeEvent("x"); - doEvaluateAndCheck("e.mdc['key'] == 'val'", event, true); - MDC.clear(); - } - - @Test - public void callerData() throws EvaluationException { - LoggingEvent event = makeEvent("x"); - doEvaluateAndCheck("e.callerData.find{ it.className =~ /junit/ }", event, true); - } - - double loop(GEventEvaluator gee) throws EvaluationException { - long start = System.nanoTime(); - ILoggingEvent event = makeEvent("x"); - for (int i = 0; i < LEN; i++) { - gee.evaluate(event); - } - long end = System.nanoTime(); - return (end - start) / LEN; - } - - - @Test - public void startMakesIsStartedReturnTrue() { - gee.setExpression("return true"); - gee.start(); - assertTrue(gee.isStarted()); - } - - @Test - @Ignore - public void MANUAL_perfTest() throws EvaluationException { - gee.setExpression("event.timeStamp < 100 && event.message != 'xx' "); - gee.start(); - - loop(gee); - loop(gee); - double avgDuration = loop(gee); - - long referencePerf = 500; - BogoPerf.assertDuration(avgDuration, referencePerf, - CoreConstants.REFERENCE_BIPS); - System.out.println("Average duration " + avgDuration); - } + LoggerContext context = new LoggerContext(); + StatusChecker statusChecker = new StatusChecker(context); + int LEN = 100 * 1000; + + Logger logger = context.getLogger(this.getClass()); + Marker markerA = MarkerFactory.getMarker("A"); + + GEventEvaluator gee = new GEventEvaluator(); + + @Before + public void setUp() { + gee.setContext(context); + } + + LoggingEvent makeEvent(String msg) { + return makeEvent(Level.DEBUG, msg, null, null); + } + + LoggingEvent makeEvent(Level level, String msg, Throwable t, Object[] argArray) { + return new LoggingEvent(this.getClass().getName(), logger, level, msg, t, argArray); + } + + void doEvaluateAndCheck(String expression, ILoggingEvent event, boolean expected) throws EvaluationException { + gee.setExpression(expression); + gee.start(); + + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + assertTrue(statusChecker.isErrorFree(0)); + + ContextUtil contextUtil = new ContextUtil(context); + contextUtil.addGroovyPackages(context.getFrameworkPackages()); + contextUtil.addFrameworkPackage(context.getFrameworkPackages(), "ch.qos.logback.classic.boolex"); + + boolean result = gee.evaluate(event); + assertEquals(expected, result); + } + + @Test + public void smoke() throws EvaluationException { + doEvaluateAndCheck("1==1", null, true); + } + + @Test + public void event() throws EvaluationException { + ILoggingEvent event = makeEvent("x"); + event.getLoggerContextVO(); + doEvaluateAndCheck("e.message == 'x'", event, true); + } + + @Test + public void msgRegex() throws EvaluationException { + LoggingEvent event = makeEvent("Hello world"); + // partial match + doEvaluateAndCheck("e.message =~ /xyz|wor/", event, true); + // full match + doEvaluateAndCheck("e.message ==~ /xyz|wor/", event, false); + } + + @Test + public void level() throws EvaluationException { + LoggingEvent event = makeEvent("x"); + doEvaluateAndCheck("e.level == DEBUG", event, true); + } + + @Test + public void nullMarker() throws EvaluationException { + LoggingEvent event = makeEvent("x"); + doEvaluateAndCheck("e.marker?.name == 'YELLOW'", event, false); + } + + @Test + public void marker() throws EvaluationException { + LoggingEvent event = makeEvent("x"); + event.setMarker(markerA); + doEvaluateAndCheck("e.marker?.name == 'A'", event, true); + } + + @Test + public void nullMDC() throws EvaluationException { + LoggingEvent event = makeEvent("x"); + doEvaluateAndCheck("e.mdc?.get('key') == 'val'", event, false); + } + + @Test + public void mdc() throws EvaluationException { + MDC.put("key", "val"); + LoggingEvent event = makeEvent("x"); + doEvaluateAndCheck("e.mdc['key'] == 'val'", event, true); + MDC.clear(); + } + + @Test + public void callerData() throws EvaluationException { + LoggingEvent event = makeEvent("x"); + doEvaluateAndCheck("e.callerData.find{ it.className =~ /junit/ }", event, true); + } + + double loop(GEventEvaluator gee) throws EvaluationException { + long start = System.nanoTime(); + ILoggingEvent event = makeEvent("x"); + for (int i = 0; i < LEN; i++) { + gee.evaluate(event); + } + long end = System.nanoTime(); + return (end - start) / LEN; + } + + @Test + public void startMakesIsStartedReturnTrue() { + gee.setExpression("return true"); + gee.start(); + assertTrue(gee.isStarted()); + } + + @Test + @Ignore + public void MANUAL_perfTest() throws EvaluationException { + gee.setExpression("event.timeStamp < 100 && event.message != 'xx' "); + gee.start(); + + loop(gee); + loop(gee); + double avgDuration = loop(gee); + + long referencePerf = 500; + BogoPerf.assertDuration(avgDuration, referencePerf, CoreConstants.REFERENCE_BIPS); + System.out.println("Average duration " + avgDuration); + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/JaninoEventEvaluatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/JaninoEventEvaluatorTest.java index f48fd8a5b7869ee7135281ee9cbbbda6a1d17cd4..ba1f78111aa3f0f8c949edeaad76d240f9c9d916 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/JaninoEventEvaluatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/JaninoEventEvaluatorTest.java @@ -40,234 +40,228 @@ import ch.qos.logback.core.util.StatusPrinter; public class JaninoEventEvaluatorTest { - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(ConverterTest.class); - - Matcher matcherX = new Matcher(); - - JaninoEventEvaluator jee = new JaninoEventEvaluator(); - - int diff = RandomUtil.getPositiveInt(); - - public JaninoEventEvaluatorTest() { - jee.setContext(loggerContext); - - matcherX.setName("x"); - matcherX.setRegex("^Some\\s.*"); - matcherX.start(); - - } - - LoggingEvent makeLoggingEvent(Exception ex) { - return new LoggingEvent( - ch.qos.logback.core.pattern.FormattingConverter.class.getName(), - logger, Level.INFO, "Some message", ex, null); - } - - @Test - public void testBasic() throws Exception { - jee.setExpression("message.equals(\"Some message\")"); - jee.start(); - - StatusPrinter.print(loggerContext); - ILoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - } - - @Test - public void testLevel() throws Exception { - jee.setExpression("level > DEBUG"); - jee.start(); - - ILoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - } - - @Test - public void testtimeStamp() throws Exception { - jee.setExpression("timeStamp > 10"); - jee.start(); - - ILoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - } - - @Test - public void testWithMatcher() throws Exception { - jee.setExpression("x.matches(message)"); - jee.addMatcher(matcherX); - jee.start(); - - ILoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - } - - - @Test - public void mdcAsString() throws Exception { - String k = "key"+diff; - - MDC.put("key"+diff, "value"+diff); - jee.setExpression("((String) mdc.get(\""+k+"\")).contains(\"alue\")"); - jee.start(); - StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); - - LoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - MDC.remove(k); - } - - @Test - public void marker() throws Exception { - jee.setExpression("marker.contains(\"BLUE\")"); - jee.start(); - - LoggingEvent event = makeLoggingEvent(null); - event.setMarker(MarkerFactory.getMarker("BLUE")); - assertTrue(jee.evaluate(event)); - } - - - @Test - public void withNullMarker_LBCORE_118() throws Exception { - jee.setExpression("marker.contains(\"BLUE\")"); - jee.start(); - - ILoggingEvent event = makeLoggingEvent(null); - try { - jee.evaluate(event); - fail("We should not reach this point"); - } catch (EvaluationException ee) { - // received an exception as expected + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(ConverterTest.class); + + Matcher matcherX = new Matcher(); + + JaninoEventEvaluator jee = new JaninoEventEvaluator(); + + int diff = RandomUtil.getPositiveInt(); + + public JaninoEventEvaluatorTest() { + jee.setContext(loggerContext); + + matcherX.setName("x"); + matcherX.setRegex("^Some\\s.*"); + matcherX.start(); + + } + + LoggingEvent makeLoggingEvent(Exception ex) { + return new LoggingEvent(ch.qos.logback.core.pattern.FormattingConverter.class.getName(), logger, Level.INFO, "Some message", ex, null); } - } - - @Test - public void evaluatorFilterWithNullMarker_LBCORE_118() throws Exception { - EvaluatorFilter ef = new EvaluatorFilter(); - ef.setContext(loggerContext); - - ef.setOnMatch(FilterReply.ACCEPT); - ef.setOnMismatch(FilterReply.DENY); - - jee.setExpression("marker.contains(\"BLUE\")"); - jee.start(); - - ef.setEvaluator(jee); - ef.start(); - ILoggingEvent event = makeLoggingEvent(null); - assertEquals(FilterReply.NEUTRAL, ef.decide(event)); - - } - - @Test - public void testComplex() throws Exception { - jee - .setExpression("level >= INFO && x.matches(message) && marker.contains(\"BLUE\")"); - jee.addMatcher(matcherX); - jee.start(); - - LoggingEvent event = makeLoggingEvent(null); - event.setMarker(MarkerFactory.getMarker("BLUE")); - assertTrue(jee.evaluate(event)); - } - - /** - * check that evaluator with bogus exp does not start - * - * @throws Exception - */ - @Test - public void testBogusExp1() { - jee.setExpression("mzzzz.get(\"key\").equals(null)"); - jee.setName("bogus"); - jee.start(); - - assertFalse(jee.isStarted()); - } - - // check that eval stops after errors - @Test - public void testBogusExp2() { - jee.setExpression("mdc.get(\"keyXN89\").equals(null)"); - jee.setName("bogus"); - jee.start(); - - assertTrue(jee.isStarted()); - - ILoggingEvent event = makeLoggingEvent(null); - - for (int i = 0; i < JaninoEventEvaluatorBase.ERROR_THRESHOLD; i++) { - try { - jee.evaluate(event); - fail("should throw an exception"); - } catch (EvaluationException e) { - } + + @Test + public void testBasic() throws Exception { + jee.setExpression("message.equals(\"Some message\")"); + jee.start(); + + StatusPrinter.print(loggerContext); + ILoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); + } + + @Test + public void testLevel() throws Exception { + jee.setExpression("level > DEBUG"); + jee.start(); + + ILoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); + } + + @Test + public void testtimeStamp() throws Exception { + jee.setExpression("timeStamp > 10"); + jee.start(); + + ILoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); } - // after a few attempts the evaluator should processPriorToRemoval - assertFalse(jee.isStarted()); - - } - - static final long LEN = 10 * 1000; - - // with 6 parameters 400 nanos - // with 7 parameters 460 nanos (all levels + selected fields from - // LoggingEvent) - // with 10 parameters 510 nanos (all levels + fields) - void loop(JaninoEventEvaluator jee, String msg) throws Exception { - ILoggingEvent event = makeLoggingEvent(null); - // final long start = System.nanoTime(); - for (int i = 0; i < LEN; i++) { - jee.evaluate(event); + + @Test + public void testWithMatcher() throws Exception { + jee.setExpression("x.matches(message)"); + jee.addMatcher(matcherX); + jee.start(); + + ILoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); + } + + @Test + public void mdcAsString() throws Exception { + String k = "key" + diff; + + MDC.put("key" + diff, "value" + diff); + jee.setExpression("((String) mdc.get(\"" + k + "\")).contains(\"alue\")"); + jee.start(); + StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); + + LoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); + MDC.remove(k); + } + + @Test + public void marker() throws Exception { + jee.setExpression("marker.contains(\"BLUE\")"); + jee.start(); + + LoggingEvent event = makeLoggingEvent(null); + event.setMarker(MarkerFactory.getMarker("BLUE")); + assertTrue(jee.evaluate(event)); + } + + @Test + public void withNullMarker_LBCORE_118() throws Exception { + jee.setExpression("marker.contains(\"BLUE\")"); + jee.start(); + + ILoggingEvent event = makeLoggingEvent(null); + try { + jee.evaluate(event); + fail("We should not reach this point"); + } catch (EvaluationException ee) { + // received an exception as expected + } + } + + @Test + public void evaluatorFilterWithNullMarker_LBCORE_118() throws Exception { + EvaluatorFilter ef = new EvaluatorFilter(); + ef.setContext(loggerContext); + + ef.setOnMatch(FilterReply.ACCEPT); + ef.setOnMismatch(FilterReply.DENY); + + jee.setExpression("marker.contains(\"BLUE\")"); + jee.start(); + + ef.setEvaluator(jee); + ef.start(); + ILoggingEvent event = makeLoggingEvent(null); + assertEquals(FilterReply.NEUTRAL, ef.decide(event)); + + } + + @Test + public void testComplex() throws Exception { + jee.setExpression("level >= INFO && x.matches(message) && marker.contains(\"BLUE\")"); + jee.addMatcher(matcherX); + jee.start(); + + LoggingEvent event = makeLoggingEvent(null); + event.setMarker(MarkerFactory.getMarker("BLUE")); + assertTrue(jee.evaluate(event)); + } + + /** + * check that evaluator with bogus exp does not start + * + * @throws Exception + */ + @Test + public void testBogusExp1() { + jee.setExpression("mzzzz.get(\"key\").equals(null)"); + jee.setName("bogus"); + jee.start(); + + assertFalse(jee.isStarted()); + } + + // check that eval stops after errors + @Test + public void testBogusExp2() { + jee.setExpression("mdc.get(\"keyXN89\").equals(null)"); + jee.setName("bogus"); + jee.start(); + + assertTrue(jee.isStarted()); + + ILoggingEvent event = makeLoggingEvent(null); + + for (int i = 0; i < JaninoEventEvaluatorBase.ERROR_THRESHOLD; i++) { + try { + jee.evaluate(event); + fail("should throw an exception"); + } catch (EvaluationException e) { + } + } + // after a few attempts the evaluator should processPriorToRemoval + assertFalse(jee.isStarted()); + + } + + static final long LEN = 10 * 1000; + + // with 6 parameters 400 nanos + // with 7 parameters 460 nanos (all levels + selected fields from + // LoggingEvent) + // with 10 parameters 510 nanos (all levels + fields) + void loop(JaninoEventEvaluator jee, String msg) throws Exception { + ILoggingEvent event = makeLoggingEvent(null); + // final long start = System.nanoTime(); + for (int i = 0; i < LEN; i++) { + jee.evaluate(event); + } + // final long end = System.nanoTime(); + // System.out.println(msg + (end - start) / LEN + " nanos"); + } + + @Test + public void testLoop1() throws Exception { + jee.setExpression("timeStamp > 10"); + jee.start(); + + loop(jee, "timestamp > 10]: "); + } + + @Test + public void testLoop2() throws Exception { + jee.setExpression("x.matches(message)"); + jee.addMatcher(matcherX); + jee.start(); + + loop(jee, "x.matches(message): "); + } + + @Test + public void throwable_LBCLASSIC_155_I() throws EvaluationException { + jee.setExpression("throwable instanceof java.io.IOException"); + jee.start(); + + LoggingEvent event = makeLoggingEvent(new IOException("")); + assertTrue(jee.evaluate(event)); + } + + @Test + public void throwable_LBCLASSIC_155_II() throws EvaluationException { + jee.setExpression("throwableProxy.getClassName().contains(\"IO\")"); + jee.start(); + + LoggingEvent event = makeLoggingEvent(new IOException("")); + assertTrue(jee.evaluate(event)); + } + + @Test + public void nullMDC() throws EvaluationException { + MDC.clear(); + jee.setExpression("mdc.isEmpty()"); + jee.start(); + + LoggingEvent event = makeLoggingEvent(null); + assertTrue(jee.evaluate(event)); } - // final long end = System.nanoTime(); - // System.out.println(msg + (end - start) / LEN + " nanos"); - } - - @Test - public void testLoop1() throws Exception { - jee.setExpression("timeStamp > 10"); - jee.start(); - - loop(jee, "timestamp > 10]: "); - } - - @Test - public void testLoop2() throws Exception { - jee.setExpression("x.matches(message)"); - jee.addMatcher(matcherX); - jee.start(); - - loop(jee, "x.matches(message): "); - } - - @Test - public void throwable_LBCLASSIC_155_I() throws EvaluationException { - jee.setExpression("throwable instanceof java.io.IOException"); - jee.start(); - - LoggingEvent event = makeLoggingEvent(new IOException("")); - assertTrue(jee.evaluate(event)); - } - - @Test - public void throwable_LBCLASSIC_155_II() throws EvaluationException { - jee.setExpression("throwableProxy.getClassName().contains(\"IO\")"); - jee.start(); - - LoggingEvent event = makeLoggingEvent(new IOException("")); - assertTrue(jee.evaluate(event)); - } - - - @Test - public void nullMDC() throws EvaluationException { - MDC.clear(); - jee.setExpression("mdc.isEmpty()"); - jee.start(); - - LoggingEvent event = makeLoggingEvent(null); - assertTrue(jee.evaluate(event)); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/OnMarkerEvaluatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/OnMarkerEvaluatorTest.java index cb6a1dd9559bd8ee3fdb51e6ec48f8778617086c..2441fa8894a6817d0b12584a34a6eacabd38275e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/OnMarkerEvaluatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/OnMarkerEvaluatorTest.java @@ -25,44 +25,41 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.boolex.EvaluationException; - public class OnMarkerEvaluatorTest { - - LoggerContext lc = new LoggerContext(); - LoggingEvent event = makeEvent(); - OnMarkerEvaluator evaluator = new OnMarkerEvaluator(); + LoggerContext lc = new LoggerContext(); + LoggingEvent event = makeEvent(); + OnMarkerEvaluator evaluator = new OnMarkerEvaluator(); + + @Before + public void before() { + evaluator.setContext(lc); + } + + @Test + public void smoke() throws EvaluationException { + evaluator.addMarker("M"); + evaluator.start(); + + event.setMarker(MarkerFactory.getMarker("M")); + assertTrue(evaluator.evaluate(event)); + } + + @Test + public void nullMarkerInEvent() throws EvaluationException { + evaluator.addMarker("M"); + evaluator.start(); + assertFalse(evaluator.evaluate(event)); + } + + @Test + public void nullMarkerInEvaluator() throws EvaluationException { + evaluator.addMarker("M"); + evaluator.start(); + assertFalse(evaluator.evaluate(event)); + } - @Before - public void before() { - evaluator.setContext(lc); - } - - @Test - public void smoke() throws EvaluationException { - evaluator.addMarker("M"); - evaluator.start(); - - event.setMarker(MarkerFactory.getMarker("M")); - assertTrue(evaluator.evaluate(event)); - } - - @Test - public void nullMarkerInEvent() throws EvaluationException { - evaluator.addMarker("M"); - evaluator.start(); - assertFalse(evaluator.evaluate(event)); - } - - @Test - public void nullMarkerInEvaluator() throws EvaluationException { - evaluator.addMarker("M"); - evaluator.start(); - assertFalse(evaluator.evaluate(event)); - } - - - LoggingEvent makeEvent() { - return new LoggingEvent("x", lc.getLogger("x"), Level.DEBUG, "msg", null, null); - } + LoggingEvent makeEvent() { + return new LoggingEvent("x", lc.getLogger("x"), Level.DEBUG, "msg", null, null); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/PackageTest.java index 0ab1606caf264116a874b918d18d84ec05510c85..f2a4a39079681cffb5ddcb7fd5be7172f5145a17 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/boolex/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/boolex/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({JaninoEventEvaluatorTest.class, OnMarkerEvaluatorTest.class}) +@SuiteClasses({ JaninoEventEvaluatorTest.class, OnMarkerEvaluatorTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/CLCTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/CLCTest.java index 29f1c1e5b46fb67b7699a1c2171b1d1cf0857c8b..7243c99ffd3e55c19625f37efb8b85a69c306032 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/CLCTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/CLCTest.java @@ -19,38 +19,35 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.control.ControlLogger; import ch.qos.logback.classic.control.ControlLoggerContext; - /** * This class is for testing ControlLoggerContext which is a control class for testing HLoggerContext. */ public class CLCTest extends TestCase { - ControlLoggerContext clc; - - - protected void setUp() throws Exception { - clc = new ControlLoggerContext(); - } + ControlLoggerContext clc; - public void test1() { - ControlLogger x = clc.getLogger("x"); - assertEquals("x", x.getName()); - assertEquals(clc.getRootLogger(), x.parent); + protected void setUp() throws Exception { + clc = new ControlLoggerContext(); + } - ControlLogger abc = clc.getLogger("a.b.c"); - assertEquals("a.b.c", abc.getName()); - assertEquals(Level.DEBUG, abc.getEffectiveLevel()); - } + public void test1() { + ControlLogger x = clc.getLogger("x"); + assertEquals("x", x.getName()); + assertEquals(clc.getRootLogger(), x.parent); - public void testCreation() { - ControlLogger xyz = clc.getLogger("x.y.z"); - assertEquals("x.y.z", xyz.getName()); - assertEquals("x.y", xyz.parent.getName()); - assertEquals("x", xyz.parent.parent.getName()); - assertEquals("root", xyz.parent.parent.parent.getName()); + ControlLogger abc = clc.getLogger("a.b.c"); + assertEquals("a.b.c", abc.getName()); + assertEquals(Level.DEBUG, abc.getEffectiveLevel()); + } - ControlLogger xyz_ = clc.exists("x.y.z"); - assertEquals("x.y.z", xyz_.getName()); + public void testCreation() { + ControlLogger xyz = clc.getLogger("x.y.z"); + assertEquals("x.y.z", xyz.getName()); + assertEquals("x.y", xyz.parent.getName()); + assertEquals("x", xyz.parent.parent.getName()); + assertEquals("root", xyz.parent.parent.parent.getName()); + ControlLogger xyz_ = clc.exists("x.y.z"); + assertEquals("x.y.z", xyz_.getName()); - } + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLogger.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLogger.java index b99a6ccdc3ec2b89431da0a1e80dfe0d473d6a47..6f4bd40e5a689175fc74182aeed8fed869cc1f44 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLogger.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLogger.java @@ -22,164 +22,170 @@ import ch.qos.logback.classic.Level; */ public class ControlLogger extends MarkerIgnoringBase { - private static final long serialVersionUID = 1L; - final ControlLogger parent; - final String name; - Level level; + private static final long serialVersionUID = 1L; + final ControlLogger parent; + final String name; + Level level; + + public ControlLogger(String name, ControlLogger parent) { + if (name == null) { + throw new IllegalArgumentException("name cannot be null"); + } + this.name = name; + this.parent = parent; + } + + public String getName() { + return name; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public final Level getEffectiveLevel() { + for (ControlLogger cl = this; cl != null; cl = cl.parent) { + if (cl.level != null) + return cl.level; + } + return null; // If reached will cause an NullPointerException. + } + + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof ControlLogger)) + return false; + + final ControlLogger controlLogger = (ControlLogger) o; + return name.equals(controlLogger.name); + } + + public int hashCode() { + return name.hashCode(); + } + + public final void trace(String o) { + if (getEffectiveLevel().levelInt <= Level.TRACE_INT) { + throw new UnsupportedOperationException("not yet implemented"); + } + } + + public void trace(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void trace(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void trace(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public final void debug(String o) { + if (getEffectiveLevel().levelInt <= Level.DEBUG_INT) { + throw new UnsupportedOperationException("not yet implemented"); + } + } + + public void debug(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void debug(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void debug(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void error(String msg) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void error(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void error(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File Templates. + } + public void error(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void info(String msg) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void info(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void info(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void info(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isTraceEnabled() { + return false; + } + + public boolean isDebugEnabled() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isErrorEnabled() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isInfoEnabled() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } + + public boolean isWarnEnabled() { + return false; // To change body of implemented methods use File | Settings | File Templates. + } + + public void warn(String msg) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void warn(String msg, Throwable t) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void warn(String parameterizedMsg, Object param1) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void warn(String parameterizedMsg, Object param1, Object param2) { + // To change body of implemented methods use File | Settings | File Templates. + } + + public void trace(String format, Object[] argArray) { + } + + public void debug(String format, Object[] argArray) { + } + + public void info(String format, Object[] argArray) { + } + + public void warn(String format, Object[] argArray) { + } - public ControlLogger(String name, ControlLogger parent) { - if(name == null){ - throw new IllegalArgumentException("name cannot be null"); + public void error(String format, Object[] argArray) { } - this.name = name; - this.parent = parent; - } - public String getName() { - return name; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public final Level getEffectiveLevel() { - for(ControlLogger cl = this; cl != null; cl=cl.parent) { - if(cl.level != null) - return cl.level; - } - return null; // If reached will cause an NullPointerException. - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ControlLogger)) return false; - - final ControlLogger controlLogger = (ControlLogger) o; - return name.equals(controlLogger.name); - } - - public int hashCode() { - return name.hashCode(); - } - - public final void trace(String o) { - if(getEffectiveLevel().levelInt <= Level.TRACE_INT ) { - throw new UnsupportedOperationException("not yet implemented"); - } - } - - public void trace(String msg, Throwable t) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void trace(String parameterizedMsg, Object param1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void trace(String parameterizedMsg, Object param1, Object param2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public final void debug(String o) { - if(getEffectiveLevel().levelInt <= Level.DEBUG_INT ) { - throw new UnsupportedOperationException("not yet implemented"); - } - } - - public void debug(String msg, Throwable t) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void debug(String parameterizedMsg, Object param1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void debug(String parameterizedMsg, Object param1, Object param2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void error(String msg) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void error(String msg, Throwable t) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void error(String parameterizedMsg, Object param1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void error(String parameterizedMsg, Object param1, Object param2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void info(String msg) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void info(String msg, Throwable t) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void info(String parameterizedMsg, Object param1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void info(String parameterizedMsg, Object param1, Object param2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isTraceEnabled() { - return false; - } - - public boolean isDebugEnabled() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isErrorEnabled() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isInfoEnabled() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - public boolean isWarnEnabled() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - public void warn(String msg) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void warn(String msg, Throwable t) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void warn(String parameterizedMsg, Object param1) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void warn(String parameterizedMsg, Object param1, Object param2) { - //To change body of implemented methods use File | Settings | File Templates. - } - - public void trace(String format, Object[] argArray) { - } - public void debug(String format, Object[] argArray) { - } - public void info(String format, Object[] argArray) { - } - public void warn(String format, Object[] argArray) { - } - public void error(String format, Object[] argArray) { - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLoggerContext.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLoggerContext.java index 19666500983909da57bff217f3e15424b9b7676a..e2208f0b545d84325e69cab352eb61b3f15063d0 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLoggerContext.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/ControlLoggerContext.java @@ -37,74 +37,74 @@ import ch.qos.logback.core.CoreConstants; */ public class ControlLoggerContext { - private ControlLogger root; - // - // Hashtable loggerMap = new Hashtable(); - Map loggerMap = new HashMap(); + private ControlLogger root; + // + // Hashtable loggerMap = new Hashtable(); + Map loggerMap = new HashMap(); - public ControlLoggerContext() { - this.root = new ControlLogger("root", null); - this.root.setLevel(Level.DEBUG); - } - - /** - * Return this contexts root logger - * - * @return - */ - public ControlLogger getRootLogger() { - return root; - } - - public ControlLogger exists(String name) { - if (name == null) { - throw new IllegalArgumentException("name parameter cannot be null"); + public ControlLoggerContext() { + this.root = new ControlLogger("root", null); + this.root.setLevel(Level.DEBUG); } - synchronized (loggerMap) { - return (ControlLogger) loggerMap.get(name); + /** + * Return this contexts root logger + * + * @return + */ + public ControlLogger getRootLogger() { + return root; } - } - public final ControlLogger getLogger(String name) { - if (name == null) { - throw new IllegalArgumentException("name parameter cannot be null"); + public ControlLogger exists(String name) { + if (name == null) { + throw new IllegalArgumentException("name parameter cannot be null"); + } + + synchronized (loggerMap) { + return (ControlLogger) loggerMap.get(name); + } } - synchronized (loggerMap) { - ControlLogger cl = (ControlLogger) loggerMap.get(name); - if (cl != null) { - return cl; - } - ControlLogger parent = this.root; + public final ControlLogger getLogger(String name) { + if (name == null) { + throw new IllegalArgumentException("name parameter cannot be null"); + } + + synchronized (loggerMap) { + ControlLogger cl = (ControlLogger) loggerMap.get(name); + if (cl != null) { + return cl; + } + ControlLogger parent = this.root; - int i = 0; - while (true) { - i = name.indexOf(CoreConstants.DOT, i); - if (i == -1) { - // System.out.println("FINAL-Creating logger named [" + name + "] with - // parent " + parent.getName()); - cl = new ControlLogger(name, parent); - loggerMap.put(name, cl); - return cl; - } else { - String parentName = name.substring(0, i); - ControlLogger p = (ControlLogger) loggerMap.get(parentName); - if (p == null) { - // System.out.println("INTERMEDIARY-Creating logger [" + parentName - // + "] with parent " + parent.getName()); - p = new ControlLogger(parentName, parent); - loggerMap.put(parentName, p); - } - parent = p; + int i = 0; + while (true) { + i = name.indexOf(CoreConstants.DOT, i); + if (i == -1) { + // System.out.println("FINAL-Creating logger named [" + name + "] with + // parent " + parent.getName()); + cl = new ControlLogger(name, parent); + loggerMap.put(name, cl); + return cl; + } else { + String parentName = name.substring(0, i); + ControlLogger p = (ControlLogger) loggerMap.get(parentName); + if (p == null) { + // System.out.println("INTERMEDIARY-Creating logger [" + parentName + // + "] with parent " + parent.getName()); + p = new ControlLogger(parentName, parent); + loggerMap.put(parentName, p); + } + parent = p; + } + // make i move past the last found dot. + i++; + } } - // make i move past the last found dot. - i++; - } } - } - public Map getLoggerMap() { - return loggerMap; - } + public Map getLoggerMap() { + return loggerMap; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/CreateLogger.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/CreateLogger.java index a912a4544a4de7fb28dc3d0bc05f3bc1550745c2..f32c91fff59fa647707c18dce684a03d3cad5c88 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/CreateLogger.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/CreateLogger.java @@ -13,20 +13,19 @@ */ package ch.qos.logback.classic.control; - public class CreateLogger extends ScenarioAction { - final String loggerName; + final String loggerName; - public CreateLogger(String loggerName) { - this.loggerName = loggerName; - } + public CreateLogger(String loggerName) { + this.loggerName = loggerName; + } - public String getLoggerName() { - return loggerName; - } + public String getLoggerName() { + return loggerName; + } - public String toString() { - return "CreateLogger("+loggerName+")"; - } + public String toString() { + return "CreateLogger(" + loggerName + ")"; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/PackageTest.java index 53351687c3f16f5b15a176c55f3614a2fe94068f..aa4f5307612fe0081f5733ae4af6676b18adc2a2 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/PackageTest.java @@ -17,7 +17,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; - @RunWith(Suite.class) @SuiteClasses({}) public class PackageTest { diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/Scenario.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/Scenario.java index 2c8cfa7facd87e7f197ded53aa9a688dda2e977c..58c368d1a8e41d5eaf33d4e89b2a48d8136e1971 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/Scenario.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/Scenario.java @@ -19,21 +19,21 @@ import java.util.Vector; public class Scenario { - private List actionList = new Vector(); + private List actionList = new Vector(); - public void add(ScenarioAction action) { - actionList.add(action); - } + public void add(ScenarioAction action) { + actionList.add(action); + } - public List getActionList() { - return new ArrayList(actionList); - } + public List getActionList() { + return new ArrayList(actionList); + } - public int size() { - return actionList.size(); - } + public int size() { + return actionList.size(); + } - public ScenarioAction get(int i) { - return (ScenarioAction) actionList.get(i); - } + public ScenarioAction get(int i) { + return (ScenarioAction) actionList.get(i); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioMaker.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioMaker.java index 4d71c4e7e20bd7556dca3f26d5f67e6f8d005e87..c017c1cc3dfd96059a9bebb9a38308bcd77e65db 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioMaker.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioMaker.java @@ -20,84 +20,81 @@ import ch.qos.logback.core.CoreConstants; public class ScenarioMaker { - private final static int AVERAGE_LOGGER_DEPTH = 4; - private final static int LOGGER_DEPT_DEV = 2; - // the frequency of a set levelInt event for every create logger event - private final static int CREATE_LOGGER_TO_SET_LEVEL_FREQUENCY = 5; - private final static int SECOND_SET_LEVEL_FREQUENCY = 3; + private final static int AVERAGE_LOGGER_DEPTH = 4; + private final static int LOGGER_DEPT_DEV = 2; + // the frequency of a set levelInt event for every create logger event + private final static int CREATE_LOGGER_TO_SET_LEVEL_FREQUENCY = 5; + private final static int SECOND_SET_LEVEL_FREQUENCY = 3; - private static long count = 0; + private static long count = 0; - /** - * Makes a scenario with len logger creations. Logger names are generated - * independently such that the overwhelming majority of logger names will be - * unrelated to each other. Each logger creation may be followed with a - * randomly generated set levelInt action on that logger. - * - * @param len - * @return - */ - static public Scenario makeTypeAScenario(int len) { - Scenario scenario = new Scenario(); - ; - for (int i = 0; i < len; i++) { - String loggerName = ScenarioRandomUtil.randomLoggerName( - AVERAGE_LOGGER_DEPTH, LOGGER_DEPT_DEV); - scenario.add(new CreateLogger(loggerName)); + /** + * Makes a scenario with len logger creations. Logger names are generated + * independently such that the overwhelming majority of logger names will be + * unrelated to each other. Each logger creation may be followed with a + * randomly generated set levelInt action on that logger. + * + * @param len + * @return + */ + static public Scenario makeTypeAScenario(int len) { + Scenario scenario = new Scenario(); + ; + for (int i = 0; i < len; i++) { + String loggerName = ScenarioRandomUtil.randomLoggerName(AVERAGE_LOGGER_DEPTH, LOGGER_DEPT_DEV); + scenario.add(new CreateLogger(loggerName)); + } + return scenario; } - return scenario; - } - static public Scenario makeRealisticCreationScenario(int len) { - Scenario scenario = new Scenario(); - LinkedList queue = new LinkedList(); - int loggerCreationCount = 0; + static public Scenario makeRealisticCreationScenario(int len) { + Scenario scenario = new Scenario(); + LinkedList queue = new LinkedList(); + int loggerCreationCount = 0; - // add an empty string to get going - queue.add(""); + // add an empty string to get going + queue.add(""); - while (loggerCreationCount < len) { - if ((count % 100) == 0) { - System.out.println("count=" + count); - } + while (loggerCreationCount < len) { + if ((count % 100) == 0) { + System.out.println("count=" + count); + } - String loggerName = (String) queue.removeFirst(); - int randomChildrenCount = ScenarioRandomUtil - .randomChildrenCount(loggerName); + String loggerName = (String) queue.removeFirst(); + int randomChildrenCount = ScenarioRandomUtil.randomChildrenCount(loggerName); - if (randomChildrenCount == 0) { - scenario.add(new CreateLogger(loggerName)); - addSetLevelSubScenario(scenario, loggerName); - loggerCreationCount++; - } else { - for (int i = 0; i < randomChildrenCount; i++) { - String childName; - if (loggerName.equals("")) { - childName = ScenarioRandomUtil.randomId(); - count += childName.length(); - } else { - childName = loggerName + CoreConstants.DOT - + ScenarioRandomUtil.randomId(); - count += childName.length(); - } - queue.add(childName); - addSetLevelSubScenario(scenario, loggerName); - loggerCreationCount++; + if (randomChildrenCount == 0) { + scenario.add(new CreateLogger(loggerName)); + addSetLevelSubScenario(scenario, loggerName); + loggerCreationCount++; + } else { + for (int i = 0; i < randomChildrenCount; i++) { + String childName; + if (loggerName.equals("")) { + childName = ScenarioRandomUtil.randomId(); + count += childName.length(); + } else { + childName = loggerName + CoreConstants.DOT + ScenarioRandomUtil.randomId(); + count += childName.length(); + } + queue.add(childName); + addSetLevelSubScenario(scenario, loggerName); + loggerCreationCount++; + } + } } - } + return scenario; } - return scenario; - } - static void addSetLevelSubScenario(Scenario scenario, String loggerName) { - if (ScenarioRandomUtil.oneInFreq(CREATE_LOGGER_TO_SET_LEVEL_FREQUENCY)) { - Level l = ScenarioRandomUtil.randomLevel(); - scenario.add(new SetLevel(l, loggerName)); - if (ScenarioRandomUtil.oneInFreq(SECOND_SET_LEVEL_FREQUENCY)) { - l = ScenarioRandomUtil.randomLevel(); - scenario.add(new SetLevel(l, loggerName)); - } + static void addSetLevelSubScenario(Scenario scenario, String loggerName) { + if (ScenarioRandomUtil.oneInFreq(CREATE_LOGGER_TO_SET_LEVEL_FREQUENCY)) { + Level l = ScenarioRandomUtil.randomLevel(); + scenario.add(new SetLevel(l, loggerName)); + if (ScenarioRandomUtil.oneInFreq(SECOND_SET_LEVEL_FREQUENCY)) { + l = ScenarioRandomUtil.randomLevel(); + scenario.add(new SetLevel(l, loggerName)); + } + } } - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioRandomUtil.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioRandomUtil.java index f27e52e99f434ed951e306bd0b678890309180d2..6815a4875f5119633844bf1fa27749cedf13de0b 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioRandomUtil.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/ScenarioRandomUtil.java @@ -19,117 +19,114 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.corpus.RandomUtil; public class ScenarioRandomUtil { - private final static long SEED = 74130; + private final static long SEED = 74130; - private final static Random random = new Random(SEED); - private final static int AVERAGE_ID_LEN = 32; - private final static int AVERAGE_ID_DEV = 16; + private final static Random random = new Random(SEED); + private final static int AVERAGE_ID_LEN = 32; + private final static int AVERAGE_ID_DEV = 16; - private final static int AVERAGE_CHILDREN_COUNT = 30; - private final static int CHILDREN_COUNT_VAR = 10; + private final static int AVERAGE_CHILDREN_COUNT = 30; + private final static int CHILDREN_COUNT_VAR = 10; - public static boolean oneInFreq(int freq) { - return (random.nextInt(freq) % freq) == 0; - } - - public static Level randomLevel() { - int rl = random.nextInt(6); - switch (rl) { - case 0: - return null; - case 1: - return Level.TRACE; - case 2: - return Level.DEBUG; - case 3: - return Level.INFO; - case 4: - return Level.WARN; - case 5: - return Level.ERROR; - default: - throw new IllegalStateException( - "rl should have been a value between 0 to 5, but it is " + rl); + public static boolean oneInFreq(int freq) { + return (random.nextInt(freq) % freq) == 0; } - } - public static String randomLoggerName(int average, int stdDeviation) { - int depth = RandomUtil.gaussianAsPositiveInt(random, average, stdDeviation); - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < depth; i++) { - if (i != 0) { - buf.append('.'); - } - buf.append(randomId()); + public static Level randomLevel() { + int rl = random.nextInt(6); + switch (rl) { + case 0: + return null; + case 1: + return Level.TRACE; + case 2: + return Level.DEBUG; + case 3: + return Level.INFO; + case 4: + return Level.WARN; + case 5: + return Level.ERROR; + default: + throw new IllegalStateException("rl should have been a value between 0 to 5, but it is " + rl); + } } - return buf.toString(); - } - - public static String randomId() { - int len = RandomUtil.gaussianAsPositiveInt(random, AVERAGE_ID_LEN, AVERAGE_ID_DEV); - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < len; i++) { - int offset = random.nextInt(26); - char c = (char) ('a' + offset); - buf.append(c); + public static String randomLoggerName(int average, int stdDeviation) { + int depth = RandomUtil.gaussianAsPositiveInt(random, average, stdDeviation); + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < depth; i++) { + if (i != 0) { + buf.append('.'); + } + buf.append(randomId()); + } + return buf.toString(); } - return buf.toString(); - } + public static String randomId() { - /** - * Returns 3 for root, 3 for children of root, 9 for offspring of generation 2 - * and 3, and for generations 4 and later, return 0 with probability 0.5 and a - * gaussian (average=AVERAGE_CHILDREN_COUNT) with probability 0.5. - * - * @param name - * @return - */ - public static int randomChildrenCount(String name) { - int dots = dotCount(name); - if (dots <= 1) { - return 3; - } else if (dots == 2 || dots == 3) { - return 9; - } else { - if (shouldHaveChildrenWithProbabilitz(0.5)) { - return RandomUtil.gaussianAsPositiveInt(random, AVERAGE_CHILDREN_COUNT, CHILDREN_COUNT_VAR); - } else { - return 0; - } + int len = RandomUtil.gaussianAsPositiveInt(random, AVERAGE_ID_LEN, AVERAGE_ID_DEV); + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < len; i++) { + int offset = random.nextInt(26); + char c = (char) ('a' + offset); + buf.append(c); + } + return buf.toString(); } - } + /** + * Returns 3 for root, 3 for children of root, 9 for offspring of generation 2 + * and 3, and for generations 4 and later, return 0 with probability 0.5 and a + * gaussian (average=AVERAGE_CHILDREN_COUNT) with probability 0.5. + * + * @param name + * @return + */ + public static int randomChildrenCount(String name) { + int dots = dotCount(name); + if (dots <= 1) { + return 3; + } else if (dots == 2 || dots == 3) { + return 9; + } else { + if (shouldHaveChildrenWithProbabilitz(0.5)) { + return RandomUtil.gaussianAsPositiveInt(random, AVERAGE_CHILDREN_COUNT, CHILDREN_COUNT_VAR); + } else { + return 0; + } + } - /** - * Returns true with probability p. - * - * @param p - * @return - */ - static boolean shouldHaveChildrenWithProbabilitz(double p) { - if (p < 0 || p > 1.0) { - throw new IllegalArgumentException( - "p must be a value between 0 and 1.0, it was " + p + " instead."); } - double r = random.nextDouble(); - if (r < p) { - return true; - } else { - return false; + + /** + * Returns true with probability p. + * + * @param p + * @return + */ + static boolean shouldHaveChildrenWithProbabilitz(double p) { + if (p < 0 || p > 1.0) { + throw new IllegalArgumentException("p must be a value between 0 and 1.0, it was " + p + " instead."); + } + double r = random.nextDouble(); + if (r < p) { + return true; + } else { + return false; + } } - } - static int dotCount(String s) { - int count = 0; - int len = s.length(); - for (int i = 0; i < len; i++) { - char c = s.charAt(i); - if (c == '.') { - count++; - } + static int dotCount(String s) { + int count = 0; + int len = s.length(); + for (int i = 0; i < len; i++) { + char c = s.charAt(i); + if (c == '.') { + count++; + } + } + return count; } - return count; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/control/SetLevel.java b/logback-classic/src/test/java/ch/qos/logback/classic/control/SetLevel.java index 15866dd7eb4210d76d6684239f1322be0c6f75d5..1f19e9de04d7f0840e8eb0c7123bb7b610c847f7 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/control/SetLevel.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/control/SetLevel.java @@ -16,22 +16,23 @@ package ch.qos.logback.classic.control; import ch.qos.logback.classic.Level; public class SetLevel extends ScenarioAction { - final String loggerName; - final Level level; + final String loggerName; + final Level level; - public SetLevel(Level level, String loggerName) { - this.level = level; - this.loggerName = loggerName; - } + public SetLevel(Level level, String loggerName) { + this.level = level; + this.loggerName = loggerName; + } - public Level getLevel() { - return level; - } + public Level getLevel() { + return level; + } - public String getLoggerName() { - return loggerName; - } - public String toString() { - return "SetLevel("+level+", "+loggerName+")"; - } + public String getLoggerName() { + return loggerName; + } + + public String toString() { + return "SetLevel(" + level + ", " + loggerName + ")"; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/Corpus.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/Corpus.java index 43cc98b78c258ab8a65b55be0a02db893e9fd150..affdc18f389583edf80183b97b6eceba9d95c19b 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/Corpus.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/Corpus.java @@ -43,76 +43,71 @@ import ch.qos.logback.core.CoreConstants; */ public class Corpus { - static public final int STANDARD_CORPUS_SIZE = 50 * 1000; - private static final int STANDARD_SEED = 34780; + static public final int STANDARD_CORPUS_SIZE = 50 * 1000; + private static final int STANDARD_SEED = 34780; - static public List getStandatdCorpusWordList() throws IOException { - ClassLoader classLoader = Corpus.class.getClassLoader(); - URL originOfSpeciesURL = classLoader - .getResource("corpus/origin_of_species.txt"); - return TextFileUtil.toWords(originOfSpeciesURL); - } + static public List getStandatdCorpusWordList() throws IOException { + ClassLoader classLoader = Corpus.class.getClassLoader(); + URL originOfSpeciesURL = classLoader.getResource("corpus/origin_of_species.txt"); + return TextFileUtil.toWords(originOfSpeciesURL); + } - /** - * Make a standard corpus. The standard corpus has - * {@link #STANDARD_CORPUS_SIZE} elements. - * - * @return event array representing the standard corpus - * @throws IOException - */ - static public ILoggingEvent[] makeStandardCorpus() throws IOException { - List worldList = getStandatdCorpusWordList(); - CorpusModel corpusMaker = new CorpusModel(STANDARD_SEED, worldList); - return make(corpusMaker, STANDARD_CORPUS_SIZE, true); - } + /** + * Make a standard corpus. The standard corpus has + * {@link #STANDARD_CORPUS_SIZE} elements. + * + * @return event array representing the standard corpus + * @throws IOException + */ + static public ILoggingEvent[] makeStandardCorpus() throws IOException { + List worldList = getStandatdCorpusWordList(); + CorpusModel corpusMaker = new CorpusModel(STANDARD_SEED, worldList); + return make(corpusMaker, STANDARD_CORPUS_SIZE, true); + } - static public ILoggingEvent[] make(CorpusModel corpusModel, int n, - boolean withCallerData) { - LoggerContextVO lcVO = corpusModel.getRandomlyNamedLoggerContextVO(); - PubLoggingEventVO[] plevoArray = new PubLoggingEventVO[n]; - for (int i = 0; i < n; i++) { - PubLoggingEventVO e = new PubLoggingEventVO(); - plevoArray[i] = e; - e.loggerContextVO = lcVO; - e.timeStamp = corpusModel.getRandomTimeStamp(); + static public ILoggingEvent[] make(CorpusModel corpusModel, int n, boolean withCallerData) { + LoggerContextVO lcVO = corpusModel.getRandomlyNamedLoggerContextVO(); + PubLoggingEventVO[] plevoArray = new PubLoggingEventVO[n]; + for (int i = 0; i < n; i++) { + PubLoggingEventVO e = new PubLoggingEventVO(); + plevoArray[i] = e; + e.loggerContextVO = lcVO; + e.timeStamp = corpusModel.getRandomTimeStamp(); - LogStatement logStatement = corpusModel.getRandomLogStatementFromPool(); - e.loggerName = logStatement.loggerName; - e.level = logStatement.level; - e.message = logStatement.mat.message; - e.argumentArray = corpusModel - .getRandomArgumentArray(logStatement.mat.numberOfArguments); + LogStatement logStatement = corpusModel.getRandomLogStatementFromPool(); + e.loggerName = logStatement.loggerName; + e.level = logStatement.level; + e.message = logStatement.mat.message; + e.argumentArray = corpusModel.getRandomArgumentArray(logStatement.mat.numberOfArguments); - if (withCallerData) { - e.callerDataArray = corpusModel.getRandomCallerData( - ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH, e.loggerName); - } - e.throwableProxy = logStatement.throwableProxy; - e.threadName = corpusModel.getRandomThreadNameFromPool(); + if (withCallerData) { + e.callerDataArray = corpusModel.getRandomCallerData(ClassicConstants.DEFAULT_MAX_CALLEDER_DATA_DEPTH, e.loggerName); + } + e.throwableProxy = logStatement.throwableProxy; + e.threadName = corpusModel.getRandomThreadNameFromPool(); + } + return plevoArray; } - return plevoArray; - } - /** - * Dump the events passed as argument into the file named targetFile. - * - * @param eventArray - * @param targetFile - * @throws IOException - */ - public static void dump(ILoggingEvent[] eventArray, String targetFile) - throws IOException { - FileWriter fw = new FileWriter(targetFile); - for (ILoggingEvent e : eventArray) { - fw.write(e.toString()); - fw.append(CoreConstants.LINE_SEPARATOR); - if (e.getThrowableProxy() != null) { - IThrowableProxy tp = e.getThrowableProxy(); - fw.write(ThrowableProxyUtil.asString(tp)); - } + /** + * Dump the events passed as argument into the file named targetFile. + * + * @param eventArray + * @param targetFile + * @throws IOException + */ + public static void dump(ILoggingEvent[] eventArray, String targetFile) throws IOException { + FileWriter fw = new FileWriter(targetFile); + for (ILoggingEvent e : eventArray) { + fw.write(e.toString()); + fw.append(CoreConstants.LINE_SEPARATOR); + if (e.getThrowableProxy() != null) { + IThrowableProxy tp = e.getThrowableProxy(); + fw.write(ThrowableProxyUtil.asString(tp)); + } + } + fw.flush(); + fw.close(); } - fw.flush(); - fw.close(); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/CorpusModel.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/CorpusModel.java index 4088d5ac157ef39e26938b37c0aae08c8cdcfdf8..70b968ad2d8e74c106541b551ad437bbb21a12db 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/CorpusModel.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/CorpusModel.java @@ -35,289 +35,282 @@ import ch.qos.logback.classic.spi.ThrowableProxyVO; */ public class CorpusModel { - // N(u,s) denotes a random variable normally distributed with mean u and - // variance sqrt(s), where sqrt() is the square root function. For an - // explanation of normal distribution please see - // http://en.wikipedia.org/wiki/Normal_distribution - - // It is assumed that the number of parts in a logger name is a random - // variable normally distributed with mean AVERAGE_LOGGER_NAME_PARTS and - // standard deviation STD_DEV_FOR_LOGGER_NAME_PARTS - static final int AVERAGE_LOGGER_NAME_PARTS = 6; - static final int STD_DEV_FOR_LOGGER_NAME_PARTS = 3; - - // It is assumed that there are LOGGER_POOL_SIZE logger names - // in our model corpus. - static final int LOGGER_POOL_SIZE = 1000; - - // It is assumed that there are LOG_STATEMENT_POOL_SIZE log statements - // in our model corpus. - static final int LOG_STATEMENT_POOL_SIZE = LOGGER_POOL_SIZE * 8; - - // level distribution is determined by the following table - // It corresponds to TRACE 3%, DEBUG 30%, INFO 30%, WARN 5%, - // ERROR 5%. See also getRandomLevel() method. - static final double[] LEVEL_DISTRIBUTION = new double[] { .3, .3, .9, .95 }; - - // It is assumed that the number of words in the message (contained in a log - // statement) is a random variable normally distributed with mean - // AVERAGE_MESSAGE_WORDS and standard deviation STD_DEV_FOR_MESSAGE_WORDS - static final int AVERAGE_MESSAGE_WORDS = 8; - static final int STD_DEV_FOR_MESSAGE_WORDS = 4; - - // messages will have no arguments 80% of the time, one argument in 8%, two - // arguments in 7% and three arguments in 5% of cases - static final double[] ARGUMENT_DISTRIBUTION = new double[] { .80, .88, 0.95 }; - - static final double THROWABLE_PROPABILITY_FOR_WARNING = .1; - static final double THROWABLE_PROPABILITY_FOR_ERRORS = .3; - // .5 of throwables are nested once - static final double NESTING_PROBABILITY = .5; - - // For each logging event the timer is incremented by a certain value. it is - // assumed that this value is a random variable normally distributed with mean - // AVERAGE_MILLIS_INCREMENT and standard deviation - // STD_DEV_FOR_MILLIS_INCREMENT - static final int AVERAGE_MILLIS_INCREMENT = 10; - static final int STD_DEV_FOR_MILLIS_INCREMENT = 5; - - // assume that there are THREAD_POOL_SIZE threads in the corpus - static final int THREAD_POOL_SIZE = 10; - - final Random random; - final List worldList; - String[] threadNamePool; - LogStatement[] logStatementPool; - String[] loggerNamePool; - - // 2009-03-06 13:08 GMT - long lastTimeStamp = 1236344888578L; - - public CorpusModel(long seed, List worldList) { - random = new Random(seed); - this.worldList = worldList; - buildThreadNamePool(); - buildLoggerNamePool(); - buildLogStatementPool(); - } - - private void buildThreadNamePool() { - threadNamePool = new String[THREAD_POOL_SIZE]; - for (int i = 0; i < THREAD_POOL_SIZE; i++) { - threadNamePool[i] = "CorpusMakerThread-" + i; + // N(u,s) denotes a random variable normally distributed with mean u and + // variance sqrt(s), where sqrt() is the square root function. For an + // explanation of normal distribution please see + // http://en.wikipedia.org/wiki/Normal_distribution + + // It is assumed that the number of parts in a logger name is a random + // variable normally distributed with mean AVERAGE_LOGGER_NAME_PARTS and + // standard deviation STD_DEV_FOR_LOGGER_NAME_PARTS + static final int AVERAGE_LOGGER_NAME_PARTS = 6; + static final int STD_DEV_FOR_LOGGER_NAME_PARTS = 3; + + // It is assumed that there are LOGGER_POOL_SIZE logger names + // in our model corpus. + static final int LOGGER_POOL_SIZE = 1000; + + // It is assumed that there are LOG_STATEMENT_POOL_SIZE log statements + // in our model corpus. + static final int LOG_STATEMENT_POOL_SIZE = LOGGER_POOL_SIZE * 8; + + // level distribution is determined by the following table + // It corresponds to TRACE 3%, DEBUG 30%, INFO 30%, WARN 5%, + // ERROR 5%. See also getRandomLevel() method. + static final double[] LEVEL_DISTRIBUTION = new double[] { .3, .3, .9, .95 }; + + // It is assumed that the number of words in the message (contained in a log + // statement) is a random variable normally distributed with mean + // AVERAGE_MESSAGE_WORDS and standard deviation STD_DEV_FOR_MESSAGE_WORDS + static final int AVERAGE_MESSAGE_WORDS = 8; + static final int STD_DEV_FOR_MESSAGE_WORDS = 4; + + // messages will have no arguments 80% of the time, one argument in 8%, two + // arguments in 7% and three arguments in 5% of cases + static final double[] ARGUMENT_DISTRIBUTION = new double[] { .80, .88, 0.95 }; + + static final double THROWABLE_PROPABILITY_FOR_WARNING = .1; + static final double THROWABLE_PROPABILITY_FOR_ERRORS = .3; + // .5 of throwables are nested once + static final double NESTING_PROBABILITY = .5; + + // For each logging event the timer is incremented by a certain value. it is + // assumed that this value is a random variable normally distributed with mean + // AVERAGE_MILLIS_INCREMENT and standard deviation + // STD_DEV_FOR_MILLIS_INCREMENT + static final int AVERAGE_MILLIS_INCREMENT = 10; + static final int STD_DEV_FOR_MILLIS_INCREMENT = 5; + + // assume that there are THREAD_POOL_SIZE threads in the corpus + static final int THREAD_POOL_SIZE = 10; + + final Random random; + final List worldList; + String[] threadNamePool; + LogStatement[] logStatementPool; + String[] loggerNamePool; + + // 2009-03-06 13:08 GMT + long lastTimeStamp = 1236344888578L; + + public CorpusModel(long seed, List worldList) { + random = new Random(seed); + this.worldList = worldList; + buildThreadNamePool(); + buildLoggerNamePool(); + buildLogStatementPool(); } - } - private void buildLoggerNamePool() { - loggerNamePool = new String[LOGGER_POOL_SIZE]; - for (int i = 0; i < LOGGER_POOL_SIZE; i++) { - loggerNamePool[i] = makeRandomLoggerName(); + private void buildThreadNamePool() { + threadNamePool = new String[THREAD_POOL_SIZE]; + for (int i = 0; i < THREAD_POOL_SIZE; i++) { + threadNamePool[i] = "CorpusMakerThread-" + i; + } } - } - private void buildLogStatementPool() { - logStatementPool = new LogStatement[LOG_STATEMENT_POOL_SIZE]; - for (int i = 0; i < LOG_STATEMENT_POOL_SIZE; i++) { - logStatementPool[i] = makeRandomLogStatement(loggerNamePool); + private void buildLoggerNamePool() { + loggerNamePool = new String[LOGGER_POOL_SIZE]; + for (int i = 0; i < LOGGER_POOL_SIZE; i++) { + loggerNamePool[i] = makeRandomLoggerName(); + } } - } - - private int[] getRandomAnchorPositions(int wordCount, int numAnchors) { - // note that the same position may appear multiple times in - // positionsIndex, but without serious consequences - int[] positionsIndex = new int[numAnchors]; - for (int i = 0; i < numAnchors; i++) { - positionsIndex[i] = random.nextInt(wordCount); - } - return positionsIndex; - } - private String[] getRandomWords(int n) { - String[] wordArray = new String[n]; - for (int i = 0; i < n; i++) { - wordArray[i] = getRandomWord(); - } - return wordArray; - } - - public long getRandomLong() { - return random.nextLong(); - } - - public String getRandomThreadNameFromPool() { - int index = random.nextInt(THREAD_POOL_SIZE); - return threadNamePool[index]; - } - - public LogStatement getRandomLogStatementFromPool() { - int index = random.nextInt(logStatementPool.length); - return logStatementPool[index]; - } - - private String getRandomLoggerNameFromPool(String[] loggerNamePool) { - int index = random.nextInt(loggerNamePool.length); - return loggerNamePool[index]; - } - - public long getRandomTimeStamp() { - // subtract 1 so that 0 is allowed - lastTimeStamp += RandomUtil.gaussianAsPositiveInt(random, - AVERAGE_MILLIS_INCREMENT, STD_DEV_FOR_MILLIS_INCREMENT) - 1; - return lastTimeStamp; - } - - LoggerContextVO getRandomlyNamedLoggerContextVO() { - LoggerContext lc = new LoggerContext(); - lc.setName(getRandomJavaIdentifier()); - return new LoggerContextVO(lc); - } - - String getRandomWord() { - int size = worldList.size(); - int randomIndex = random.nextInt(size); - return worldList.get(randomIndex); - } - - String extractLastPart(String loggerName) { - int i = loggerName.lastIndexOf('.'); - if (i == -1) { - return loggerName; - } else { - return loggerName.substring(i + 1); + private void buildLogStatementPool() { + logStatementPool = new LogStatement[LOG_STATEMENT_POOL_SIZE]; + for (int i = 0; i < LOG_STATEMENT_POOL_SIZE; i++) { + logStatementPool[i] = makeRandomLogStatement(loggerNamePool); + } } - } - - public StackTraceElement[] getRandomCallerData(int depth, String loggerName) { - StackTraceElement[] cda = new StackTraceElement[depth]; - StackTraceElement cd = new StackTraceElement(loggerName, - getRandomJavaIdentifier(), extractLastPart(loggerName), 0); - cda[0] = cd; - for (int i = 1; i < depth; i++) { - String ln = getRandomLoggerNameFromPool(loggerNamePool); - cda[i] = new StackTraceElement(ln, getRandomJavaIdentifier(), - extractLastPart(ln), i * 10); + + private int[] getRandomAnchorPositions(int wordCount, int numAnchors) { + // note that the same position may appear multiple times in + // positionsIndex, but without serious consequences + int[] positionsIndex = new int[numAnchors]; + for (int i = 0; i < numAnchors; i++) { + positionsIndex[i] = random.nextInt(wordCount); + } + return positionsIndex; } - return cda; - } - public Object[] getRandomArgumentArray(int numOfArguments) { - if (numOfArguments == 0) { - return null; + private String[] getRandomWords(int n) { + String[] wordArray = new String[n]; + for (int i = 0; i < n; i++) { + wordArray[i] = getRandomWord(); + } + return wordArray; } - Object[] argumentArray = new Object[numOfArguments]; - for (int i = 0; i < numOfArguments; i++) { - argumentArray[i] = new Long(random.nextLong()); + + public long getRandomLong() { + return random.nextLong(); } - return argumentArray; - } - private MessageArgumentTuple makeRandomMessageArgumentTuple() { - int numOfArguments = getNumberOfMessageArguments(); + public String getRandomThreadNameFromPool() { + int index = random.nextInt(THREAD_POOL_SIZE); + return threadNamePool[index]; + } - int wordCount = RandomUtil.gaussianAsPositiveInt(random, - AVERAGE_MESSAGE_WORDS, STD_DEV_FOR_MESSAGE_WORDS); - String[] wordArray = getRandomWords(wordCount); + public LogStatement getRandomLogStatementFromPool() { + int index = random.nextInt(logStatementPool.length); + return logStatementPool[index]; + } - int[] anchorPositions = getRandomAnchorPositions(wordCount, numOfArguments); + private String getRandomLoggerNameFromPool(String[] loggerNamePool) { + int index = random.nextInt(loggerNamePool.length); + return loggerNamePool[index]; + } - for (int anchorIndex : anchorPositions) { - wordArray[anchorIndex] = "{}"; + public long getRandomTimeStamp() { + // subtract 1 so that 0 is allowed + lastTimeStamp += RandomUtil.gaussianAsPositiveInt(random, AVERAGE_MILLIS_INCREMENT, STD_DEV_FOR_MILLIS_INCREMENT) - 1; + return lastTimeStamp; } - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < wordCount; i++) { - sb.append(wordArray[i]).append(' '); + LoggerContextVO getRandomlyNamedLoggerContextVO() { + LoggerContext lc = new LoggerContext(); + lc.setName(getRandomJavaIdentifier()); + return new LoggerContextVO(lc); } - sb.append(getRandomWord()); - return new MessageArgumentTuple(sb.toString(), numOfArguments); - } - - private LogStatement makeRandomLogStatement(String[] loggerNamePool) { - MessageArgumentTuple mat = makeRandomMessageArgumentTuple(); - String loggerName = getRandomLoggerNameFromPool(loggerNamePool); - Level randomLevel = getRandomLevel(); - Throwable t = getRandomThrowable(randomLevel); - ThrowableProxyVO throwableProxy = null; - if (t != null) { - throwableProxy = ThrowableProxyVO.build(new ThrowableProxy(t)); - pupulateWithPackagingData(throwableProxy.getStackTraceElementProxyArray()); + + String getRandomWord() { + int size = worldList.size(); + int randomIndex = random.nextInt(size); + return worldList.get(randomIndex); } - return new LogStatement(loggerName, randomLevel, mat, - throwableProxy); - } - - private Throwable getRandomThrowable(Level level) { - double rn = random.nextDouble(); - if ((level == Level.WARN && rn < THROWABLE_PROPABILITY_FOR_WARNING) - || (level == Level.ERROR && rn < THROWABLE_PROPABILITY_FOR_ERRORS)) { - return ExceptionBuilder.build(random, NESTING_PROBABILITY); - } else { - return null; + + String extractLastPart(String loggerName) { + int i = loggerName.lastIndexOf('.'); + if (i == -1) { + return loggerName; + } else { + return loggerName.substring(i + 1); + } } - } - - private void pupulateWithPackagingData(StackTraceElementProxy[] stepArray) { - int i = 0; - for (StackTraceElementProxy step : stepArray) { - String identifier = "na"; - String version = "na"; - if (i++ % 2 == 0) { - identifier = getRandomJavaIdentifier(); - version = getRandomJavaIdentifier(); - } - ClassPackagingData cpd = new ClassPackagingData(identifier, version); - step.setClassPackagingData(cpd); + + public StackTraceElement[] getRandomCallerData(int depth, String loggerName) { + StackTraceElement[] cda = new StackTraceElement[depth]; + StackTraceElement cd = new StackTraceElement(loggerName, getRandomJavaIdentifier(), extractLastPart(loggerName), 0); + cda[0] = cd; + for (int i = 1; i < depth; i++) { + String ln = getRandomLoggerNameFromPool(loggerNamePool); + cda[i] = new StackTraceElement(ln, getRandomJavaIdentifier(), extractLastPart(ln), i * 10); + } + return cda; } - } - private int getNumberOfMessageArguments() { - double rn = random.nextDouble(); - if (rn < ARGUMENT_DISTRIBUTION[0]) { - return 0; + public Object[] getRandomArgumentArray(int numOfArguments) { + if (numOfArguments == 0) { + return null; + } + Object[] argumentArray = new Object[numOfArguments]; + for (int i = 0; i < numOfArguments; i++) { + argumentArray[i] = new Long(random.nextLong()); + } + return argumentArray; } - if (rn < ARGUMENT_DISTRIBUTION[1]) { - return 1; + + private MessageArgumentTuple makeRandomMessageArgumentTuple() { + int numOfArguments = getNumberOfMessageArguments(); + + int wordCount = RandomUtil.gaussianAsPositiveInt(random, AVERAGE_MESSAGE_WORDS, STD_DEV_FOR_MESSAGE_WORDS); + String[] wordArray = getRandomWords(wordCount); + + int[] anchorPositions = getRandomAnchorPositions(wordCount, numOfArguments); + + for (int anchorIndex : anchorPositions) { + wordArray[anchorIndex] = "{}"; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < wordCount; i++) { + sb.append(wordArray[i]).append(' '); + } + sb.append(getRandomWord()); + return new MessageArgumentTuple(sb.toString(), numOfArguments); } - if (rn < ARGUMENT_DISTRIBUTION[2]) { - return 2; + + private LogStatement makeRandomLogStatement(String[] loggerNamePool) { + MessageArgumentTuple mat = makeRandomMessageArgumentTuple(); + String loggerName = getRandomLoggerNameFromPool(loggerNamePool); + Level randomLevel = getRandomLevel(); + Throwable t = getRandomThrowable(randomLevel); + ThrowableProxyVO throwableProxy = null; + if (t != null) { + throwableProxy = ThrowableProxyVO.build(new ThrowableProxy(t)); + pupulateWithPackagingData(throwableProxy.getStackTraceElementProxyArray()); + } + return new LogStatement(loggerName, randomLevel, mat, throwableProxy); } - return 3; - } - - String getRandomJavaIdentifier() { - String w = getRandomWord(); - w = w.replaceAll("\\p{Punct}", ""); - return w; - } - - private String makeRandomLoggerName() { - int parts = RandomUtil.gaussianAsPositiveInt(random, - AVERAGE_LOGGER_NAME_PARTS, STD_DEV_FOR_LOGGER_NAME_PARTS); - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < parts; i++) { - sb.append(getRandomJavaIdentifier()).append('.'); + + private Throwable getRandomThrowable(Level level) { + double rn = random.nextDouble(); + if ((level == Level.WARN && rn < THROWABLE_PROPABILITY_FOR_WARNING) || (level == Level.ERROR && rn < THROWABLE_PROPABILITY_FOR_ERRORS)) { + return ExceptionBuilder.build(random, NESTING_PROBABILITY); + } else { + return null; + } } - sb.append(getRandomJavaIdentifier()); - return sb.toString(); - } - - private Level getRandomLevel() { - double rn = random.nextDouble(); - if (rn < LEVEL_DISTRIBUTION[0]) { - return Level.TRACE; + + private void pupulateWithPackagingData(StackTraceElementProxy[] stepArray) { + int i = 0; + for (StackTraceElementProxy step : stepArray) { + String identifier = "na"; + String version = "na"; + if (i++ % 2 == 0) { + identifier = getRandomJavaIdentifier(); + version = getRandomJavaIdentifier(); + } + ClassPackagingData cpd = new ClassPackagingData(identifier, version); + step.setClassPackagingData(cpd); + } } - if (rn < LEVEL_DISTRIBUTION[1]) { - return Level.DEBUG; + + private int getNumberOfMessageArguments() { + double rn = random.nextDouble(); + if (rn < ARGUMENT_DISTRIBUTION[0]) { + return 0; + } + if (rn < ARGUMENT_DISTRIBUTION[1]) { + return 1; + } + if (rn < ARGUMENT_DISTRIBUTION[2]) { + return 2; + } + return 3; } - if (rn < LEVEL_DISTRIBUTION[2]) { - return Level.INFO; + String getRandomJavaIdentifier() { + String w = getRandomWord(); + w = w.replaceAll("\\p{Punct}", ""); + return w; } - if (rn < LEVEL_DISTRIBUTION[3]) { - return Level.WARN; + private String makeRandomLoggerName() { + int parts = RandomUtil.gaussianAsPositiveInt(random, AVERAGE_LOGGER_NAME_PARTS, STD_DEV_FOR_LOGGER_NAME_PARTS); + StringBuilder sb = new StringBuilder(); + for (int i = 1; i < parts; i++) { + sb.append(getRandomJavaIdentifier()).append('.'); + } + sb.append(getRandomJavaIdentifier()); + return sb.toString(); } - return Level.ERROR; - } + private Level getRandomLevel() { + double rn = random.nextDouble(); + if (rn < LEVEL_DISTRIBUTION[0]) { + return Level.TRACE; + } + if (rn < LEVEL_DISTRIBUTION[1]) { + return Level.DEBUG; + } + + if (rn < LEVEL_DISTRIBUTION[2]) { + return Level.INFO; + } + + if (rn < LEVEL_DISTRIBUTION[3]) { + return Level.WARN; + } + + return Level.ERROR; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/ExceptionBuilder.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/ExceptionBuilder.java index 81c25d2be4cec0aa436938492e2733e4b0bf423e..c288fe53ed29d25ce878c7be5f905f13cd90b4e5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/ExceptionBuilder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/ExceptionBuilder.java @@ -19,29 +19,33 @@ import javax.management.remote.JMXProviderException; public class ExceptionBuilder { - static Throwable build(Random r, double nestingProbability) { - double rn = r.nextDouble(); - boolean nested = false; - if (rn < nestingProbability) { - nested = true; - } + static Throwable build(Random r, double nestingProbability) { + double rn = r.nextDouble(); + boolean nested = false; + if (rn < nestingProbability) { + nested = true; + } - Throwable cause = null; - if(nested) { - cause = makeThrowable(r, null); - } - return makeThrowable(r, cause); - } + Throwable cause = null; + if (nested) { + cause = makeThrowable(r, null); + } + return makeThrowable(r, cause); + } - private static Throwable makeThrowable(Random r, Throwable cause) { - int exType = r.nextInt(4); - switch(exType) { - case 0: return new IllegalArgumentException("an illegal argument was passed", cause); - case 1: return new Exception("this is a test", cause); - case 2: return new JMXProviderException("jmx provider exception error occured", cause); - case 3: return new OutOfMemoryError("ran out of memory"); + private static Throwable makeThrowable(Random r, Throwable cause) { + int exType = r.nextInt(4); + switch (exType) { + case 0: + return new IllegalArgumentException("an illegal argument was passed", cause); + case 1: + return new Exception("this is a test", cause); + case 2: + return new JMXProviderException("jmx provider exception error occured", cause); + case 3: + return new OutOfMemoryError("ran out of memory"); + } + return null; } - return null; - } - + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/LogStatement.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/LogStatement.java index 4367d359686a36486a09760d0273d13e6b9ba199..68bfc2a44c969529e97ec33179e7dc3251b2334a 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/LogStatement.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/LogStatement.java @@ -26,21 +26,19 @@ import ch.qos.logback.classic.spi.IThrowableProxy; */ public class LogStatement { - final String loggerName; - final MessageArgumentTuple mat; - final Level level; - final IThrowableProxy throwableProxy; + final String loggerName; + final MessageArgumentTuple mat; + final Level level; + final IThrowableProxy throwableProxy; - public LogStatement(String loggerName, Level level, MessageArgumentTuple mat, - IThrowableProxy tp) { - this.loggerName = loggerName; - this.level = level; - this.mat = mat; - this.throwableProxy = tp; - } + public LogStatement(String loggerName, Level level, MessageArgumentTuple mat, IThrowableProxy tp) { + this.loggerName = loggerName; + this.level = level; + this.mat = mat; + this.throwableProxy = tp; + } - - public String getLoggerName() { - return loggerName; - } + public String getLoggerName() { + return loggerName; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/MessageArgumentTuple.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/MessageArgumentTuple.java index 8990042d51713e9775e1888f303aab154c43c23e..a05159c9092ff40825703710ff231ece272594be 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/MessageArgumentTuple.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/MessageArgumentTuple.java @@ -14,17 +14,17 @@ package ch.qos.logback.classic.corpus; public class MessageArgumentTuple { - - final String message; - final int numberOfArguments; - MessageArgumentTuple(String message) { - this(message, 0); - } + final String message; + final int numberOfArguments; - public MessageArgumentTuple(String message, int numberOfArguments) { - this.message = message; - this.numberOfArguments = numberOfArguments; - } + MessageArgumentTuple(String message) { + this(message, 0); + } + + public MessageArgumentTuple(String message, int numberOfArguments) { + this.message = message; + this.numberOfArguments = numberOfArguments; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/RandomUtil.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/RandomUtil.java index 8abd8fa03dfd465a10d75b0af0e1c029d708ed04..77f4c5acf434fec8c1b7625a14f349a8c4ec0e93 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/RandomUtil.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/RandomUtil.java @@ -17,30 +17,27 @@ import java.util.Random; public class RandomUtil { - - /** - * Approximate a gaussian distrib with only positive integer values - * - * @param average - * @param stdDeviation - * @return - */ - static public int gaussianAsPositiveInt(Random random, int average, int stdDeviation) { - if (average < 1) { - throw new IllegalArgumentException( - "The average must not be smaller than 1."); - } + /** + * Approximate a gaussian distrib with only positive integer values + * + * @param average + * @param stdDeviation + * @return + */ + static public int gaussianAsPositiveInt(Random random, int average, int stdDeviation) { + if (average < 1) { + throw new IllegalArgumentException("The average must not be smaller than 1."); + } - if (stdDeviation < 1) { - throw new IllegalArgumentException( - "The stdDeviation must not be smaller than 1."); - } + if (stdDeviation < 1) { + throw new IllegalArgumentException("The stdDeviation must not be smaller than 1."); + } - double d = random.nextGaussian() * stdDeviation + average; - int result = 1; - if (d > 1.0) { - result = (int) Math.round(d); + double d = random.nextGaussian() * stdDeviation + average; + int result = 1; + if (d > 1.0) { + result = (int) Math.round(d); + } + return result; } - return result; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/TextFileUtil.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/TextFileUtil.java index a2b75d267e7082df15aef6f138de5d3cd83d992a..c3f742a5016053854947e65faf1d5ddda2b8905d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpus/TextFileUtil.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpus/TextFileUtil.java @@ -24,38 +24,37 @@ import java.util.List; public class TextFileUtil { - - public static List toWords(URL url) throws IOException { - InputStream is = url.openStream(); - InputStreamReader reader = new InputStreamReader(is); - BufferedReader br = new BufferedReader(reader); - return toWords(br); - } - - public static List toWords(String filename) throws IOException { - FileReader fr = new FileReader(filename); - BufferedReader br = new BufferedReader(fr); - return toWords(br); - } - - public static List toWords(BufferedReader br) throws IOException { - - // (\\d+)$ - //String regExp = "^(\\d+) "+ msg + " ([\\dabcdef-]+)$"; - //Pattern p = Pattern.compile(regExp); - String line; - - List wordList = new ArrayList(); - - while ((line = br.readLine()) != null) { - //line = line.replaceAll("\\p{Punct}+", " "); - String[] words = line.split("\\s"); - for(String word: words) { - wordList.add(word); - } - } - br.close(); - - return wordList; - } + public static List toWords(URL url) throws IOException { + InputStream is = url.openStream(); + InputStreamReader reader = new InputStreamReader(is); + BufferedReader br = new BufferedReader(reader); + return toWords(br); + } + + public static List toWords(String filename) throws IOException { + FileReader fr = new FileReader(filename); + BufferedReader br = new BufferedReader(fr); + return toWords(br); + } + + public static List toWords(BufferedReader br) throws IOException { + + // (\\d+)$ + // String regExp = "^(\\d+) "+ msg + " ([\\dabcdef-]+)$"; + // Pattern p = Pattern.compile(regExp); + String line; + + List wordList = new ArrayList(); + + while ((line = br.readLine()) != null) { + // line = line.replaceAll("\\p{Punct}+", " "); + String[] words = line.split("\\s"); + for (String word : words) { + wordList.add(word); + } + } + br.close(); + + return wordList; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/RandomUtilTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/RandomUtilTest.java index a4a18f953fd5fdd9ace68cfd7b0ebd25579c5e16..2d85074b5cf4535d0f4297bf5e53801b6e57a1b9 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/RandomUtilTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/RandomUtilTest.java @@ -22,40 +22,38 @@ import org.junit.Test; import ch.qos.logback.classic.corpus.RandomUtil; - public class RandomUtilTest { - long now = System.currentTimeMillis(); - - @Before - public void setup() { - System.out.println(RandomUtilTest.class.getName()+" now="+now); - } - - @Test - public void smoke() { - - int EXPECTED_AVERAGE = 6; - int EXPECTED_STD_DEVIATION = 3; - - - System.out.println(); - Random r = new Random(now); - int len = 3000; - int[] valArray = new int[len]; - for(int i = 0; i < len; i++) { - valArray[i] = RandomUtil.gaussianAsPositiveInt(r, EXPECTED_AVERAGE, EXPECTED_STD_DEVIATION); + long now = System.currentTimeMillis(); + + @Before + public void setup() { + System.out.println(RandomUtilTest.class.getName() + " now=" + now); } - double avg = average(valArray); - - assertEquals(EXPECTED_AVERAGE, avg, 0.3); - } - - public double average(int[] va) { - double avg = 0; - for(int i = 0; i < va.length; i++) { - avg = (avg*i+va[i])/(i+1); + + @Test + public void smoke() { + + int EXPECTED_AVERAGE = 6; + int EXPECTED_STD_DEVIATION = 3; + + System.out.println(); + Random r = new Random(now); + int len = 3000; + int[] valArray = new int[len]; + for (int i = 0; i < len; i++) { + valArray[i] = RandomUtil.gaussianAsPositiveInt(r, EXPECTED_AVERAGE, EXPECTED_STD_DEVIATION); + } + double avg = average(valArray); + + assertEquals(EXPECTED_AVERAGE, avg, 0.3); + } + + public double average(int[] va) { + double avg = 0; + for (int i = 0; i < va.length; i++) { + avg = (avg * i + va[i]) / (i + 1); + } + return avg; } - return avg; - } - + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/TextFileUtilTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/TextFileUtilTest.java index a249c2748d7fc3ba39c0d7f5b85215b47aa73823..72b7e26c62f02d006ce9b1e4d59cd9b2c59396d8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/TextFileUtilTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/corpusTest/TextFileUtilTest.java @@ -26,20 +26,19 @@ import ch.qos.logback.classic.corpus.TextFileUtil; public class TextFileUtilTest { - @Test - public void smoke() throws IOException { - String s = "When on board H.M.S. 'Beagle,' as naturalist, I was much struck with\r\n" - + "certain facts in the distribution of the inhabitants of South America,\r\n" - + "and in the geological relations of the present to the past inhabitants\r\n" - + "of that continent."; - - StringReader sr = new StringReader(s); - BufferedReader br = new BufferedReader(sr); - List wordList = TextFileUtil.toWords(br); - assertEquals(38, wordList.size()); - assertEquals("When", wordList.get(0)); - assertEquals("'Beagle,'", wordList.get(4)); - assertEquals("of", wordList.get(17)); - - } + @Test + public void smoke() throws IOException { + String s = "When on board H.M.S. 'Beagle,' as naturalist, I was much struck with\r\n" + + "certain facts in the distribution of the inhabitants of South America,\r\n" + + "and in the geological relations of the present to the past inhabitants\r\n" + "of that continent."; + + StringReader sr = new StringReader(s); + BufferedReader br = new BufferedReader(sr); + List wordList = TextFileUtil.toWords(br); + assertEquals(38, wordList.size()); + assertEquals("When", wordList.get(0)); + assertEquals("'Beagle,'", wordList.get(4)); + assertEquals("of", wordList.get(17)); + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2Test.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2Test.java index ff14382cdec3e5e147cadeef3072a66434119541..adba0a4db05a45a01a2f1c34e6e4d96d77f44810 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2Test.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2Test.java @@ -41,185 +41,179 @@ import ch.qos.logback.core.util.StatusPrinter; public class DBAppenderH2Test { - LoggerContext loggerContext = new LoggerContext();; - Logger logger; - DBAppender appender; - DriverManagerConnectionSource connectionSource; - DBAppenderH2TestFixture dbAppenderH2TestFixture; - int diff = RandomUtil.getPositiveInt(); - StatusChecker checker = new StatusChecker(loggerContext); - - @Before - public void setUp() throws SQLException { - dbAppenderH2TestFixture = new DBAppenderH2TestFixture(); - dbAppenderH2TestFixture.setUp(); - loggerContext.setName("default"); - logger = loggerContext.getLogger("root"); - appender = new DBAppender(); - appender.setName("DB"); - appender.setContext(loggerContext); - connectionSource = new DriverManagerConnectionSource(); - connectionSource.setContext(loggerContext); - connectionSource.setDriverClass(DBAppenderH2TestFixture.H2_DRIVER_CLASS); - connectionSource.setUrl(dbAppenderH2TestFixture.url); - System.out.println("cs.url=" + dbAppenderH2TestFixture.url); - connectionSource.setUser(dbAppenderH2TestFixture.user); - connectionSource.setPassword(dbAppenderH2TestFixture.password); - - - connectionSource.start(); - appender.setConnectionSource(connectionSource); - appender.start(); - } - - @After - public void tearDown() throws SQLException { - logger = null; - loggerContext = null; - appender = null; - connectionSource = null; - dbAppenderH2TestFixture.tearDown(); - } - - @Test - public void testAppendLoggingEvent() throws SQLException { - ILoggingEvent event = createLoggingEvent(); - - appender.append(event); - - StatusPrinter.print(loggerContext); - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM logging_event"); - if (rs.next()) { - assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); - assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); - assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX)); - assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX)); - assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX)); - assertEquals(DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX)); - assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX)); - StackTraceElement callerData = event.getCallerData()[0]; - assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX)); - assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX)); - assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX)); - } else { - fail("No row was inserted in the database"); + LoggerContext loggerContext = new LoggerContext();; + Logger logger; + DBAppender appender; + DriverManagerConnectionSource connectionSource; + DBAppenderH2TestFixture dbAppenderH2TestFixture; + int diff = RandomUtil.getPositiveInt(); + StatusChecker checker = new StatusChecker(loggerContext); + + @Before + public void setUp() throws SQLException { + dbAppenderH2TestFixture = new DBAppenderH2TestFixture(); + dbAppenderH2TestFixture.setUp(); + loggerContext.setName("default"); + logger = loggerContext.getLogger("root"); + appender = new DBAppender(); + appender.setName("DB"); + appender.setContext(loggerContext); + connectionSource = new DriverManagerConnectionSource(); + connectionSource.setContext(loggerContext); + connectionSource.setDriverClass(DBAppenderH2TestFixture.H2_DRIVER_CLASS); + connectionSource.setUrl(dbAppenderH2TestFixture.url); + System.out.println("cs.url=" + dbAppenderH2TestFixture.url); + connectionSource.setUser(dbAppenderH2TestFixture.user); + connectionSource.setPassword(dbAppenderH2TestFixture.password); + + connectionSource.start(); + appender.setConnectionSource(connectionSource); + appender.start(); } - rs.close(); - stmt.close(); - } - - @Test - public void testAppendThrowable() throws SQLException { - ILoggingEvent event = createLoggingEvent(); - appender.append(event); - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_EXCEPTION WHERE EVENT_ID=1"); - rs.next(); - String expected = "java.lang.Exception: test Ex"; - String firstLine = rs.getString(3); - assertTrue("[" + firstLine + "] does not match [" + expected + "]", firstLine.contains(expected)); - - int i = 0; - while (rs.next()) { - expected = event.getThrowableProxy().getStackTraceElementProxyArray()[i].toString(); - String st = rs.getString(3); - assertTrue("[" + st + "] does not match [" + expected + "]", st.contains(expected)); - i++; + @After + public void tearDown() throws SQLException { + logger = null; + loggerContext = null; + appender = null; + connectionSource = null; + dbAppenderH2TestFixture.tearDown(); } - assertTrue(i != 0); - rs.close(); - stmt.close(); - } - - @Test - public void withNullArgument() throws SQLException { - ILoggingEvent event = createLoggingEvent("Processing code {}; code type is {}; request date {}; record from date {}", new Object[] { 1, 2, new Date(), null }); - appender.append(event); - - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM logging_event"); - if (rs.next()) { - assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); - assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); - } - } - - @Test - public void testContextInfo() throws SQLException { - loggerContext.putProperty("testKey1", "testValue1"); - MDC.put("k" + diff, "v" + diff); - ILoggingEvent event = createLoggingEvent(); - - appender.append(event); - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID=1"); - Map map = appender.mergePropertyMaps(event); - int i = 0; - while (rs.next()) { - String key = rs.getString(2); - assertEquals(map.get(key), rs.getString(3)); - i++; - } - assertTrue(map.size() != 0); - assertEquals(map.size(), i); - rs.close(); - stmt.close(); - } - - - @Test - public void testAppendMultipleEvents() throws SQLException { - for (int i = 0; i < 10; i++) { - ILoggingEvent event = createLoggingEvent(); - appender.append(event); + @Test + public void testAppendLoggingEvent() throws SQLException { + ILoggingEvent event = createLoggingEvent(); + + appender.append(event); + + StatusPrinter.print(loggerContext); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM logging_event"); + if (rs.next()) { + assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); + assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); + assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX)); + assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX)); + assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX)); + assertEquals(DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX)); + assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX)); + StackTraceElement callerData = event.getCallerData()[0]; + assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX)); + assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX)); + assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX)); + } else { + fail("No row was inserted in the database"); + } + + rs.close(); + stmt.close(); } - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM logging_event"); - int count = 0; - while (rs.next()) { - count++; + @Test + public void testAppendThrowable() throws SQLException { + ILoggingEvent event = createLoggingEvent(); + appender.append(event); + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_EXCEPTION WHERE EVENT_ID=1"); + rs.next(); + String expected = "java.lang.Exception: test Ex"; + String firstLine = rs.getString(3); + assertTrue("[" + firstLine + "] does not match [" + expected + "]", firstLine.contains(expected)); + + int i = 0; + while (rs.next()) { + expected = event.getThrowableProxy().getStackTraceElementProxyArray()[i].toString(); + String st = rs.getString(3); + assertTrue("[" + st + "] does not match [" + expected + "]", st.contains(expected)); + i++; + } + assertTrue(i != 0); + + rs.close(); + stmt.close(); } - assertEquals(10, count); - - rs.close(); - stmt.close(); - } - // http://jira.qos.ch/browse/LOGBACK-805 - @Test - public void emptyCallerDataShouldBeHandledGracefully() { - LoggingEvent event = createLoggingEvent(); - event.setCallerData(new StackTraceElement[0]); - appender.append(event); + @Test + public void withNullArgument() throws SQLException { + ILoggingEvent event = createLoggingEvent("Processing code {}; code type is {}; request date {}; record from date {}", new Object[] { 1, 2, new Date(), + null }); + appender.append(event); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM logging_event"); + if (rs.next()) { + assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); + assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); + } + } - event.setCallerData(new StackTraceElement[] {null}); - appender.append(event); + @Test + public void testContextInfo() throws SQLException { + loggerContext.putProperty("testKey1", "testValue1"); + MDC.put("k" + diff, "v" + diff); + ILoggingEvent event = createLoggingEvent(); + + appender.append(event); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID=1"); + Map map = appender.mergePropertyMaps(event); + int i = 0; + while (rs.next()) { + String key = rs.getString(2); + assertEquals(map.get(key), rs.getString(3)); + i++; + } + assertTrue(map.size() != 0); + assertEquals(map.size(), i); + rs.close(); + stmt.close(); + } - checker.assertIsErrorFree(); - } + @Test + public void testAppendMultipleEvents() throws SQLException { + for (int i = 0; i < 10; i++) { + ILoggingEvent event = createLoggingEvent(); + appender.append(event); + } + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM logging_event"); + int count = 0; + while (rs.next()) { + count++; + } + assertEquals(10, count); + + rs.close(); + stmt.close(); + } + // http://jira.qos.ch/browse/LOGBACK-805 + @Test + public void emptyCallerDataShouldBeHandledGracefully() { + LoggingEvent event = createLoggingEvent(); + event.setCallerData(new StackTraceElement[0]); + appender.append(event); - private LoggingEvent createLoggingEvent(String msg, Object[] args) { - return new LoggingEvent(this.getClass().getName(), logger, - Level.DEBUG, msg, new Exception("test Ex"), args); - } + event.setCallerData(new StackTraceElement[] { null }); + appender.append(event); + checker.assertIsErrorFree(); + } - private LoggingEvent createLoggingEvent() { - return createLoggingEvent("test message", new Integer[]{diff}); - } + private LoggingEvent createLoggingEvent(String msg, Object[] args) { + return new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, msg, new Exception("test Ex"), args); + } + private LoggingEvent createLoggingEvent() { + return createLoggingEvent("test message", new Integer[] { diff }); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2TestFixture.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2TestFixture.java index 648b6a5eb982dabfa6bc05ee3507156b9a4edfd6..df41c0217b8665bd55a85d1e9f2cba504d9db72a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2TestFixture.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderH2TestFixture.java @@ -24,119 +24,118 @@ import org.h2.Driver; import ch.qos.logback.core.testUtil.RandomUtil; -public class DBAppenderH2TestFixture { - - public enum H2Mode { - MEM, FILE, NET; - } - - public static final String H2_DRIVER_CLASS = "org.h2.Driver"; - String url = null; - String user = "sa"; - String password = ""; - - // boolean isNetwork = true; - H2Mode mode = H2Mode.MEM; - - int diff = RandomUtil.getPositiveInt(); - - Connection connection; - - public void setUp() throws SQLException { - - switch (mode) { - case NET: - url = "jdbc:h2:tcp://localhost:4808/test"; - break; - case MEM: - url = "jdbc:h2:mem:test"+diff; - break; - case FILE: - url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; - break; +public class DBAppenderH2TestFixture { + public enum H2Mode { + MEM, FILE, NET; } - connection = newConnection(); - createTables(); - } - - public void tearDown() throws SQLException { - dropTables(); - connection.close(); - } - - Connection newConnection() throws SQLException { - System.out.println("url="+url); - org.h2.Driver driver = Driver.load(); - Properties props = new Properties(); - props.setProperty("user", user); - props.setProperty("password", password); - return driver.connect(url, props); - } - - private void createTables() throws SQLException { - assertNotNull(connection); - StringBuilder buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT ("); - buf.append("TIMESTMP BIGINT NOT NULL,"); - buf.append("FORMATTED_MESSAGE LONGVARCHAR NOT NULL,"); - buf.append("LOGGER_NAME VARCHAR(256) NOT NULL,"); - buf.append("LEVEL_STRING VARCHAR(256) NOT NULL,"); - buf.append("THREAD_NAME VARCHAR(256),"); - buf.append("REFERENCE_FLAG SMALLINT,"); - buf.append("ARG0 VARCHAR(256),"); - buf.append("ARG1 VARCHAR(256),"); - buf.append("ARG2 VARCHAR(256),"); - buf.append("ARG3 VARCHAR(256),"); - buf.append("CALLER_FILENAME VARCHAR(256), "); - buf.append("CALLER_CLASS VARCHAR(256), "); - buf.append("CALLER_METHOD VARCHAR(256), "); - buf.append("CALLER_LINE CHAR(4), "); - buf.append("EVENT_ID IDENTITY NOT NULL);"); - executeQuery(connection, buf.toString()); - - buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT_PROPERTY ("); - buf.append("EVENT_ID BIGINT NOT NULL,"); - buf.append("MAPPED_KEY VARCHAR(254) NOT NULL,"); - buf.append("MAPPED_VALUE LONGVARCHAR,"); - buf.append("PRIMARY KEY(EVENT_ID, MAPPED_KEY),"); - buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); - executeQuery(connection, buf.toString()); - - buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT_EXCEPTION ("); - buf.append("EVENT_ID BIGINT NOT NULL,"); - buf.append("I SMALLINT NOT NULL,"); - buf.append("TRACE_LINE VARCHAR(256) NOT NULL,"); - buf.append("PRIMARY KEY(EVENT_ID, I),"); - buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); - executeQuery(connection, buf.toString()); - } - - private void dropTables() throws SQLException { - StringBuilder buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT_EXCEPTION IF EXISTS;"); - executeQuery(connection, buf.toString()); - - buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT_PROPERTY IF EXISTS;"); - executeQuery(connection, buf.toString()); - - buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT IF EXISTS;"); - executeQuery(connection, buf.toString()); - } - - private void executeQuery(Connection conn, String expression) throws SQLException { - Statement st = null; - st = conn.createStatement(); - int i = st.executeUpdate(expression); - if (i == -1) { - throw new IllegalStateException("db error : " + expression); + + public static final String H2_DRIVER_CLASS = "org.h2.Driver"; + String url = null; + String user = "sa"; + String password = ""; + + // boolean isNetwork = true; + H2Mode mode = H2Mode.MEM; + + int diff = RandomUtil.getPositiveInt(); + + Connection connection; + + public void setUp() throws SQLException { + + switch (mode) { + case NET: + url = "jdbc:h2:tcp://localhost:4808/test"; + break; + case MEM: + url = "jdbc:h2:mem:test" + diff; + break; + case FILE: + url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; + break; + + } + connection = newConnection(); + createTables(); + } + + public void tearDown() throws SQLException { + dropTables(); + connection.close(); } - st.close(); - } + Connection newConnection() throws SQLException { + System.out.println("url=" + url); + org.h2.Driver driver = Driver.load(); + Properties props = new Properties(); + props.setProperty("user", user); + props.setProperty("password", password); + return driver.connect(url, props); + } + + private void createTables() throws SQLException { + assertNotNull(connection); + StringBuilder buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT ("); + buf.append("TIMESTMP BIGINT NOT NULL,"); + buf.append("FORMATTED_MESSAGE LONGVARCHAR NOT NULL,"); + buf.append("LOGGER_NAME VARCHAR(256) NOT NULL,"); + buf.append("LEVEL_STRING VARCHAR(256) NOT NULL,"); + buf.append("THREAD_NAME VARCHAR(256),"); + buf.append("REFERENCE_FLAG SMALLINT,"); + buf.append("ARG0 VARCHAR(256),"); + buf.append("ARG1 VARCHAR(256),"); + buf.append("ARG2 VARCHAR(256),"); + buf.append("ARG3 VARCHAR(256),"); + buf.append("CALLER_FILENAME VARCHAR(256), "); + buf.append("CALLER_CLASS VARCHAR(256), "); + buf.append("CALLER_METHOD VARCHAR(256), "); + buf.append("CALLER_LINE CHAR(4), "); + buf.append("EVENT_ID IDENTITY NOT NULL);"); + executeQuery(connection, buf.toString()); + + buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT_PROPERTY ("); + buf.append("EVENT_ID BIGINT NOT NULL,"); + buf.append("MAPPED_KEY VARCHAR(254) NOT NULL,"); + buf.append("MAPPED_VALUE LONGVARCHAR,"); + buf.append("PRIMARY KEY(EVENT_ID, MAPPED_KEY),"); + buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); + executeQuery(connection, buf.toString()); + + buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT_EXCEPTION ("); + buf.append("EVENT_ID BIGINT NOT NULL,"); + buf.append("I SMALLINT NOT NULL,"); + buf.append("TRACE_LINE VARCHAR(256) NOT NULL,"); + buf.append("PRIMARY KEY(EVENT_ID, I),"); + buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); + executeQuery(connection, buf.toString()); + } + + private void dropTables() throws SQLException { + StringBuilder buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT_EXCEPTION IF EXISTS;"); + executeQuery(connection, buf.toString()); + + buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT_PROPERTY IF EXISTS;"); + executeQuery(connection, buf.toString()); + + buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT IF EXISTS;"); + executeQuery(connection, buf.toString()); + } + + private void executeQuery(Connection conn, String expression) throws SQLException { + Statement st = null; + st = conn.createStatement(); + int i = st.executeUpdate(expression); + if (i == -1) { + throw new IllegalStateException("db error : " + expression); + } + st.close(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTest.java index 2190280071a46a409804984a91531c25a175bcb8..3f007194bcc5ed7ac5a26e2d015ea27a9a31891c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTest.java @@ -34,173 +34,166 @@ import ch.qos.logback.core.db.DriverManagerConnectionSource; import ch.qos.logback.core.testUtil.RandomUtil; import ch.qos.logback.core.util.StatusPrinter; -public class DBAppenderHSQLTest { - - LoggerContext lc; - Logger logger; - DBAppender appender; - DriverManagerConnectionSource connectionSource; - - static DBAppenderHSQLTestFixture DB_APPENDER_HSQL_TEST_FIXTURE; - int diff = RandomUtil.getPositiveInt(); - int existingRowCount; - Statement stmt; - - @BeforeClass - public static void beforeClass() throws SQLException { - DB_APPENDER_HSQL_TEST_FIXTURE = new DBAppenderHSQLTestFixture(); - DB_APPENDER_HSQL_TEST_FIXTURE.setUp(); - } - - @AfterClass - public static void afterClass() throws SQLException { - DB_APPENDER_HSQL_TEST_FIXTURE.tearDown(); - } - - @Before - public void setUp() throws SQLException { - lc = new LoggerContext(); - lc.setName("default"); - logger = lc.getLogger("root"); - appender = new DBAppender(); - appender.setName("DB"); - appender.setContext(lc); - connectionSource = new DriverManagerConnectionSource(); - connectionSource.setContext(lc); - connectionSource.setDriverClass(DBAppenderHSQLTestFixture.HSQLDB_DRIVER_CLASS); - connectionSource.setUrl(DB_APPENDER_HSQL_TEST_FIXTURE.url); - connectionSource.setUser(DB_APPENDER_HSQL_TEST_FIXTURE.user); - connectionSource.setPassword(DB_APPENDER_HSQL_TEST_FIXTURE.password); - connectionSource.start(); - appender.setConnectionSource(connectionSource); - appender.start(); - - stmt = connectionSource.getConnection().createStatement(); - existingRowCount = existingRowCount(stmt); - - } - - - - @After - public void tearDown() throws SQLException { - logger = null; - lc = null; - appender = null; - connectionSource = null; - stmt.close(); - } - - int existingRowCount(Statement stmt) throws SQLException { - ResultSet rs = stmt.executeQuery("SELECT count(*) FROM logging_event"); - int result = -1; - if (rs.next()) { - result = rs.getInt(1); +public class DBAppenderHSQLTest { + + LoggerContext lc; + Logger logger; + DBAppender appender; + DriverManagerConnectionSource connectionSource; + + static DBAppenderHSQLTestFixture DB_APPENDER_HSQL_TEST_FIXTURE; + int diff = RandomUtil.getPositiveInt(); + int existingRowCount; + Statement stmt; + + @BeforeClass + public static void beforeClass() throws SQLException { + DB_APPENDER_HSQL_TEST_FIXTURE = new DBAppenderHSQLTestFixture(); + DB_APPENDER_HSQL_TEST_FIXTURE.setUp(); } - rs.close(); - return result; - } - - @Test - public void testAppendLoggingEvent() throws SQLException { - - - ILoggingEvent event = createLoggingEvent(); - appender.append(event); - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM logging_event where EVENT_ID = "+ existingRowCount); - if (rs.next()) { - assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); - assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); - assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX)); - assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX)); - assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX)); - assertEquals(DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX)); - assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX)); - StackTraceElement callerData = event.getCallerData()[0]; - assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX)); - assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX)); - assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX)); - } else { - fail("No row was inserted in the database"); + + @AfterClass + public static void afterClass() throws SQLException { + DB_APPENDER_HSQL_TEST_FIXTURE.tearDown(); + } + + @Before + public void setUp() throws SQLException { + lc = new LoggerContext(); + lc.setName("default"); + logger = lc.getLogger("root"); + appender = new DBAppender(); + appender.setName("DB"); + appender.setContext(lc); + connectionSource = new DriverManagerConnectionSource(); + connectionSource.setContext(lc); + connectionSource.setDriverClass(DBAppenderHSQLTestFixture.HSQLDB_DRIVER_CLASS); + connectionSource.setUrl(DB_APPENDER_HSQL_TEST_FIXTURE.url); + connectionSource.setUser(DB_APPENDER_HSQL_TEST_FIXTURE.user); + connectionSource.setPassword(DB_APPENDER_HSQL_TEST_FIXTURE.password); + connectionSource.start(); + appender.setConnectionSource(connectionSource); + appender.start(); + + stmt = connectionSource.getConnection().createStatement(); + existingRowCount = existingRowCount(stmt); + + } + + @After + public void tearDown() throws SQLException { + logger = null; + lc = null; + appender = null; + connectionSource = null; + stmt.close(); } - rs.close(); - } - - - - @Test - public void testAppendThrowable() throws SQLException { - ILoggingEvent event = createLoggingEvent(); - appender.append(event); - - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_EXCEPTION where EVENT_ID = "+ existingRowCount); - - rs.next(); - String expected = "java.lang.Exception: test Ex"; - String firstLine = rs.getString(3); - assertTrue("["+firstLine+"] does not match ["+expected+"]", firstLine.contains(expected)); - - int i = 0; - while (rs.next()) { - expected = event.getThrowableProxy().getStackTraceElementProxyArray()[i].toString(); - String st = rs.getString(3); - assertTrue("["+st+"] does not match ["+expected+"]", st.contains(expected)); - i++; + + int existingRowCount(Statement stmt) throws SQLException { + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM logging_event"); + int result = -1; + if (rs.next()) { + result = rs.getInt(1); + } + rs.close(); + return result; } - assertTrue(i != 0); - rs.close(); - } - - @Test - public void testContextInfo() throws SQLException { - lc.putProperty("testKey1", "testValue1"); - MDC.put("k"+diff, "v"+diff); - ILoggingEvent event = createLoggingEvent(); - - appender.append(event); - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID = "+ existingRowCount); - Map map = appender.mergePropertyMaps(event); - System.out.println("ma.size="+map.size()); - int i = 0; - while (rs.next()) { - String key = rs.getString(2); - assertEquals(map.get(key), rs.getString(3)); - i++; + + @Test + public void testAppendLoggingEvent() throws SQLException { + + ILoggingEvent event = createLoggingEvent(); + appender.append(event); + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM logging_event where EVENT_ID = " + existingRowCount); + if (rs.next()) { + assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); + assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); + assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX)); + assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX)); + assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX)); + assertEquals(DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX)); + assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX)); + StackTraceElement callerData = event.getCallerData()[0]; + assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX)); + assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX)); + assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX)); + } else { + fail("No row was inserted in the database"); + } + rs.close(); } - assertTrue(map.size() != 0); - assertEquals(map.size(), i); - rs.close(); - } - - @Test - public void testAppendMultipleEvents() throws SQLException { - int numEvents = 3; - for (int i = 0; i < numEvents; i++) { - ILoggingEvent event = createLoggingEvent(); - appender.append(event); + + @Test + public void testAppendThrowable() throws SQLException { + ILoggingEvent event = createLoggingEvent(); + appender.append(event); + + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_EXCEPTION where EVENT_ID = " + existingRowCount); + + rs.next(); + String expected = "java.lang.Exception: test Ex"; + String firstLine = rs.getString(3); + assertTrue("[" + firstLine + "] does not match [" + expected + "]", firstLine.contains(expected)); + + int i = 0; + while (rs.next()) { + expected = event.getThrowableProxy().getStackTraceElementProxyArray()[i].toString(); + String st = rs.getString(3); + assertTrue("[" + st + "] does not match [" + expected + "]", st.contains(expected)); + i++; + } + assertTrue(i != 0); + rs.close(); } - - Statement stmt = connectionSource.getConnection().createStatement(); - ResultSet rs = null; - rs = stmt.executeQuery("SELECT * FROM logging_event WHERE EVENT_ID >="+ existingRowCount); - int count = 0; - while (rs.next()) { - count++; + + @Test + public void testContextInfo() throws SQLException { + lc.putProperty("testKey1", "testValue1"); + MDC.put("k" + diff, "v" + diff); + ILoggingEvent event = createLoggingEvent(); + + appender.append(event); + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM LOGGING_EVENT_PROPERTY WHERE EVENT_ID = " + existingRowCount); + Map map = appender.mergePropertyMaps(event); + System.out.println("ma.size=" + map.size()); + int i = 0; + while (rs.next()) { + String key = rs.getString(2); + assertEquals(map.get(key), rs.getString(3)); + i++; + } + assertTrue(map.size() != 0); + assertEquals(map.size(), i); + rs.close(); } - assertEquals(numEvents, count); - rs.close(); - } + @Test + public void testAppendMultipleEvents() throws SQLException { + int numEvents = 3; + for (int i = 0; i < numEvents; i++) { + ILoggingEvent event = createLoggingEvent(); + appender.append(event); + } + + Statement stmt = connectionSource.getConnection().createStatement(); + ResultSet rs = null; + rs = stmt.executeQuery("SELECT * FROM logging_event WHERE EVENT_ID >=" + existingRowCount); + int count = 0; + while (rs.next()) { + count++; + } + assertEquals(numEvents, count); + rs.close(); + } - private ILoggingEvent createLoggingEvent() { - return new LoggingEvent(this.getClass().getName(), logger, - Level.DEBUG, "test message", new Exception("test Ex"), new Integer[]{diff}); - } + private ILoggingEvent createLoggingEvent() { + return new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, "test message", new Exception("test Ex"), new Integer[] { diff }); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTestFixture.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTestFixture.java index ab34f497aa1a1add60cfd1423ffe6cc78db5bf41..b72d7de012de53d5634e246904d5621e7afa0223 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTestFixture.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderHSQLTestFixture.java @@ -25,153 +25,151 @@ import org.hsqldb.Server; import org.hsqldb.ServerConstants; import org.hsqldb.jdbcDriver; -public class DBAppenderHSQLTestFixture { - - public static final String HSQLDB_DRIVER_CLASS = "org.hsqldb.jdbcDriver"; - // String serverProps; - String url = null; - String user = "sa"; - String password = ""; - Server server; - - // boolean isNetwork = true; - HsqlMode mode = HsqlMode.MEM; - - public void setUp() throws SQLException { - - switch (mode) { - case NET: - url = "jdbc:hsqldb:hsql://localhost:4808/test"; - break; - case MEM: - url = "jdbc:hsqldb:mem:test;sql.enforce_strict_size=true"; - server = new Server(); - server.setDatabaseName(0, "test"); - server.setDatabasePath(0, url); - server.setLogWriter(new PrintWriter(System.out)); - server.setErrWriter(new PrintWriter(System.out)); - server.setTrace(false); - server.setSilent(false); - server.start(); - - break; - case FILE: - url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; - break; +public class DBAppenderHSQLTestFixture { + + public static final String HSQLDB_DRIVER_CLASS = "org.hsqldb.jdbcDriver"; + // String serverProps; + String url = null; + String user = "sa"; + String password = ""; + Server server; + + // boolean isNetwork = true; + HsqlMode mode = HsqlMode.MEM; + + public void setUp() throws SQLException { + + switch (mode) { + case NET: + url = "jdbc:hsqldb:hsql://localhost:4808/test"; + break; + case MEM: + url = "jdbc:hsqldb:mem:test;sql.enforce_strict_size=true"; + server = new Server(); + server.setDatabaseName(0, "test"); + server.setDatabasePath(0, url); + server.setLogWriter(new PrintWriter(System.out)); + server.setErrWriter(new PrintWriter(System.out)); + server.setTrace(false); + server.setSilent(false); + server.start(); + + break; + case FILE: + url = "jdbc:hsqldb:file:test;sql.enforce_strict_size=true"; + break; + + } + + // try { + // Class.forName(DRIVER_CLASS); + // } catch (Exception e) { + // e.printStackTrace(); + // System.out.println(this + ".setUp() error: " + e.getMessage()); + // } + // Thread.yield(); + System.out.println(server.getState()); + + int waitCount = 0; + while (server.getState() != ServerConstants.SERVER_STATE_ONLINE && waitCount < 5) { + try { + waitCount++; + Thread.sleep(1); + } catch (InterruptedException e) { + } + } + createTables(); + } + + public void tearDown() throws SQLException { + dropTables(); + + if (mode == HsqlMode.MEM) { + server.stop(); + server = null; + } + } + + Connection newConnection() throws SQLException { + jdbcDriver driver = new jdbcDriver(); + Properties props = new Properties(); + props.setProperty("user", user); + props.setProperty("password", password); + return driver.connect(url, props); + // return DriverManager.getConnection(url, user, password); } - // try { - // Class.forName(DRIVER_CLASS); - // } catch (Exception e) { - // e.printStackTrace(); - // System.out.println(this + ".setUp() error: " + e.getMessage()); - // } - // Thread.yield(); - System.out.println(server.getState()); - - int waitCount = 0; - while (server.getState() != ServerConstants.SERVER_STATE_ONLINE - && waitCount < 5) { - try { - waitCount++; - Thread.sleep(1); - } catch (InterruptedException e) { - } + private void createTables() throws SQLException { + Connection conn = newConnection(); + assertNotNull(conn); + StringBuilder buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT ("); + buf.append("TIMESTMP BIGINT NOT NULL,"); + buf.append("FORMATTED_MESSAGE LONGVARCHAR NOT NULL,"); + buf.append("LOGGER_NAME VARCHAR(256) NOT NULL,"); + buf.append("LEVEL_STRING VARCHAR(256) NOT NULL,"); + buf.append("THREAD_NAME VARCHAR(256),"); + buf.append("REFERENCE_FLAG SMALLINT,"); + + buf.append("ARG0 VARCHAR(256),"); + buf.append("ARG1 VARCHAR(256),"); + buf.append("ARG2 VARCHAR(256),"); + buf.append("ARG3 VARCHAR(256),"); + + buf.append("CALLER_FILENAME VARCHAR(256), "); + buf.append("CALLER_CLASS VARCHAR(256), "); + buf.append("CALLER_METHOD VARCHAR(256), "); + buf.append("CALLER_LINE CHAR(4), "); + buf.append("EVENT_ID BIGINT NOT NULL IDENTITY);"); + query(conn, buf.toString()); + + buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT_PROPERTY ("); + buf.append("EVENT_ID BIGINT NOT NULL,"); + buf.append("MAPPED_KEY VARCHAR(254) NOT NULL,"); + buf.append("MAPPED_VALUE LONGVARCHAR,"); + buf.append("PRIMARY KEY(EVENT_ID, MAPPED_KEY),"); + buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); + query(conn, buf.toString()); + + buf = new StringBuilder(); + buf.append("CREATE TABLE LOGGING_EVENT_EXCEPTION ("); + buf.append("EVENT_ID BIGINT NOT NULL,"); + buf.append("I SMALLINT NOT NULL,"); + buf.append("TRACE_LINE VARCHAR(256) NOT NULL,"); + buf.append("PRIMARY KEY(EVENT_ID, I),"); + buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); + query(conn, buf.toString()); } - createTables(); - } - public void tearDown() throws SQLException { - dropTables(); + private void dropTables() throws SQLException { + Connection conn = newConnection(); + StringBuilder buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT_EXCEPTION IF EXISTS;"); + query(conn, buf.toString()); - if (mode == HsqlMode.MEM) { - server.stop(); - server = null; + buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT_PROPERTY IF EXISTS;"); + query(conn, buf.toString()); + + buf = new StringBuilder(); + buf.append("DROP TABLE LOGGING_EVENT IF EXISTS;"); + query(conn, buf.toString()); } - } - - Connection newConnection() throws SQLException { - jdbcDriver driver = new jdbcDriver(); - Properties props = new Properties(); - props.setProperty("user", user); - props.setProperty("password", password); - return driver.connect(url, props); - - // return DriverManager.getConnection(url, user, password); - } - - private void createTables() throws SQLException { - Connection conn = newConnection(); - assertNotNull(conn); - StringBuilder buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT ("); - buf.append("TIMESTMP BIGINT NOT NULL,"); - buf.append("FORMATTED_MESSAGE LONGVARCHAR NOT NULL,"); - buf.append("LOGGER_NAME VARCHAR(256) NOT NULL,"); - buf.append("LEVEL_STRING VARCHAR(256) NOT NULL,"); - buf.append("THREAD_NAME VARCHAR(256),"); - buf.append("REFERENCE_FLAG SMALLINT,"); - - buf.append("ARG0 VARCHAR(256),"); - buf.append("ARG1 VARCHAR(256),"); - buf.append("ARG2 VARCHAR(256),"); - buf.append("ARG3 VARCHAR(256),"); - - - buf.append("CALLER_FILENAME VARCHAR(256), "); - buf.append("CALLER_CLASS VARCHAR(256), "); - buf.append("CALLER_METHOD VARCHAR(256), "); - buf.append("CALLER_LINE CHAR(4), "); - buf.append("EVENT_ID BIGINT NOT NULL IDENTITY);"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT_PROPERTY ("); - buf.append("EVENT_ID BIGINT NOT NULL,"); - buf.append("MAPPED_KEY VARCHAR(254) NOT NULL,"); - buf.append("MAPPED_VALUE LONGVARCHAR,"); - buf.append("PRIMARY KEY(EVENT_ID, MAPPED_KEY),"); - buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("CREATE TABLE LOGGING_EVENT_EXCEPTION ("); - buf.append("EVENT_ID BIGINT NOT NULL,"); - buf.append("I SMALLINT NOT NULL,"); - buf.append("TRACE_LINE VARCHAR(256) NOT NULL,"); - buf.append("PRIMARY KEY(EVENT_ID, I),"); - buf.append("FOREIGN KEY (EVENT_ID) REFERENCES LOGGING_EVENT(EVENT_ID));"); - query(conn, buf.toString()); - } - - private void dropTables() throws SQLException { - Connection conn = newConnection(); - StringBuilder buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT_EXCEPTION IF EXISTS;"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT_PROPERTY IF EXISTS;"); - query(conn, buf.toString()); - - buf = new StringBuilder(); - buf.append("DROP TABLE LOGGING_EVENT IF EXISTS;"); - query(conn, buf.toString()); - } - - private void query(Connection conn, String expression) throws SQLException { - - Statement st = null; - st = conn.createStatement(); - int i = st.executeUpdate(expression); - if (i == -1) { - System.out.println("db error : " + expression); + + private void query(Connection conn, String expression) throws SQLException { + + Statement st = null; + st = conn.createStatement(); + int i = st.executeUpdate(expression); + if (i == -1) { + System.out.println("db error : " + expression); + } + st.close(); } - st.close(); - } - public enum HsqlMode { - MEM, FILE, NET; - } + public enum HsqlMode { + MEM, FILE, NET; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderIntegrationTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderIntegrationTest.java index 72ff4ebdc3296389b2f92ce9be05ce5365bd207d..7e9db2476d468b61640952093d30254bb5f633f0 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderIntegrationTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/DBAppenderIntegrationTest.java @@ -37,207 +37,199 @@ import static org.junit.Assert.*; public class DBAppenderIntegrationTest { - static String LOCAL_HOST_NAME; - static String[] CONFORMING_HOST_LIST = new String[] { "Orion" }; - static String[] POSTGRES_CONFORMING_HOST_LIST = new String[] { "haro" }; - static String[] MYSQL_CONFORMING_HOST_LIST = new String[] { "xharo" }; - static String[] ORACLE_CONFORMING_HOST_LIST = new String[] { "xharo" }; - - int diff = RandomUtil.getPositiveInt(); - LoggerContext lc = new LoggerContext(); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - InetAddress localhostIA = InetAddress.getLocalHost(); - LOCAL_HOST_NAME = localhostIA.getHostName(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - lc.setName("lc" + diff); - } - - @After - public void tearDown() throws Exception { - // lc will never be used again - lc.stop(); - } - - DriverManagerConnectionSource getConnectionSource() { - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) lc - .getLogger(Logger.ROOT_LOGGER_NAME); - - DBAppender dbAppender = (DBAppender) root.getAppender("DB"); - assertNotNull(dbAppender); - return (DriverManagerConnectionSource) dbAppender.getConnectionSource(); - - } - - public void doTest(String configFile) throws JoranException, SQLException { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - - Logger logger = lc.getLogger(DBAppenderIntegrationTest.class); - - // the key userid is used in SiftingAppender test - // suffix with diff to avoid collision - MDC.put("userid"+diff, "user" + diff); - int runLength = 5; - for (int i = 1; i <= runLength; i++) { - logger.debug("This is a debug message. Message number: " + (diff + i)); - } - - Exception e = new Exception("Just testing", getCause()); - logger.error("At last an error.", e); - - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - long lastEventId = getLastEventId(); - verify(lastEventId); - - // check that there were no errors - StatusChecker checker = new StatusChecker(lc); - checker.assertIsErrorFree(); - } - - long getLastEventId() throws SQLException { - DriverManagerConnectionSource cs = getConnectionSource(); - - Connection con = cs.getConnection(); - Statement statement = con.createStatement(); - statement.setMaxRows(1); - ResultSet rs = statement - .executeQuery("select event_id from logging_event order by event_id desc"); - rs.next(); - long eventId = rs.getLong(1); - rs.close(); - statement.close(); - return eventId; - } - - void verify(long lastEventId) throws SQLException { - verifyDebugMsg(lastEventId); - verifyException(lastEventId); - verifyProperty(lastEventId); - - } - - void verifyDebugMsg(long lastEventId) throws SQLException { - DriverManagerConnectionSource cs = getConnectionSource(); - Connection con = cs.getConnection(); - Statement statement = con.createStatement(); - ResultSet rs = statement - .executeQuery("select formatted_message from logging_event where event_id='" - + (lastEventId - 1) + "'"); - rs.next(); - String msg = rs.getString(1); - assertEquals("This is a debug message. Message number: " + (diff + 5), msg); - } - - @SuppressWarnings("unchecked") - void verifyProperty(long lastEventId) throws SQLException { - DriverManagerConnectionSource cs = getConnectionSource(); - Connection con = cs.getConnection(); - Statement statement = con.createStatement(); - ResultSet rs = statement - .executeQuery("select mapped_key, mapped_value from logging_event_property where event_id='" - + (lastEventId - 1) + "'"); - - Map witness = lc.getCopyOfPropertyMap(); - witness.putAll(MDC.getCopyOfContextMap()); - - Map map = new HashMap(); - while (rs.next()) { - String key = rs.getString(1); - String val = rs.getString(2); - map.put(key, val); - } - - assertEquals(witness, map); - } - - void verifyException(long lastEventId) throws SQLException { - DriverManagerConnectionSource cs = getConnectionSource(); - Connection con = cs.getConnection(); - Statement statement = con.createStatement(); - ResultSet rs = statement - .executeQuery("select trace_line from logging_event_exception where event_id='" - + (lastEventId) + "' AND I='0'"); - rs.next(); - String traceLine = rs.getString(1); - assertEquals("java.lang.Exception: Just testing", traceLine); - } - - Throwable getCause() { - return new IllegalStateException("test cause"); - } - - static boolean isConformingHostAndJDK16OrHigher(String[] conformingHostList) { - if (!EnvUtil.isJDK6OrHigher()) { - return false; - } - for (String conformingHost : conformingHostList) { - if (conformingHost.equalsIgnoreCase(LOCAL_HOST_NAME)) { - return true; - } - } - return false; - } - - static boolean isConformingHostAndJDK16OrHigher() { - return isConformingHostAndJDK16OrHigher(CONFORMING_HOST_LIST); - } - - @Test - public void sqlserver() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; - } - doTest("src/test/input/integration/db/sqlserver-with-driver.xml"); - } - - @Test - public void oracle10g() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher(ORACLE_CONFORMING_HOST_LIST)) { - return; - } - doTest("src/test/input/integration/db/oracle10g-with-driver.xml"); - } - - @Test - @Ignore - public void oracle11g() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher()) { - return; - } - doTest("src/test/input/integration/db/oracle11g-with-driver.xml"); - } - - @Test - public void mysql() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher(MYSQL_CONFORMING_HOST_LIST)) { - return; - } - doTest("src/test/input/integration/db/mysql-with-driver.xml"); - } - - @Test - public void postgres() throws Exception { - // perform test only on conforming hosts - if (!isConformingHostAndJDK16OrHigher(POSTGRES_CONFORMING_HOST_LIST)) { - return; - } - System.out.println("running postgres() test"); - doTest("src/test/input/integration/db/postgresql-with-driver.xml"); - } + static String LOCAL_HOST_NAME; + static String[] CONFORMING_HOST_LIST = new String[] { "Orion" }; + static String[] POSTGRES_CONFORMING_HOST_LIST = new String[] { "haro" }; + static String[] MYSQL_CONFORMING_HOST_LIST = new String[] { "xharo" }; + static String[] ORACLE_CONFORMING_HOST_LIST = new String[] { "xharo" }; + + int diff = RandomUtil.getPositiveInt(); + LoggerContext lc = new LoggerContext(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + InetAddress localhostIA = InetAddress.getLocalHost(); + LOCAL_HOST_NAME = localhostIA.getHostName(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + lc.setName("lc" + diff); + } + + @After + public void tearDown() throws Exception { + // lc will never be used again + lc.stop(); + } + + DriverManagerConnectionSource getConnectionSource() { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) lc.getLogger(Logger.ROOT_LOGGER_NAME); + + DBAppender dbAppender = (DBAppender) root.getAppender("DB"); + assertNotNull(dbAppender); + return (DriverManagerConnectionSource) dbAppender.getConnectionSource(); + + } + + public void doTest(String configFile) throws JoranException, SQLException { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + + Logger logger = lc.getLogger(DBAppenderIntegrationTest.class); + + // the key userid is used in SiftingAppender test + // suffix with diff to avoid collision + MDC.put("userid" + diff, "user" + diff); + int runLength = 5; + for (int i = 1; i <= runLength; i++) { + logger.debug("This is a debug message. Message number: " + (diff + i)); + } + + Exception e = new Exception("Just testing", getCause()); + logger.error("At last an error.", e); + + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + + long lastEventId = getLastEventId(); + verify(lastEventId); + + // check that there were no errors + StatusChecker checker = new StatusChecker(lc); + checker.assertIsErrorFree(); + } + + long getLastEventId() throws SQLException { + DriverManagerConnectionSource cs = getConnectionSource(); + + Connection con = cs.getConnection(); + Statement statement = con.createStatement(); + statement.setMaxRows(1); + ResultSet rs = statement.executeQuery("select event_id from logging_event order by event_id desc"); + rs.next(); + long eventId = rs.getLong(1); + rs.close(); + statement.close(); + return eventId; + } + + void verify(long lastEventId) throws SQLException { + verifyDebugMsg(lastEventId); + verifyException(lastEventId); + verifyProperty(lastEventId); + + } + + void verifyDebugMsg(long lastEventId) throws SQLException { + DriverManagerConnectionSource cs = getConnectionSource(); + Connection con = cs.getConnection(); + Statement statement = con.createStatement(); + ResultSet rs = statement.executeQuery("select formatted_message from logging_event where event_id='" + (lastEventId - 1) + "'"); + rs.next(); + String msg = rs.getString(1); + assertEquals("This is a debug message. Message number: " + (diff + 5), msg); + } + + @SuppressWarnings("unchecked") + void verifyProperty(long lastEventId) throws SQLException { + DriverManagerConnectionSource cs = getConnectionSource(); + Connection con = cs.getConnection(); + Statement statement = con.createStatement(); + ResultSet rs = statement.executeQuery("select mapped_key, mapped_value from logging_event_property where event_id='" + (lastEventId - 1) + "'"); + + Map witness = lc.getCopyOfPropertyMap(); + witness.putAll(MDC.getCopyOfContextMap()); + + Map map = new HashMap(); + while (rs.next()) { + String key = rs.getString(1); + String val = rs.getString(2); + map.put(key, val); + } + + assertEquals(witness, map); + } + + void verifyException(long lastEventId) throws SQLException { + DriverManagerConnectionSource cs = getConnectionSource(); + Connection con = cs.getConnection(); + Statement statement = con.createStatement(); + ResultSet rs = statement.executeQuery("select trace_line from logging_event_exception where event_id='" + (lastEventId) + "' AND I='0'"); + rs.next(); + String traceLine = rs.getString(1); + assertEquals("java.lang.Exception: Just testing", traceLine); + } + + Throwable getCause() { + return new IllegalStateException("test cause"); + } + + static boolean isConformingHostAndJDK16OrHigher(String[] conformingHostList) { + if (!EnvUtil.isJDK6OrHigher()) { + return false; + } + for (String conformingHost : conformingHostList) { + if (conformingHost.equalsIgnoreCase(LOCAL_HOST_NAME)) { + return true; + } + } + return false; + } + + static boolean isConformingHostAndJDK16OrHigher() { + return isConformingHostAndJDK16OrHigher(CONFORMING_HOST_LIST); + } + + @Test + public void sqlserver() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/sqlserver-with-driver.xml"); + } + + @Test + public void oracle10g() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher(ORACLE_CONFORMING_HOST_LIST)) { + return; + } + doTest("src/test/input/integration/db/oracle10g-with-driver.xml"); + } + + @Test + @Ignore + public void oracle11g() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher()) { + return; + } + doTest("src/test/input/integration/db/oracle11g-with-driver.xml"); + } + + @Test + public void mysql() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher(MYSQL_CONFORMING_HOST_LIST)) { + return; + } + doTest("src/test/input/integration/db/mysql-with-driver.xml"); + } + + @Test + public void postgres() throws Exception { + // perform test only on conforming hosts + if (!isConformingHostAndJDK16OrHigher(POSTGRES_CONFORMING_HOST_LIST)) { + return; + } + System.out.println("running postgres() test"); + doTest("src/test/input/integration/db/postgresql-with-driver.xml"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/PackageTest.java index 1689f4a1f48a00ccedce7cfe32789b6d41d15d78..abc0a3f1c32cde85e5a0e02c4db4a5d710956a3a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/PackageTest.java @@ -18,8 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { DBAppenderHSQLTest.class, DBAppenderH2Test.class, - DBAppenderIntegrationTest.class, SQLBuilderTest.class, - ch.qos.logback.classic.db.names.PackageTest.class}) +@SuiteClasses({ DBAppenderHSQLTest.class, DBAppenderH2Test.class, DBAppenderIntegrationTest.class, SQLBuilderTest.class, + ch.qos.logback.classic.db.names.PackageTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/SQLBuilderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/SQLBuilderTest.java index 5b4835aedc24e956459c6bfdeba8fbf3dd597373..9637a2aea8e3df2188c289a785c59dd70a2de0ad 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/SQLBuilderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/SQLBuilderTest.java @@ -27,92 +27,91 @@ import ch.qos.logback.classic.db.names.SimpleDBNameResolver; */ public class SQLBuilderTest { - @Test - public void shouldReturnDefaultSqlInsertLoggingEventQuery() throws Exception { - //given - DBNameResolver nameResolver = new DefaultDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertSQL(nameResolver); - - //then - final String expected = "INSERT INTO logging_event (timestmp, formatted_message, logger_name, level_string, thread_name, reference_flag, arg0, arg1, arg2, arg3, caller_filename, caller_class, caller_method, caller_line) VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } - - @Test - public void shouldReturnDefaultSqlInsertExceptionQuery() throws Exception { - //given - DBNameResolver nameResolver = new DefaultDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertExceptionSQL(nameResolver); - - //then - final String expected = "INSERT INTO logging_event_exception (event_id, i, trace_line) VALUES (?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } - - @Test - public void shouldReturnDefaultSqlInsertLoggingPropertyQuery() throws Exception { - //given - DBNameResolver nameResolver = new DefaultDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertPropertiesSQL(nameResolver); - - //then - final String expected = "INSERT INTO logging_event_property (event_id, mapped_key, mapped_value) VALUES (?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } - - - private DBNameResolver createSimpleDBNameResolver() { - final SimpleDBNameResolver nameResolver = new SimpleDBNameResolver(); - nameResolver.setTableNamePrefix("tp_"); - nameResolver.setTableNameSuffix("_ts"); - nameResolver.setColumnNamePrefix("cp_"); - nameResolver.setColumnNameSuffix("_cs"); - return nameResolver; - } - - @Test - public void shouldReturnSimpleSqlInsertLoggingEventQuery() throws Exception { - //given - DBNameResolver nameResolver = createSimpleDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertSQL(nameResolver); - - //then - final String expected = "INSERT INTO tp_logging_event_ts (cp_timestmp_cs, cp_formatted_message_cs, cp_logger_name_cs, cp_level_string_cs, cp_thread_name_cs, cp_reference_flag_cs, cp_arg0_cs, cp_arg1_cs, cp_arg2_cs, cp_arg3_cs, cp_caller_filename_cs, cp_caller_class_cs, cp_caller_method_cs, cp_caller_line_cs) VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } - - @Test - public void shouldReturnSimpleSqlInsertExceptionQuery() throws Exception { - //given - DBNameResolver nameResolver = createSimpleDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertExceptionSQL(nameResolver); - - //then - final String expected = "INSERT INTO tp_logging_event_exception_ts (cp_event_id_cs, cp_i_cs, cp_trace_line_cs) VALUES (?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } - - @Test - public void shouldReturnSimpleSqlInsertLoggingPropertyQuery() throws Exception { - //given - DBNameResolver nameResolver = createSimpleDBNameResolver(); - - //when - String sql = SQLBuilder.buildInsertPropertiesSQL(nameResolver); - - //then - final String expected = "INSERT INTO tp_logging_event_property_ts (cp_event_id_cs, cp_mapped_key_cs, cp_mapped_value_cs) VALUES (?, ?, ?)"; - assertThat(sql).isEqualTo(expected); - } + @Test + public void shouldReturnDefaultSqlInsertLoggingEventQuery() throws Exception { + // given + DBNameResolver nameResolver = new DefaultDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertSQL(nameResolver); + + // then + final String expected = "INSERT INTO logging_event (timestmp, formatted_message, logger_name, level_string, thread_name, reference_flag, arg0, arg1, arg2, arg3, caller_filename, caller_class, caller_method, caller_line) VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } + + @Test + public void shouldReturnDefaultSqlInsertExceptionQuery() throws Exception { + // given + DBNameResolver nameResolver = new DefaultDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertExceptionSQL(nameResolver); + + // then + final String expected = "INSERT INTO logging_event_exception (event_id, i, trace_line) VALUES (?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } + + @Test + public void shouldReturnDefaultSqlInsertLoggingPropertyQuery() throws Exception { + // given + DBNameResolver nameResolver = new DefaultDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertPropertiesSQL(nameResolver); + + // then + final String expected = "INSERT INTO logging_event_property (event_id, mapped_key, mapped_value) VALUES (?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } + + private DBNameResolver createSimpleDBNameResolver() { + final SimpleDBNameResolver nameResolver = new SimpleDBNameResolver(); + nameResolver.setTableNamePrefix("tp_"); + nameResolver.setTableNameSuffix("_ts"); + nameResolver.setColumnNamePrefix("cp_"); + nameResolver.setColumnNameSuffix("_cs"); + return nameResolver; + } + + @Test + public void shouldReturnSimpleSqlInsertLoggingEventQuery() throws Exception { + // given + DBNameResolver nameResolver = createSimpleDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertSQL(nameResolver); + + // then + final String expected = "INSERT INTO tp_logging_event_ts (cp_timestmp_cs, cp_formatted_message_cs, cp_logger_name_cs, cp_level_string_cs, cp_thread_name_cs, cp_reference_flag_cs, cp_arg0_cs, cp_arg1_cs, cp_arg2_cs, cp_arg3_cs, cp_caller_filename_cs, cp_caller_class_cs, cp_caller_method_cs, cp_caller_line_cs) VALUES (?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } + + @Test + public void shouldReturnSimpleSqlInsertExceptionQuery() throws Exception { + // given + DBNameResolver nameResolver = createSimpleDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertExceptionSQL(nameResolver); + + // then + final String expected = "INSERT INTO tp_logging_event_exception_ts (cp_event_id_cs, cp_i_cs, cp_trace_line_cs) VALUES (?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } + + @Test + public void shouldReturnSimpleSqlInsertLoggingPropertyQuery() throws Exception { + // given + DBNameResolver nameResolver = createSimpleDBNameResolver(); + + // when + String sql = SQLBuilder.buildInsertPropertiesSQL(nameResolver); + + // then + final String expected = "INSERT INTO tp_logging_event_property_ts (cp_event_id_cs, cp_mapped_key_cs, cp_mapped_value_cs) VALUES (?, ?, ?)"; + assertThat(sql).isEqualTo(expected); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/DefaultDBNameResolverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/DefaultDBNameResolverTest.java index 23080ecac2fd0737c2279757453ed5ed34add40f..ca01480fd1bf437499aabbf7751fb72f4c35922f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/DefaultDBNameResolverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/DefaultDBNameResolverTest.java @@ -24,47 +24,47 @@ import static org.fest.assertions.Assertions.assertThat; */ public class DefaultDBNameResolverTest { - private DefaultDBNameResolver resolver; + private DefaultDBNameResolver resolver; - @Before - public void setUp() throws Exception { - resolver = new DefaultDBNameResolver(); - } + @Before + public void setUp() throws Exception { + resolver = new DefaultDBNameResolver(); + } - @Test - public void testGetLoggingEventColumnName() throws Exception { - //when - String columnName = resolver.getColumnName(ColumnName.LOGGER_NAME); + @Test + public void testGetLoggingEventColumnName() throws Exception { + // when + String columnName = resolver.getColumnName(ColumnName.LOGGER_NAME); - //then - assertThat(columnName).isEqualTo("logger_name"); - } + // then + assertThat(columnName).isEqualTo("logger_name"); + } - @Test - public void testGetLoggingEventPropertyColumnName() throws Exception { - //when - String columnName = resolver.getColumnName(ColumnName.MAPPED_KEY); + @Test + public void testGetLoggingEventPropertyColumnName() throws Exception { + // when + String columnName = resolver.getColumnName(ColumnName.MAPPED_KEY); - //then - assertThat(columnName).isEqualTo("mapped_key"); - } + // then + assertThat(columnName).isEqualTo("mapped_key"); + } - @Test - public void testGetLoggingEventExceptionColumnName() throws Exception { - //when - String columnName = resolver.getColumnName(ColumnName.TRACE_LINE); + @Test + public void testGetLoggingEventExceptionColumnName() throws Exception { + // when + String columnName = resolver.getColumnName(ColumnName.TRACE_LINE); - //then - assertThat(columnName).isEqualTo("trace_line"); - } + // then + assertThat(columnName).isEqualTo("trace_line"); + } - @Test - public void testGetTableName() throws Exception { - //when - String tableName = resolver.getTableName(TableName.LOGGING_EVENT_EXCEPTION); + @Test + public void testGetTableName() throws Exception { + // when + String tableName = resolver.getTableName(TableName.LOGGING_EVENT_EXCEPTION); - //then - assertThat(tableName).isEqualTo("logging_event_exception"); - } + // then + assertThat(tableName).isEqualTo("logging_event_exception"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/PackageTest.java index 3a2693f109f2d4da27f4d3606d16fc5b409e8f18..4ef7120c5cac178d9bc3e37f34d6f03851686f06 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/PackageTest.java @@ -18,7 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { DefaultDBNameResolverTest.class, - SimpleDBNameResolverTest.class }) +@SuiteClasses({ DefaultDBNameResolverTest.class, SimpleDBNameResolverTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/SimpleDBNameResolverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/SimpleDBNameResolverTest.java index bb2416e280852e619f0f90ba22f3605c5cda886f..28f78205b2b7f17fc2025abbbb17645a0dac75f3 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/db/names/SimpleDBNameResolverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/db/names/SimpleDBNameResolverTest.java @@ -24,118 +24,119 @@ import static org.fest.assertions.Assertions.assertThat; */ public class SimpleDBNameResolverTest { - private SimpleDBNameResolver nameResolver; - - @Before - public void setUp() throws Exception { - nameResolver = new SimpleDBNameResolver(); - /*nameResolver.setTableNameSuffix("_ts"); - nameResolver.setColumnNamePrefix("cp_"); - nameResolver.setColumnNameSuffix("_cs");*/ - } - - @Test - public void shouldReturnTableNameWithPrefix() throws Exception { - //given - - //when - nameResolver.setTableNamePrefix("tp_"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); - } - - @Test - public void shouldReturnTableNameWithSuffix() throws Exception { - //given - - //when - nameResolver.setTableNameSuffix("_ts"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event_ts"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); - } - - @Test - public void shouldReturnTableNameWithBothPrefixAndSuffix() throws Exception { - //given - - //when - nameResolver.setTableNamePrefix("tp_"); - nameResolver.setTableNameSuffix("_ts"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event_ts"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); - } - - @Test - public void shouldReturnColumnNameWithPrefix() throws Exception { - //given - - //when - nameResolver.setColumnNamePrefix("cp_"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name"); - } - - @Test - public void shouldReturnColumnNameWithSuffix() throws Exception { - //given - - //when - nameResolver.setColumnNameSuffix("_cs"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name_cs"); - } - - @Test - public void shouldReturnColumnNameWithBothPrefixAndSuffix() throws Exception { - //given - - //when - nameResolver.setColumnNamePrefix("cp_"); - nameResolver.setColumnNameSuffix("_cs"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name_cs"); - } - - @Test - public void shouldReturnTableAndColumnNamesWithBothPrefixAndSuffix() throws Exception { - //given - - //when - nameResolver.setTableNamePrefix("tp_"); - nameResolver.setTableNameSuffix("_ts"); - nameResolver.setColumnNamePrefix("cp_"); - nameResolver.setColumnNameSuffix("_cs"); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event_ts"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name_cs"); - } - - @Test - public void shouldHandleNullsAsEmptyStrings() throws Exception { - //given - - //when - nameResolver.setTableNamePrefix(null); - nameResolver.setTableNameSuffix(null); - nameResolver.setColumnNamePrefix(null); - nameResolver.setColumnNameSuffix(null); - - //then - assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); - assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); - } + private SimpleDBNameResolver nameResolver; + + @Before + public void setUp() throws Exception { + nameResolver = new SimpleDBNameResolver(); + /* + * nameResolver.setTableNameSuffix("_ts"); nameResolver.setColumnNamePrefix("cp_"); + * nameResolver.setColumnNameSuffix("_cs"); + */ + } + + @Test + public void shouldReturnTableNameWithPrefix() throws Exception { + // given + + // when + nameResolver.setTableNamePrefix("tp_"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); + } + + @Test + public void shouldReturnTableNameWithSuffix() throws Exception { + // given + + // when + nameResolver.setTableNameSuffix("_ts"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event_ts"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); + } + + @Test + public void shouldReturnTableNameWithBothPrefixAndSuffix() throws Exception { + // given + + // when + nameResolver.setTableNamePrefix("tp_"); + nameResolver.setTableNameSuffix("_ts"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event_ts"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); + } + + @Test + public void shouldReturnColumnNameWithPrefix() throws Exception { + // given + + // when + nameResolver.setColumnNamePrefix("cp_"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name"); + } + + @Test + public void shouldReturnColumnNameWithSuffix() throws Exception { + // given + + // when + nameResolver.setColumnNameSuffix("_cs"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name_cs"); + } + + @Test + public void shouldReturnColumnNameWithBothPrefixAndSuffix() throws Exception { + // given + + // when + nameResolver.setColumnNamePrefix("cp_"); + nameResolver.setColumnNameSuffix("_cs"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name_cs"); + } + + @Test + public void shouldReturnTableAndColumnNamesWithBothPrefixAndSuffix() throws Exception { + // given + + // when + nameResolver.setTableNamePrefix("tp_"); + nameResolver.setTableNameSuffix("_ts"); + nameResolver.setColumnNamePrefix("cp_"); + nameResolver.setColumnNameSuffix("_cs"); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("tp_logging_event_ts"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("cp_thread_name_cs"); + } + + @Test + public void shouldHandleNullsAsEmptyStrings() throws Exception { + // given + + // when + nameResolver.setTableNamePrefix(null); + nameResolver.setTableNameSuffix(null); + nameResolver.setColumnNamePrefix(null); + nameResolver.setColumnNameSuffix(null); + + // then + assertThat(nameResolver.getTableName(TableName.LOGGING_EVENT)).isEqualTo("logging_event"); + assertThat(nameResolver.getColumnName(ColumnName.THREAD_NAME)).isEqualTo("thread_name"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/LayoutInsteadOfEncoderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/LayoutInsteadOfEncoderTest.java index 785bf0c2f2992b2a56789cf8b390170a52d38d8c..643a7881690f9f8cfd8749eab88405908c2f8d9b 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/LayoutInsteadOfEncoderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/LayoutInsteadOfEncoderTest.java @@ -33,30 +33,29 @@ import ch.qos.logback.core.util.StatusPrinter; public class LayoutInsteadOfEncoderTest { - // TeztConstants.TEST_SRC_PREFIX + "input/joran/ignore.xml" - JoranConfigurator jc = new JoranConfigurator(); - LoggerContext loggerContext = new LoggerContext(); - - @Before - public void setUp() { - jc.setContext(loggerContext); - - } - - // jc.doConfigure(TeztConstants.TEST_SRC_PREFIX + "input/joran/ignore.xml"); - - @Test - public void layoutInsteadOfEncoer() throws JoranException { - jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "compatibility/layoutInsteadOfEncoder.xml"); - StatusPrinter.print(loggerContext); - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertContainsMatch(Status.WARN, "This appender no longer admits a layout as a sub-component"); - checker.assertContainsMatch(Status.WARN, "See also "+CODES_URL+"#layoutInsteadOfEncoder for details"); - - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - FileAppender fileAppender = (FileAppender) root.getAppender("LIOE"); - assertTrue(fileAppender.isStarted()); - assertTrue(fileAppender.getEncoder() instanceof LayoutWrappingEncoder); - } + // TeztConstants.TEST_SRC_PREFIX + "input/joran/ignore.xml" + JoranConfigurator jc = new JoranConfigurator(); + LoggerContext loggerContext = new LoggerContext(); + + @Before + public void setUp() { + jc.setContext(loggerContext); + + } + + // jc.doConfigure(TeztConstants.TEST_SRC_PREFIX + "input/joran/ignore.xml"); + + @Test + public void layoutInsteadOfEncoer() throws JoranException { + jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "compatibility/layoutInsteadOfEncoder.xml"); + StatusPrinter.print(loggerContext); + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertContainsMatch(Status.WARN, "This appender no longer admits a layout as a sub-component"); + checker.assertContainsMatch(Status.WARN, "See also " + CODES_URL + "#layoutInsteadOfEncoder for details"); + + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + FileAppender fileAppender = (FileAppender) root.getAppender("LIOE"); + assertTrue(fileAppender.isStarted()); + assertTrue(fileAppender.getEncoder() instanceof LayoutWrappingEncoder); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PackageTest.java index 20aaf930a8b59223d19ab3f3dc1e2e5f03ca7866..9f1cdddf3092612bf5c59c43a11d79b1e76bab4f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { PatternLayoutEncoderTest.class, LayoutInsteadOfEncoderTest.class}) +@SuiteClasses({ PatternLayoutEncoderTest.class, LayoutInsteadOfEncoderTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PatternLayoutEncoderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PatternLayoutEncoderTest.java index 56e2b97ff810463f6105007ca304f6de4fbb08f1..8a027a7a03fbb690474217de7200f5b942f00afc 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PatternLayoutEncoderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/encoder/PatternLayoutEncoderTest.java @@ -31,47 +31,47 @@ import ch.qos.logback.classic.spi.LoggingEvent; public class PatternLayoutEncoderTest { - PatternLayoutEncoder ple = new PatternLayoutEncoder(); - LoggerContext context = new LoggerContext(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Logger logger = context.getLogger(PatternLayoutEncoderTest.class); - Charset utf8Charset = Charset.forName("UTF-8"); - - @Before - public void setUp() { - ple.setPattern("%m"); - ple.setContext(context); - } + PatternLayoutEncoder ple = new PatternLayoutEncoder(); + LoggerContext context = new LoggerContext(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Logger logger = context.getLogger(PatternLayoutEncoderTest.class); + Charset utf8Charset = Charset.forName("UTF-8"); - ILoggingEvent makeLoggingEvent(String message) { - return new LoggingEvent("", logger, Level.DEBUG, message, null, null); - } + @Before + public void setUp() { + ple.setPattern("%m"); + ple.setContext(context); + } - @Test - public void smoke() throws IOException { - init(baos); - String msg = "hello"; - ILoggingEvent event = makeLoggingEvent(msg); - ple.doEncode(event); - ple.close(); - assertEquals(msg, baos.toString()); - } + ILoggingEvent makeLoggingEvent(String message) { + return new LoggingEvent("", logger, Level.DEBUG, message, null, null); + } - void init(ByteArrayOutputStream baos) throws IOException { - ple.start(); - ((PatternLayout) ple.getLayout()).setOutputPatternAsHeader(false); - ple.init(baos); - } + @Test + public void smoke() throws IOException { + init(baos); + String msg = "hello"; + ILoggingEvent event = makeLoggingEvent(msg); + ple.doEncode(event); + ple.close(); + assertEquals(msg, baos.toString()); + } - @Test - public void charset() throws IOException { - ple.setCharset(utf8Charset); - init(baos); - String msg = "\u03b1"; - ILoggingEvent event = makeLoggingEvent(msg); - ple.doEncode(event); - ple.close(); - assertEquals(msg, new String(baos.toByteArray(), utf8Charset.name())); - } + void init(ByteArrayOutputStream baos) throws IOException { + ple.start(); + ((PatternLayout) ple.getLayout()).setOutputPatternAsHeader(false); + ple.init(baos); + } + + @Test + public void charset() throws IOException { + ple.setCharset(utf8Charset); + init(baos); + String msg = "\u03b1"; + ILoggingEvent event = makeLoggingEvent(msg); + ple.doEncode(event); + ple.close(); + assertEquals(msg, new String(baos.toByteArray(), utf8Charset.name())); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/html/HTMLLayoutTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/html/HTMLLayoutTest.java index 9e77cd57bf5364d9eed4b5c635f01cc5939790a0..c5ebe8f961c161c94a5d0a0598534eb4e0a5e2d5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/html/HTMLLayoutTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/html/HTMLLayoutTest.java @@ -47,205 +47,197 @@ import ch.qos.logback.core.util.StatusPrinter; public class HTMLLayoutTest { - LoggerContext lc; - Logger root; - HTMLLayout layout; - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName("default"); - - layout = new HTMLLayout(); - layout.setThrowableRenderer(new DefaultThrowableRenderer()); - layout.setContext(lc); - layout.setPattern("%level%thread%msg"); - layout.start(); - - root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - - } - - @After - public void tearDown() throws Exception { - lc = null; - layout = null; - } - - @Test - public void testHeader() throws Exception { - String header = layout.getFileHeader(); - // System.out.println(header); - - Document doc = parseOutput(header + ""); - Element rootElement = doc.getRootElement(); - assertNotNull(rootElement.element("body")); - } - - @SuppressWarnings("unchecked") - @Test - public void testPresentationHeader() throws Exception { - String header = layout.getFileHeader(); - String presentationHeader = layout.getPresentationHeader(); - header = header + presentationHeader; - // System.out.println(header); - - Document doc = parseOutput(header + ""); - Element rootElement = doc.getRootElement(); - Element bodyElement = rootElement.element("body"); - Element tableElement = bodyElement.element("table"); - Element trElement = tableElement.element("tr"); - List elementList = trElement.elements(); - assertEquals("Level", elementList.get(0).getText()); - assertEquals("Thread", elementList.get(1).getText()); - assertEquals("Message", elementList.get(2).getText()); - } - - @Test - public void testAppendThrowable() throws Exception { - StringBuilder buf = new StringBuilder(); - DummyThrowableProxy tp = new DummyThrowableProxy(); - tp.setClassName("test1"); - tp.setMessage("msg1"); - - StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); - StackTraceElement ste2 = new StackTraceElement("c2", "m2", "f2", 2); - - StackTraceElementProxy[] stepArray = { new StackTraceElementProxy(ste1), - new StackTraceElementProxy(ste2) }; - tp.setStackTraceElementProxyArray(stepArray); - DefaultThrowableRenderer renderer = (DefaultThrowableRenderer) layout - .getThrowableRenderer(); - - renderer.render(buf, tp); - System.out.println(buf.toString()); - String[] result = buf.toString().split(CoreConstants.LINE_SEPARATOR); - System.out.println(result[0]); - assertEquals("test1: msg1", result[0]); - assertEquals(DefaultThrowableRenderer.TRACE_PREFIX + "at c1.m1(f1:1)", result[1]); - } - - @Test - public void testDoLayout() throws Exception { - ILoggingEvent le = createLoggingEvent(); - - String result = layout.getFileHeader(); - result += layout.getPresentationHeader(); - result += layout.doLayout(le); - result += layout.getPresentationFooter(); - result += layout.getFileFooter(); - - Document doc = parseOutput(result); - Element rootElement = doc.getRootElement(); - rootElement.toString(); - - // the rest of this test is very dependent of the output generated - // by HTMLLayout. Given that the XML parser already verifies - // that the result conforms to xhtml-strict, we may want to - // skip the assertions below. However, the assertions below are another - // *independent* way to check the output format. - - // head, body - assertEquals(2, rootElement.elements().size()); - Element bodyElement = (Element) rootElement.elements().get(1); - Element tableElement = (Element) bodyElement.elements().get(3); - assertEquals("table", tableElement.getName()); - Element trElement = (Element) tableElement.elements().get(1); - { - Element tdElement = (Element) trElement.elements().get(0); - assertEquals("DEBUG", tdElement.getText()); + LoggerContext lc; + Logger root; + HTMLLayout layout; + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + lc.setName("default"); + + layout = new HTMLLayout(); + layout.setThrowableRenderer(new DefaultThrowableRenderer()); + layout.setContext(lc); + layout.setPattern("%level%thread%msg"); + layout.start(); + + root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + + } + + @After + public void tearDown() throws Exception { + lc = null; + layout = null; + } + + @Test + public void testHeader() throws Exception { + String header = layout.getFileHeader(); + // System.out.println(header); + + Document doc = parseOutput(header + ""); + Element rootElement = doc.getRootElement(); + assertNotNull(rootElement.element("body")); + } + + @SuppressWarnings("unchecked") + @Test + public void testPresentationHeader() throws Exception { + String header = layout.getFileHeader(); + String presentationHeader = layout.getPresentationHeader(); + header = header + presentationHeader; + // System.out.println(header); + + Document doc = parseOutput(header + ""); + Element rootElement = doc.getRootElement(); + Element bodyElement = rootElement.element("body"); + Element tableElement = bodyElement.element("table"); + Element trElement = tableElement.element("tr"); + List elementList = trElement.elements(); + assertEquals("Level", elementList.get(0).getText()); + assertEquals("Thread", elementList.get(1).getText()); + assertEquals("Message", elementList.get(2).getText()); + } + + @Test + public void testAppendThrowable() throws Exception { + StringBuilder buf = new StringBuilder(); + DummyThrowableProxy tp = new DummyThrowableProxy(); + tp.setClassName("test1"); + tp.setMessage("msg1"); + + StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); + StackTraceElement ste2 = new StackTraceElement("c2", "m2", "f2", 2); + + StackTraceElementProxy[] stepArray = { new StackTraceElementProxy(ste1), new StackTraceElementProxy(ste2) }; + tp.setStackTraceElementProxyArray(stepArray); + DefaultThrowableRenderer renderer = (DefaultThrowableRenderer) layout.getThrowableRenderer(); + + renderer.render(buf, tp); + System.out.println(buf.toString()); + String[] result = buf.toString().split(CoreConstants.LINE_SEPARATOR); + System.out.println(result[0]); + assertEquals("test1: msg1", result[0]); + assertEquals(DefaultThrowableRenderer.TRACE_PREFIX + "at c1.m1(f1:1)", result[1]); + } + + @Test + public void testDoLayout() throws Exception { + ILoggingEvent le = createLoggingEvent(); + + String result = layout.getFileHeader(); + result += layout.getPresentationHeader(); + result += layout.doLayout(le); + result += layout.getPresentationFooter(); + result += layout.getFileFooter(); + + Document doc = parseOutput(result); + Element rootElement = doc.getRootElement(); + rootElement.toString(); + + // the rest of this test is very dependent of the output generated + // by HTMLLayout. Given that the XML parser already verifies + // that the result conforms to xhtml-strict, we may want to + // skip the assertions below. However, the assertions below are another + // *independent* way to check the output format. + + // head, body + assertEquals(2, rootElement.elements().size()); + Element bodyElement = (Element) rootElement.elements().get(1); + Element tableElement = (Element) bodyElement.elements().get(3); + assertEquals("table", tableElement.getName()); + Element trElement = (Element) tableElement.elements().get(1); + { + Element tdElement = (Element) trElement.elements().get(0); + assertEquals("DEBUG", tdElement.getText()); + } + { + Element tdElement = (Element) trElement.elements().get(1); + String regex = ClassicTestConstants.NAKED_MAIN_REGEX; + System.out.println(tdElement.getText()); + assertTrue(tdElement.getText().matches(regex)); + } + { + Element tdElement = (Element) trElement.elements().get(2); + assertEquals("test message", tdElement.getText()); + } + } + + @SuppressWarnings("unchecked") + @Test + public void layoutWithException() throws Exception { + layout.setPattern("%level %thread %msg %ex"); + LoggingEvent le = createLoggingEvent(); + le.setThrowableProxy(new ThrowableProxy(new Exception("test Exception"))); + String result = layout.doLayout(le); + + String stringToParse = layout.getFileHeader(); + stringToParse = stringToParse + layout.getPresentationHeader(); + stringToParse += result; + stringToParse += ""; + + // System.out.println(stringToParse); + + Document doc = parseOutput(stringToParse); + Element rootElement = doc.getRootElement(); + Element bodyElement = rootElement.element("body"); + Element tableElement = bodyElement.element("table"); + List trElementList = tableElement.elements(); + Element exceptionRowElement = trElementList.get(2); + Element exceptionElement = exceptionRowElement.element("td"); + + assertEquals(3, tableElement.elements().size()); + assertTrue(exceptionElement.getText().contains("java.lang.Exception: test Exception")); + } + + @Test + @Ignore + public void rawLimit() throws Exception { + StringBuilder sb = new StringBuilder(); + String header = layout.getFileHeader(); + assertTrue(header.startsWith("")); + sb.append(header); + sb.append(layout.getPresentationHeader()); + for (int i = 0; i < CoreConstants.TABLE_ROW_LIMIT * 3; i++) { + sb.append(layout.doLayout(new LoggingEvent(this.getClass().getName(), root, Level.DEBUG, "test message" + i, null, null))); + } + sb.append(layout.getPresentationFooter()); + sb.append(layout.getFileFooter()); + // check that the output adheres to xhtml-strict.dtd + parseOutput(sb.toString()); + } + + private LoggingEvent createLoggingEvent() { + return new LoggingEvent(this.getClass().getName(), root, Level.DEBUG, "test message", null, null); } - { - Element tdElement = (Element) trElement.elements().get(1); - String regex = ClassicTestConstants.NAKED_MAIN_REGEX; - System.out.println(tdElement.getText()); - assertTrue(tdElement.getText().matches(regex)); + + Document parseOutput(String output) throws Exception { + EntityResolver resolver = new XHTMLEntityResolver(); + SAXReader reader = new SAXReader(); + reader.setValidation(true); + reader.setEntityResolver(resolver); + return reader.read(new ByteArrayInputStream(output.getBytes())); } - { - Element tdElement = (Element) trElement.elements().get(2); - assertEquals("test message", tdElement.getText()); + + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(lc); + jc.doConfigure(file); } - } - - @SuppressWarnings("unchecked") - @Test - public void layoutWithException() throws Exception { - layout.setPattern("%level %thread %msg %ex"); - LoggingEvent le = createLoggingEvent(); - le.setThrowableProxy(new ThrowableProxy(new Exception("test Exception"))); - String result = layout.doLayout(le); - - String stringToParse = layout.getFileHeader(); - stringToParse = stringToParse + layout.getPresentationHeader(); - stringToParse += result; - stringToParse += ""; - - // System.out.println(stringToParse); - - Document doc = parseOutput(stringToParse); - Element rootElement = doc.getRootElement(); - Element bodyElement = rootElement.element("body"); - Element tableElement = bodyElement.element("table"); - List trElementList = tableElement.elements(); - Element exceptionRowElement = trElementList.get(2); - Element exceptionElement = exceptionRowElement.element("td"); - - assertEquals(3, tableElement.elements().size()); - assertTrue(exceptionElement.getText().contains( - "java.lang.Exception: test Exception")); - } - - @Test - @Ignore - public void rawLimit() throws Exception { - StringBuilder sb = new StringBuilder(); - String header = layout.getFileHeader(); - assertTrue(header - .startsWith("")); - sb.append(header); - sb.append(layout.getPresentationHeader()); - for (int i = 0; i < CoreConstants.TABLE_ROW_LIMIT * 3; i++) { - sb.append(layout.doLayout(new LoggingEvent(this.getClass().getName(), - root, Level.DEBUG, "test message" + i, null, null))); + + @Test + public void testConversionRuleSupportInHtmlLayout() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "conversionRule/htmlLayout0.xml"); + + root.getAppender("LIST"); + String msg = "Simon says"; + root.debug(msg); + StringListAppender sla = (StringListAppender) root.getAppender("LIST"); + assertNotNull(sla); + StatusPrinter.print(lc); + assertEquals(1, sla.strList.size()); + assertFalse(sla.strList.get(0).contains("PARSER_ERROR")); } - sb.append(layout.getPresentationFooter()); - sb.append(layout.getFileFooter()); - // check that the output adheres to xhtml-strict.dtd - parseOutput(sb.toString()); - } - - private LoggingEvent createLoggingEvent() { - return new LoggingEvent(this.getClass().getName(), root, - Level.DEBUG, "test message", null, null); - } - - Document parseOutput(String output) throws Exception { - EntityResolver resolver = new XHTMLEntityResolver(); - SAXReader reader = new SAXReader(); - reader.setValidation(true); - reader.setEntityResolver(resolver); - return reader.read(new ByteArrayInputStream(output.getBytes())); - } - - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(lc); - jc.doConfigure(file); - } - - @Test - public void testConversionRuleSupportInHtmlLayout() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "conversionRule/htmlLayout0.xml"); - - root.getAppender("LIST"); - String msg = "Simon says"; - root.debug(msg); - StringListAppender sla = (StringListAppender) root - .getAppender("LIST"); - assertNotNull(sla); - StatusPrinter.print(lc); - assertEquals(1, sla.strList.size()); - assertFalse(sla.strList.get(0).contains("PARSER_ERROR")); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/html/XHTMLEntityResolver.java b/logback-classic/src/test/java/ch/qos/logback/classic/html/XHTMLEntityResolver.java index 5eec02f9a63c4839dd03caaf632a5f6cd9cec9b8..0b00af689358b48b23340cb4c466fbcc6b9bb086 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/html/XHTMLEntityResolver.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/html/XHTMLEntityResolver.java @@ -22,35 +22,30 @@ import org.xml.sax.InputSource; public class XHTMLEntityResolver implements EntityResolver { - // key: public id, value: relative path to DTD file - static Map entityMap = new HashMap(); + // key: public id, value: relative path to DTD file + static Map entityMap = new HashMap(); - static { - entityMap.put("-//W3C//DTD XHTML 1.0 Strict//EN", - "/dtd/xhtml1-strict.dtd"); - entityMap.put("-//W3C//ENTITIES Latin 1 for XHTML//EN", - "/dtd/xhtml-lat1.ent"); - entityMap.put("-//W3C//ENTITIES Symbols for XHTML//EN", - "/dtd/xhtml-symbol.ent"); - entityMap.put("-//W3C//ENTITIES Special for XHTML//EN", - "/dtd/xhtml-special.ent"); - } + static { + entityMap.put("-//W3C//DTD XHTML 1.0 Strict//EN", "/dtd/xhtml1-strict.dtd"); + entityMap.put("-//W3C//ENTITIES Latin 1 for XHTML//EN", "/dtd/xhtml-lat1.ent"); + entityMap.put("-//W3C//ENTITIES Symbols for XHTML//EN", "/dtd/xhtml-symbol.ent"); + entityMap.put("-//W3C//ENTITIES Special for XHTML//EN", "/dtd/xhtml-special.ent"); + } - public InputSource resolveEntity(String publicId, String systemId) { - //System.out.println(publicId); - final String relativePath = (String)entityMap.get(publicId); + public InputSource resolveEntity(String publicId, String systemId) { + // System.out.println(publicId); + final String relativePath = (String) entityMap.get(publicId); - if (relativePath != null) { - Class clazz = getClass(); - InputStream in = - clazz.getResourceAsStream(relativePath); - if (in == null) { - return null; - } else { - return new InputSource(in); - } - } else { - return null; + if (relativePath != null) { + Class clazz = getClass(); + InputStream in = clazz.getResourceAsStream(relativePath); + if (in == null) { + return null; + } else { + return new InputSource(in); + } + } else { + return null; + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/DarioCampagna/Main.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/DarioCampagna/Main.java index 02d1e69503f90d9ab021e5acfac6103ce1be711e..48e56628f7c96355362abbadf845a1672193fc34 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/DarioCampagna/Main.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/DarioCampagna/Main.java @@ -27,18 +27,18 @@ import org.slf4j.cal10n.LocLoggerFactory; import java.util.Locale; public class Main { - public static void main(String[] args) throws JoranException { + public static void main(String[] args) throws JoranException { - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - context.reset(); - JoranConfigurator joranConfigurator = new JoranConfigurator(); - joranConfigurator.setContext(context); - joranConfigurator.doConfigure("src/test/java/ch/qos/logback/classic/issue/DarioCampagna/logback-marker.xml"); - IMessageConveyor mc = new MessageConveyor(Locale.getDefault()); - LocLoggerFactory llFactory_default = new LocLoggerFactory(mc); - LocLogger locLogger = llFactory_default.getLocLogger("defaultLocLogger"); - Marker alwaysMarker = MarkerFactory.getMarker("ALWAYS"); - locLogger.info(alwaysMarker, "This will always appear."); - locLogger.info("Hello!"); - } + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + context.reset(); + JoranConfigurator joranConfigurator = new JoranConfigurator(); + joranConfigurator.setContext(context); + joranConfigurator.doConfigure("src/test/java/ch/qos/logback/classic/issue/DarioCampagna/logback-marker.xml"); + IMessageConveyor mc = new MessageConveyor(Locale.getDefault()); + LocLoggerFactory llFactory_default = new LocLoggerFactory(mc); + LocLogger locLogger = llFactory_default.getLocLogger("defaultLocLogger"); + Marker alwaysMarker = MarkerFactory.getMarker("ALWAYS"); + locLogger.info(alwaysMarker, "This will always appear."); + locLogger.info("Hello!"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/LBCORE63.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/LBCORE63.java index b973b1e36c8862ffec1172d0457b13a67d0d8d5b..7c5e32fddb386aaa32dd9f40e01dd6edad5950cd 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/LBCORE63.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/LBCORE63.java @@ -26,75 +26,75 @@ import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; public class LBCORE63 extends Thread { - private final static String LOGGER_CONFIGURATION_FILE = "./src/test/input/issue/lbcore63.xml"; - private final Logger logger = LoggerFactory.getLogger(LBCORE63.class); + private final static String LOGGER_CONFIGURATION_FILE = "./src/test/input/issue/lbcore63.xml"; + private final Logger logger = LoggerFactory.getLogger(LBCORE63.class); - private final long start; + private final long start; - public LBCORE63() throws JoranException { - start = new Date().getTime(); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(LOGGER_CONFIGURATION_FILE); - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - } + public LBCORE63() throws JoranException { + start = new Date().getTime(); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(LOGGER_CONFIGURATION_FILE); + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + } - public void start() { - ScheduledThreadPoolExecutor ex1 = new ScheduledThreadPoolExecutor(1); - ScheduledThreadPoolExecutor ex2 = new ScheduledThreadPoolExecutor(1); - ScheduledThreadPoolExecutor ex3 = new ScheduledThreadPoolExecutor(1); - ScheduledThreadPoolExecutor ex4 = new ScheduledThreadPoolExecutor(1); - ScheduledThreadPoolExecutor ex5 = new ScheduledThreadPoolExecutor(1); - ex1.scheduleAtFixedRate(new Task("EX1"), 10, 10, TimeUnit.MICROSECONDS); - ex2.scheduleAtFixedRate(new Task("EX2"), 10, 10, TimeUnit.MICROSECONDS); - ex3.scheduleAtFixedRate(new Task("EX3"), 10, 10, TimeUnit.MICROSECONDS); - ex4.scheduleAtFixedRate(new Task("EX4"), 10, 10, TimeUnit.MICROSECONDS); - ex5.scheduleAtFixedRate(new Task("EX5"), 10, 10, TimeUnit.MICROSECONDS); + public void start() { + ScheduledThreadPoolExecutor ex1 = new ScheduledThreadPoolExecutor(1); + ScheduledThreadPoolExecutor ex2 = new ScheduledThreadPoolExecutor(1); + ScheduledThreadPoolExecutor ex3 = new ScheduledThreadPoolExecutor(1); + ScheduledThreadPoolExecutor ex4 = new ScheduledThreadPoolExecutor(1); + ScheduledThreadPoolExecutor ex5 = new ScheduledThreadPoolExecutor(1); + ex1.scheduleAtFixedRate(new Task("EX1"), 10, 10, TimeUnit.MICROSECONDS); + ex2.scheduleAtFixedRate(new Task("EX2"), 10, 10, TimeUnit.MICROSECONDS); + ex3.scheduleAtFixedRate(new Task("EX3"), 10, 10, TimeUnit.MICROSECONDS); + ex4.scheduleAtFixedRate(new Task("EX4"), 10, 10, TimeUnit.MICROSECONDS); + ex5.scheduleAtFixedRate(new Task("EX5"), 10, 10, TimeUnit.MICROSECONDS); - super.start(); - } + super.start(); + } - public void run() { - try { - while (true) { - logger.debug("[MAIN] {}", new Date().getTime() - start); - Thread.sleep(10); - } - } catch (InterruptedException e) { - logger.info("[MAIN]: Interrupted: {}", e.getMessage()); + public void run() { + try { + while (true) { + logger.debug("[MAIN] {}", new Date().getTime() - start); + Thread.sleep(10); + } + } catch (InterruptedException e) { + logger.info("[MAIN]: Interrupted: {}", e.getMessage()); + } } - } - public static void main(String[] args) { - try { - LBCORE63 main = new LBCORE63(); - main.start(); - } catch (JoranException e) { - System.out.println("Failed to load application: " + e.getMessage()); + public static void main(String[] args) { + try { + LBCORE63 main = new LBCORE63(); + main.start(); + } catch (JoranException e) { + System.out.println("Failed to load application: " + e.getMessage()); + } } - } - class Task implements Runnable { - private final Logger logger = LoggerFactory.getLogger(Task.class); - //private final Logger logger_main = LoggerFactory.getLogger(LBCORE63.class); - final String name; - private final long start; + class Task implements Runnable { + private final Logger logger = LoggerFactory.getLogger(Task.class); + // private final Logger logger_main = LoggerFactory.getLogger(LBCORE63.class); + final String name; + private final long start; - int counter = 0; - public long diff; - - public Task(final String name) { - this.name = name; - start = new Date().getTime(); - } + int counter = 0; + public long diff; - public void run() { - counter++; - diff = new Date().getTime() - start; - logger.debug("counter={}", counter); - //logger_main.debug("[MAIN] - [{}] {}", name, new Date().getTime() - start); + public Task(final String name) { + this.name = name; + start = new Date().getTime(); + } + + public void run() { + counter++; + diff = new Date().getTime() - start; + logger.debug("counter={}", counter); + // logger_main.debug("[MAIN] - [{}] {}", name, new Date().getTime() - start); + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/PackageTest.java index b30305d4028ec2dd338ac249bfd4def17034fff5..649ba434ae2de7be6eb7a317ae3cb10febe26f19 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/PackageTest.java @@ -20,7 +20,6 @@ import org.junit.runners.Suite.SuiteClasses; import ch.qos.logback.classic.issue.lbclassic135.lbclassic139.LB139_DeadlockTest; @RunWith(Suite.class) -@SuiteClasses({LB139_DeadlockTest.class, - ch.qos.logback.classic.issue.logback416.PackageTest.class}) +@SuiteClasses({ LB139_DeadlockTest.class, ch.qos.logback.classic.issue.logback416.PackageTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingRunnable.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingRunnable.java index 70b067c57d538a190b0a9faae1339582ac020dbc..4d0f4dd88e327b67cc571565363d10c495e0b6f8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingRunnable.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingRunnable.java @@ -18,32 +18,31 @@ import ch.qos.logback.core.contention.RunnableWithCounterAndDone; public class LoggingRunnable extends RunnableWithCounterAndDone { - final Logger logger; - final int burstLength; + final Logger logger; + final int burstLength; + public LoggingRunnable(Logger logger, int burstLength) { + this.logger = logger; + this.burstLength = burstLength; + } - public LoggingRunnable(Logger logger, int burstLength) { - this.logger = logger; - this.burstLength = burstLength; - } - - public LoggingRunnable(Logger logger) { - this(logger, 100); - } + public LoggingRunnable(Logger logger) { + this(logger, 100); + } - public void run() { - while (!isDone()) { - logger.info("hello world ABCDEFGHI"); - counter++; - // don't hog the CPU forever - if (counter % burstLength == 0) { - try { - Thread.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); + public void run() { + while (!isDone()) { + logger.info("hello world ABCDEFGHI"); + counter++; + // don't hog the CPU forever + if (counter % burstLength == 0) { + try { + Thread.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } } - } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingToFileThroughput.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingToFileThroughput.java index fd8bec1f12881a1c60b34ea927c0c5eb92e37e8c..d9f61c71c4e8cd20173247ed30609dddb1ad164e 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingToFileThroughput.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/LoggingToFileThroughput.java @@ -27,90 +27,89 @@ import ch.qos.logback.core.contention.ThreadedThroughputCalculator; */ public class LoggingToFileThroughput { - static int THREAD_COUNT = 1; - static long OVERALL_DURATION_IN_MILLIS = 5000; + static int THREAD_COUNT = 1; + static long OVERALL_DURATION_IN_MILLIS = 5000; - public static void main(String args[]) throws InterruptedException { + public static void main(String args[]) throws InterruptedException { - ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator( - OVERALL_DURATION_IN_MILLIS); - tp.printEnvironmentInfo("lbclassic135 LoggingToFileThrouhput"); + ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator(OVERALL_DURATION_IN_MILLIS); + tp.printEnvironmentInfo("lbclassic135 LoggingToFileThrouhput"); - LoggerContext lc = new LoggerContext(); - Logger logger = buildLoggerContext(lc); - - for (int i = 0; i < 2; i++) { - tp.execute(buildArray(logger)); + LoggerContext lc = new LoggerContext(); + Logger logger = buildLoggerContext(lc); + + for (int i = 0; i < 2; i++) { + tp.execute(buildArray(logger)); + } + + tp.execute(buildArray(logger)); + tp.printThroughput("File: "); + lc.stop(); } - tp.execute(buildArray(logger)); - tp.printThroughput("File: "); - lc.stop(); - } - - static Logger buildLoggerContext(LoggerContext lc) { - Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - - PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); - patternLayout.setContext(lc); - patternLayout.setPattern("%d %l [%t] - %msg%n"); - patternLayout.start(); - FileAppender fileAppender = new FileAppender(); - fileAppender.setContext(lc); - fileAppender.setFile("target/lbclassic135.log"); - fileAppender.setEncoder(patternLayout); - fileAppender.setAppend(false); - fileAppender.start(); - root.addAppender(fileAppender); - return lc.getLogger(LoggingToFileThroughput.class); - } - - static LoggingRunnable[] buildArray(Logger logger) { - - LoggingRunnable[] array = new LoggingRunnable[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - array[i] = new LoggingRunnable(logger); + static Logger buildLoggerContext(LoggerContext lc) { + Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + + PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); + patternLayout.setContext(lc); + patternLayout.setPattern("%d %l [%t] - %msg%n"); + patternLayout.start(); + FileAppender fileAppender = new FileAppender(); + fileAppender.setContext(lc); + fileAppender.setFile("target/lbclassic135.log"); + fileAppender.setEncoder(patternLayout); + fileAppender.setAppend(false); + fileAppender.start(); + root.addAppender(fileAppender); + return lc.getLogger(LoggingToFileThroughput.class); + } + + static LoggingRunnable[] buildArray(Logger logger) { + + LoggingRunnable[] array = new LoggingRunnable[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + array[i] = new LoggingRunnable(logger); + } + return array; } - return array; - } } -//=== lbclassic135 LoggingToFileThrouhput === +// === lbclassic135 LoggingToFileThrouhput === // ******** 10 Threads ***** // synchronized doAppend() method // // java.runtime.version = 1.6.0_05-b13 -// java.vendor = Sun Microsystems Inc. -// os.name = Windows XP +// java.vendor = Sun Microsystems Inc. +// os.name = Windows XP // -// Threads 1: total of 485077 operations, or 97 operations per millisecond -// Threads 10: total of 309402 operations, or 61 operations per millisecond +// Threads 1: total of 485077 operations, or 97 operations per millisecond +// Threads 10: total of 309402 operations, or 61 operations per millisecond -//* After revision 2310 -//* Threads 1: total of 462465 operations, or 92 operations per millisecond -//* Threads 10: total of 243362 operations, or 48 operations per millisecond +// * After revision 2310 +// * Threads 1: total of 462465 operations, or 92 operations per millisecond +// * Threads 10: total of 243362 operations, or 48 operations per millisecond -// ==================== Linux ======================== +// ==================== Linux ======================== // java.runtime.version = 1.6.0_11-b03 -// java.vendor = Sun Microsystems Inc. -// os.name = Linux -// os.version = 2.6.25-gentoo-r6 -// Threads 1: total of 356355 operations, or 71 operations per millisecond +// java.vendor = Sun Microsystems Inc. +// os.name = Linux +// os.version = 2.6.25-gentoo-r6 +// Threads 1: total of 356355 operations, or 71 operations per millisecond // Threads 10: total of 287943 operations, or 57 operations per millisecond -//* After revision 2310 -//* Threads 1: total of 331494 operations, or 66 operations per millisecond -//* Threads 10: total of 311104 operations, or 58 operations per millisecond +// * After revision 2310 +// * Threads 1: total of 331494 operations, or 66 operations per millisecond +// * Threads 10: total of 311104 operations, or 58 operations per millisecond // java.runtime.version = jvmxa6460-20081105_25433 -// java.vendor = IBM Corporation -// java.version = 1.6.0 -// os.name = Linux -// os.version = 2.6.25-gentoo-r6 -// Threads 1: total of 280381 operations, or 56 operations per millisecond -// Threads 10 total of 142989 operations, or 28 operations per millisecond - -//* After revision 2310 -//* Threads 1: total of 305638 operations, or 61 operations per millisecond -//* Threads 10: total of 147660 operations, or 29 operations per millisecond \ No newline at end of file +// java.vendor = IBM Corporation +// java.version = 1.6.0 +// os.name = Linux +// os.version = 2.6.25-gentoo-r6 +// Threads 1: total of 280381 operations, or 56 operations per millisecond +// Threads 10 total of 142989 operations, or 28 operations per millisecond + +// * After revision 2310 +// * Threads 1: total of 305638 operations, or 61 operations per millisecond +// * Threads 10: total of 147660 operations, or 29 operations per millisecond \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Accessor.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Accessor.java index 097d4184bab5d426bdbcc77e36eb79b044bdcd2f..62b6c53fb999b8a0aa4f4a1b4aaa89d289fc0fcb 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Accessor.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Accessor.java @@ -24,28 +24,27 @@ import ch.qos.logback.core.contention.RunnableWithCounterAndDone; * */ public class Accessor extends RunnableWithCounterAndDone { - private Logger logger; - final Worker worker; - final LoggerContext loggerContext; + private Logger logger; + final Worker worker; + final LoggerContext loggerContext; - - Accessor(Worker worker, LoggerContext lc) { - this.worker = worker; - this.loggerContext = lc; - logger = lc.getLogger(this.getClass()); - } + Accessor(Worker worker, LoggerContext lc) { + this.worker = worker; + this.loggerContext = lc; + logger = lc.getLogger(this.getClass()); + } + + public void run() { + print("entered run()"); + // Thread.yield(); + while (!isDone()) { + logger.info("Current worker status is: {}.", worker); + } + print("leaving run()"); + } - public void run() { - print("entered run()"); - //Thread.yield(); - while (!isDone()) { - logger.info("Current worker status is: {}.", worker); + void print(String msg) { + String thread = Thread.currentThread().getName(); + System.out.println("[" + thread + "] " + msg); } - print("leaving run()"); - } - - void print(String msg) { - String thread = Thread.currentThread().getName(); - System.out.println("["+thread+"] "+msg); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/LB139_DeadlockTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/LB139_DeadlockTest.java index 51ee72f73fe95d40e12b038b4f393f18a394cef9..8e3a70679dcb9c11dc9d5dff86b735f2c4ea4927 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/LB139_DeadlockTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/LB139_DeadlockTest.java @@ -21,34 +21,35 @@ import ch.qos.logback.classic.LoggerContext; public class LB139_DeadlockTest { - LoggerContext loggerContext = new LoggerContext(); - - @Before - public void setUp() { - loggerContext.setName("LB139"); - BasicConfigurator.configure(loggerContext); - } - - @Test //(timeout=3000) - public void test() throws Exception { - Worker worker = new Worker(loggerContext); - Accessor accessor = new Accessor(worker, loggerContext); - - Thread workerThread = new Thread(worker, "WorkerThread"); - Thread accessorThread = new Thread(accessor, "AccessorThread"); - - workerThread.start(); - accessorThread.start(); - - int sleep = Worker.SLEEP_DUIRATION*10; - - System.out.println("Will sleep for "+sleep+" millis"); - Thread.sleep(sleep); - System.out.println("Done sleeping ("+sleep+" millis)"); - worker.setDone(true); - accessor.setDone(true); - - workerThread.join(); - accessorThread.join(); - } + LoggerContext loggerContext = new LoggerContext(); + + @Before + public void setUp() { + loggerContext.setName("LB139"); + BasicConfigurator.configure(loggerContext); + } + + @Test + // (timeout=3000) + public void test() throws Exception { + Worker worker = new Worker(loggerContext); + Accessor accessor = new Accessor(worker, loggerContext); + + Thread workerThread = new Thread(worker, "WorkerThread"); + Thread accessorThread = new Thread(accessor, "AccessorThread"); + + workerThread.start(); + accessorThread.start(); + + int sleep = Worker.SLEEP_DUIRATION * 10; + + System.out.println("Will sleep for " + sleep + " millis"); + Thread.sleep(sleep); + System.out.println("Done sleeping (" + sleep + " millis)"); + worker.setDone(true); + accessor.setDone(true); + + workerThread.join(); + accessorThread.join(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Worker.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Worker.java index 6817cd7b1c203be979a1ff26aba4357646c0b3bb..58a79ad8caf2bb2b11c10037ecabc7fc226ccc78 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Worker.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic135/lbclassic139/Worker.java @@ -26,50 +26,51 @@ import ch.qos.logback.core.contention.RunnableWithCounterAndDone; * */ public class Worker extends RunnableWithCounterAndDone { - static final int SLEEP_DUIRATION = 50; - - private Logger logger; - private final Vector lock = new Vector(); + static final int SLEEP_DUIRATION = 50; - final LoggerContext loggerContext; - Worker(LoggerContext lc) { - loggerContext = lc; - logger = lc.getLogger(this.getClass()); - } - - public void run() { - print("entered run()"); - while (!isDone()) { - synchronized (lock) { - sleep(); - logger.info("lock the logger"); - } + private Logger logger; + private final Vector lock = new Vector(); + + final LoggerContext loggerContext; + + Worker(LoggerContext lc) { + loggerContext = lc; + logger = lc.getLogger(this.getClass()); + } + + public void run() { + print("entered run()"); + while (!isDone()) { + synchronized (lock) { + sleep(); + logger.info("lock the logger"); + } + } + print("leaving run()"); } - print("leaving run()"); - } - @Override - public String toString() { - print("In Worker.toString() - about to access lock"); - synchronized (lock) { - print("In Worker.toString() - got the lock"); - //sleep(); - return "STATUS"; + @Override + public String toString() { + print("In Worker.toString() - about to access lock"); + synchronized (lock) { + print("In Worker.toString() - got the lock"); + // sleep(); + return "STATUS"; + } } - } - - public void sleep() { - try { - print("About to go to sleep"); - Thread.sleep(SLEEP_DUIRATION); - print("just woke up"); - } catch (InterruptedException exc) { - exc.printStackTrace(); + + public void sleep() { + try { + print("About to go to sleep"); + Thread.sleep(SLEEP_DUIRATION); + print("just woke up"); + } catch (InterruptedException exc) { + exc.printStackTrace(); + } + } + + void print(String msg) { + String thread = Thread.currentThread().getName(); + System.out.println("[" + thread + "] " + msg); } - } - - void print(String msg) { - String thread = Thread.currentThread().getName(); - System.out.println("["+thread+"] "+msg); - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/HtmlEscapedMessageConverter.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/HtmlEscapedMessageConverter.java index 80341ce05f3876a3b4fc5a2f7581b92ee3ce1c1a..fa9922244d1eaa843c54cb7093415882d89ae775 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/HtmlEscapedMessageConverter.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/HtmlEscapedMessageConverter.java @@ -19,7 +19,7 @@ import ch.qos.logback.core.helpers.Transform; public class HtmlEscapedMessageConverter extends ClassicConverter { - public String convert(ILoggingEvent event) { - return Transform.escapeTags(event.getFormattedMessage()); - } + public String convert(ILoggingEvent event) { + return Transform.escapeTags(event.getFormattedMessage()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/Main.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/Main.java index 4cca7a3927ab5f02999cffb208e211e2fcdbfa87..f8c2511c720f2ca36e0ddb18ba5f75aa4c0610ff 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/Main.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic180/Main.java @@ -19,23 +19,21 @@ import ch.qos.logback.core.joran.spi.JoranException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class Main { - static Logger logger = LoggerFactory.getLogger(Main.class); - static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic180/"; - - public static void main(String[] args) throws JoranException, InterruptedException { - init(DIR_PREFIX + "logback.xml"); - logger.debug("

hello

"); - } + static Logger logger = LoggerFactory.getLogger(Main.class); + static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic180/"; + public static void main(String[] args) throws JoranException, InterruptedException { + init(DIR_PREFIX + "logback.xml"); + logger.debug("

hello

"); + } - static void init(String file) throws JoranException { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.reset(); - jc.doConfigure(file); - } + static void init(String file) throws JoranException { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.reset(); + jc.doConfigure(file); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Barebones.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Barebones.java index 2bfe3e568ad35df03e8c6cf3ccff7f6dbf4dfc3f..0dac3e0de7dc0e637f10b1c60d7978adc9615fe8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Barebones.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Barebones.java @@ -18,28 +18,29 @@ import ch.qos.logback.core.ContextBase; public class Barebones { - public static void main(String[] args) { - Context context = new ContextBase(); - for(int i = 0; i < 3; i++) { - SenderRunnable senderRunnable = new SenderRunnable(""+i); - context.getExecutorService().execute(senderRunnable); + public static void main(String[] args) { + Context context = new ContextBase(); + for (int i = 0; i < 3; i++) { + SenderRunnable senderRunnable = new SenderRunnable("" + i); + context.getExecutorService().execute(senderRunnable); + } + System.out.println("done"); + // System.exit(0); } - System.out.println("done"); - //System.exit(0); - } - static class SenderRunnable implements Runnable { - String id; - SenderRunnable(String id) { - this.id = id; - } + static class SenderRunnable implements Runnable { + String id; + + SenderRunnable(String id) { + this.id = id; + } - public void run() { - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - } - System.out.println("SenderRunnable " +id); + public void run() { + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + } + System.out.println("SenderRunnable " + id); + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Simple.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Simple.java index 0abcbc469b1029f9dc7f67e323850b4fc452434c..e31cd7573f86f632cd30efd104b376a6070d77ee 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Simple.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic323/Simple.java @@ -23,27 +23,26 @@ import org.slf4j.LoggerFactory; */ public class Simple { - static Logger logger = LoggerFactory.getLogger(Simple.class); - static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic323/"; - - public static void main(String[] args) throws JoranException, InterruptedException { - init(DIR_PREFIX + "logback_smtp.xml"); - - for (int i = 0; i < 10; i++) { - logger.debug("SEE IF THIS IS LOGGED {}.", i); + static Logger logger = LoggerFactory.getLogger(Simple.class); + static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic323/"; + + public static void main(String[] args) throws JoranException, InterruptedException { + init(DIR_PREFIX + "logback_smtp.xml"); + + for (int i = 0; i < 10; i++) { + logger.debug("SEE IF THIS IS LOGGED {}.", i); + } + logger.error("trigger"); + System.out.println("done"); + System.exit(0); } - logger.error("trigger"); - System.out.println("done"); - System.exit(0); - } - - static void init(String file) throws JoranException { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.reset(); - jc.doConfigure(file); - } + static void init(String file) throws JoranException { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.reset(); + jc.doConfigure(file); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic330/Main.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic330/Main.java index fceb381f4aa7387c7749141095bac16c61e59652..f519aeccbabdb298c7551ca5c3add9dacdb0c65c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic330/Main.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic330/Main.java @@ -19,23 +19,21 @@ import ch.qos.logback.core.joran.spi.JoranException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class Main { - static Logger logger = LoggerFactory.getLogger(Main.class); - static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic330/"; - - public static void main(String[] args) throws JoranException, InterruptedException { - init(DIR_PREFIX + "logback.xml"); - logger.debug("hello"); - } + static Logger logger = LoggerFactory.getLogger(Main.class); + static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbclassic330/"; + public static void main(String[] args) throws JoranException, InterruptedException { + init(DIR_PREFIX + "logback.xml"); + logger.debug("hello"); + } - static void init(String file) throws JoranException { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.reset(); - jc.doConfigure(file); - } + static void init(String file) throws JoranException { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.reset(); + jc.doConfigure(file); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatOriginal_tzest.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatOriginal_tzest.java index db7bd3b29de8d12e5823c68fa18b0627198aabfe..7915f89259a5a53382ca30412fddcc2f6221112e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatOriginal_tzest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatOriginal_tzest.java @@ -25,228 +25,228 @@ import java.util.Date; //import org.joda.time.DateTime; public class DateFormatOriginal_tzest extends TestCase { - public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; - static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; - - /** - * Create the test case - * - * @param testName - * name of the test case - */ - public DateFormatOriginal_tzest(String testName) { - super(testName); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() { - return new TestSuite(DateFormatOriginal_tzest.class); - } - - public static void main(String[] args) { - junit.textui.TestRunner.run(suite()); - } - - public void setUp() throws Exception { - super.setUp(); - } - - public void tearDown() throws Exception { - super.tearDown(); - } - -// public void testRaw() throws Exception { -// SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); -// DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN); -// -// Date date = new Date(); -// DateTime dateTime = new DateTime(date); -// -// long start = System.nanoTime(); -// for (int i = 0; i < 100000; ++i) { -// jodaFormat.print(dateTime); -// } -// long jodaAvg = (System.nanoTime() - start) / 100000; -// -// -// start = System.nanoTime(); -// for (int i = 0; i < 100000; ++i) { -// simpleFormat.format(date); -// } -// long simpleAvg = (System.nanoTime() - start) / 100000; -// -// float diff = (((float) (simpleAvg - jodaAvg)) / simpleAvg) * 100; -// System.out.println("Raw - JDK: " + simpleAvg + " ns Joda: " + jodaAvg -// + " ns - Difference: " + diff + "%"); -// } - - public void testSynchronized() throws Exception { - SynchronizedDateFormatter formatter = new SynchronizedDateFormatter(); - int threads = 10; - int iterations = 10000; - Thread[] formatThreads = new Thread[threads]; - Date date = new Date(); - - for (int i = 0; i < threads; i++) { - formatThreads[i] = new DateFormatThread(formatter, date, iterations); + public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; + static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; + + /** + * Create the test case + * + * @param testName + * name of the test case + */ + public DateFormatOriginal_tzest(String testName) { + super(testName); } - long start = System.nanoTime(); - for (Thread thread : formatThreads) { - thread.start(); - } - for (Thread thread : formatThreads) { - thread.join(); - } - long end = System.nanoTime(); - double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; - System.out.printf("Synchronized DateFormat: %,.4f seconds\n", actual); - } - - public void testUnSynchronized() throws Exception { - UnsynchronizedDateFormatter formatter = new UnsynchronizedDateFormatter(); - int threads = 10; - int iterations = 10000; - Thread[] formatThreads = new Thread[threads]; - Date date = new Date(); + /** + * @return the suite of tests being tested + */ + public static Test suite() { + return new TestSuite(DateFormatOriginal_tzest.class); + } - for (int i = 0; i < threads; i++) { - formatThreads[i] = new DateFormatThread(formatter, date, iterations); + public static void main(String[] args) { + junit.textui.TestRunner.run(suite()); } - long start = System.nanoTime(); - for (Thread thread : formatThreads) { - thread.start(); + + public void setUp() throws Exception { + super.setUp(); } - for (Thread thread : formatThreads) { - thread.join(); + + public void tearDown() throws Exception { + super.tearDown(); } - long end = System.nanoTime(); - double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; - System.out.printf("Unsynchronized DateFormat: %,.4f seconds\n", actual); - } + // public void testRaw() throws Exception { + // SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); + // DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN); + // + // Date date = new Date(); + // DateTime dateTime = new DateTime(date); + // + // long start = System.nanoTime(); + // for (int i = 0; i < 100000; ++i) { + // jodaFormat.print(dateTime); + // } + // long jodaAvg = (System.nanoTime() - start) / 100000; + // + // + // start = System.nanoTime(); + // for (int i = 0; i < 100000; ++i) { + // simpleFormat.format(date); + // } + // long simpleAvg = (System.nanoTime() - start) / 100000; + // + // float diff = (((float) (simpleAvg - jodaAvg)) / simpleAvg) * 100; + // System.out.println("Raw - JDK: " + simpleAvg + " ns Joda: " + jodaAvg + // + " ns - Difference: " + diff + "%"); + // } + + public void testSynchronized() throws Exception { + SynchronizedDateFormatter formatter = new SynchronizedDateFormatter(); + int threads = 10; + int iterations = 10000; + Thread[] formatThreads = new Thread[threads]; + Date date = new Date(); + + for (int i = 0; i < threads; i++) { + formatThreads[i] = new DateFormatThread(formatter, date, iterations); + } + long start = System.nanoTime(); + for (Thread thread : formatThreads) { + thread.start(); + } + for (Thread thread : formatThreads) { + thread.join(); + } + long end = System.nanoTime(); + double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; + System.out.printf("Synchronized DateFormat: %,.4f seconds\n", actual); + + } - public void testThreadLocal() throws Exception { - ThreadLocalDateFormatter formatter = new ThreadLocalDateFormatter(); - int threads = 10; - int iterations = 10000; - Thread[] formatThreads = new Thread[threads]; - Date date = new Date(); + public void testUnSynchronized() throws Exception { + UnsynchronizedDateFormatter formatter = new UnsynchronizedDateFormatter(); + int threads = 10; + int iterations = 10000; + Thread[] formatThreads = new Thread[threads]; + Date date = new Date(); + + for (int i = 0; i < threads; i++) { + formatThreads[i] = new DateFormatThread(formatter, date, iterations); + } + long start = System.nanoTime(); + for (Thread thread : formatThreads) { + thread.start(); + } + for (Thread thread : formatThreads) { + thread.join(); + } + long end = System.nanoTime(); + double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; + System.out.printf("Unsynchronized DateFormat: %,.4f seconds\n", actual); - for (int i = 0; i < threads; i++) { - formatThreads[i] = new DateFormatThread(formatter, date, iterations); } - long start = System.nanoTime(); - for (Thread thread : formatThreads) { - thread.start(); + + public void testThreadLocal() throws Exception { + ThreadLocalDateFormatter formatter = new ThreadLocalDateFormatter(); + int threads = 10; + int iterations = 10000; + Thread[] formatThreads = new Thread[threads]; + Date date = new Date(); + + for (int i = 0; i < threads; i++) { + formatThreads[i] = new DateFormatThread(formatter, date, iterations); + } + long start = System.nanoTime(); + for (Thread thread : formatThreads) { + thread.start(); + } + for (Thread thread : formatThreads) { + thread.join(); + } + long end = System.nanoTime(); + double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; + System.out.printf("ThreadLocal DateFormat: %,.4f seconds\n", actual); + } - for (Thread thread : formatThreads) { - thread.join(); + + // public void testDateTimeFormatter() throws Exception { + // int threads = 10; + // int iterations = 10000; + // Thread[] formatThreads = new DateTimeFormatThread[threads]; + // JodaFormatter formatter = new JodaFormatter(); + // Date date = new Date(); + // DateTime dateTime = new DateTime(date); + // + // for (int i = 0; i < threads; i++) { + // formatThreads[i] = new DateTimeFormatThread(formatter, dateTime, + // iterations); + // } + // long start = System.nanoTime(); + // for (Thread thread : formatThreads) { + // thread.start(); + // } + // for (Thread thread : formatThreads) { + // thread.join(); + // } + // long end = System.nanoTime(); + // double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; + // System.out.printf("Joda DateTimeFormatter: %,.4f seconds\n", actual); + // + // } + + public interface Formatter { + String format(Date date); } - long end = System.nanoTime(); - double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; - System.out.printf("ThreadLocal DateFormat: %,.4f seconds\n", actual); - - } - -// public void testDateTimeFormatter() throws Exception { -// int threads = 10; -// int iterations = 10000; -// Thread[] formatThreads = new DateTimeFormatThread[threads]; -// JodaFormatter formatter = new JodaFormatter(); -// Date date = new Date(); -// DateTime dateTime = new DateTime(date); -// -// for (int i = 0; i < threads; i++) { -// formatThreads[i] = new DateTimeFormatThread(formatter, dateTime, -// iterations); -// } -// long start = System.nanoTime(); -// for (Thread thread : formatThreads) { -// thread.start(); -// } -// for (Thread thread : formatThreads) { -// thread.join(); -// } -// long end = System.nanoTime(); -// double actual = ((double) (end - start)) / NANOS_IN_ONE_SEC; -// System.out.printf("Joda DateTimeFormatter: %,.4f seconds\n", actual); -// -// } - - public interface Formatter { - String format(Date date); - } - - public static class SynchronizedDateFormatter implements Formatter { - SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); - - public synchronized String format(Date date) { - return simpleFormat.format(date); + + public static class SynchronizedDateFormatter implements Formatter { + SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); + + public synchronized String format(Date date) { + return simpleFormat.format(date); + } } - } - public static class UnsynchronizedDateFormatter implements Formatter { - public synchronized String format(Date date) { - return new SimpleDateFormat(ISO8601_PATTERN).format(date); + public static class UnsynchronizedDateFormatter implements Formatter { + public synchronized String format(Date date) { + return new SimpleDateFormat(ISO8601_PATTERN).format(date); + } } - } - public static class ThreadLocalDateFormatter implements Formatter { - ThreadLocal formatter = new ThreadLocal() { - protected synchronized SimpleDateFormat initialValue() { - return new SimpleDateFormat(ISO8601_PATTERN); - } - }; + public static class ThreadLocalDateFormatter implements Formatter { + ThreadLocal formatter = new ThreadLocal() { + protected synchronized SimpleDateFormat initialValue() { + return new SimpleDateFormat(ISO8601_PATTERN); + } + }; - public String format(Date date) { - return formatter.get().format(date); - } - } - -// public static class JodaFormatter { -// DateTimeFormatter formatter = DateTimeFormat.forPattern(ISO8601_PATTERN); -// -// public String format(DateTime date) { -// return formatter.print(date); -// } -// } - - public static class DateFormatThread extends Thread { - Formatter formatter; - Date date; - long iterCount; - - public DateFormatThread(Formatter f, Date date, long iterations) { - this.formatter = f; - this.date = date; - this.iterCount = iterations; + public String format(Date date) { + return formatter.get().format(date); + } } - public void run() { - for (int i = 0; i < iterCount; i++) { - formatter.format(this.date); - } + // public static class JodaFormatter { + // DateTimeFormatter formatter = DateTimeFormat.forPattern(ISO8601_PATTERN); + // + // public String format(DateTime date) { + // return formatter.print(date); + // } + // } + + public static class DateFormatThread extends Thread { + Formatter formatter; + Date date; + long iterCount; + + public DateFormatThread(Formatter f, Date date, long iterations) { + this.formatter = f; + this.date = date; + this.iterCount = iterations; + } + + public void run() { + for (int i = 0; i < iterCount; i++) { + formatter.format(this.date); + } + } } - } - -// public static class DateTimeFormatThread extends Thread { -// JodaFormatter formatter; -// DateTime date; -// long iterCount; -// -// public DateTimeFormatThread(JodaFormatter f, DateTime date, long iterations) { -// this.formatter = f; -// this.date = date; -// this.iterCount = iterations; -// } -// -// public void run() { -// for (int i = 0; i < iterCount; i++) { -// formatter.format(this.date); -// } -// } -// } + + // public static class DateTimeFormatThread extends Thread { + // JodaFormatter formatter; + // DateTime date; + // long iterCount; + // + // public DateTimeFormatThread(JodaFormatter f, DateTime date, long iterations) { + // this.formatter = f; + // this.date = date; + // this.iterCount = iterations; + // } + // + // public void run() { + // for (int i = 0; i < iterCount; i++) { + // formatter.format(this.date); + // } + // } + // } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatPerf_Tapp.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatPerf_Tapp.java index a0fdb538cecf4715e4626cfaf2c9a207ea48e939..64ba2e050d2026e5e465d4c2efdc66fa4121a0de 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatPerf_Tapp.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormatPerf_Tapp.java @@ -20,43 +20,43 @@ import java.util.Date; //import org.joda.time.format.DateTimeFormatter; public class DateFormatPerf_Tapp { - public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; - static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; + public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; + static final long NANOS_IN_ONE_SEC = 1000 * 1000 * 1000L; - static long RUN_LENGTH = 1000 * 1000; + static long RUN_LENGTH = 1000 * 1000; - public static void main(String[] args) { - for (int i = 0; i < 5; i++) { - doRawJoda(); - doRawSDF(); - } + public static void main(String[] args) { + for (int i = 0; i < 5; i++) { + doRawJoda(); + doRawSDF(); + } - print("Raw Joda: ", doRawJoda()); - print("Raw SDF: ", doRawSDF()); - } + print("Raw Joda: ", doRawJoda()); + print("Raw SDF: ", doRawSDF()); + } - static void print(String msg, double avg) { - System.out.println(msg + " average tick " + avg + " nanoseconds"); - } + static void print(String msg, double avg) { + System.out.println(msg + " average tick " + avg + " nanoseconds"); + } - static double doRawJoda() { -// DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN); - long timeInMillis = new Date().getTime(); - long start = System.nanoTime(); - for (int i = 0; i < RUN_LENGTH; ++i) { -// jodaFormat.print(timeInMillis); + static double doRawJoda() { + // DateTimeFormatter jodaFormat = DateTimeFormat.forPattern(ISO8601_PATTERN); + long timeInMillis = new Date().getTime(); + long start = System.nanoTime(); + for (int i = 0; i < RUN_LENGTH; ++i) { + // jodaFormat.print(timeInMillis); + } + return (System.nanoTime() - start) * 1.0d / RUN_LENGTH; } - return (System.nanoTime() - start) * 1.0d / RUN_LENGTH; - } - - static double doRawSDF() { - SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); - long timeInMillis = new Date().getTime(); - long start = System.nanoTime(); - for (int i = 0; i < RUN_LENGTH; ++i) { - simpleFormat.format(timeInMillis); + + static double doRawSDF() { + SimpleDateFormat simpleFormat = new SimpleDateFormat(ISO8601_PATTERN); + long timeInMillis = new Date().getTime(); + long start = System.nanoTime(); + for (int i = 0; i < RUN_LENGTH; ++i) { + simpleFormat.format(timeInMillis); + } + return (System.nanoTime() - start) * 1.0d / RUN_LENGTH; } - return (System.nanoTime() - start) * 1.0d / RUN_LENGTH; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormattingThreadedThroughputCalculator.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormattingThreadedThroughputCalculator.java index 81d287b3496d36481f7a3ea70cc1542718e10be6..3a3fb11bf85c0fda92f5ff2f57779540100975dc 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormattingThreadedThroughputCalculator.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/DateFormattingThreadedThroughputCalculator.java @@ -24,35 +24,33 @@ import ch.qos.logback.core.contention.ThreadedThroughputCalculator; */ public class DateFormattingThreadedThroughputCalculator { - static int THREAD_COUNT = 16; - static long OVERALL_DURATION_IN_MILLIS = 3000; + static int THREAD_COUNT = 16; + static long OVERALL_DURATION_IN_MILLIS = 3000; - public static void main(String args[]) throws InterruptedException { + public static void main(String args[]) throws InterruptedException { - ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator( - OVERALL_DURATION_IN_MILLIS); - tp.printEnvironmentInfo("DateFormatting"); + ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator(OVERALL_DURATION_IN_MILLIS); + tp.printEnvironmentInfo("DateFormatting"); - for (int i = 0; i < 2; i++) { - tp.execute(buildArray(FormattingModel.SDF)); - tp.execute(buildArray(FormattingModel.JODA)); - } + for (int i = 0; i < 2; i++) { + tp.execute(buildArray(FormattingModel.SDF)); + tp.execute(buildArray(FormattingModel.JODA)); + } - tp.execute(buildArray(FormattingModel.JODA)); - tp.printThroughput("JODA: "); - - tp.execute(buildArray(FormattingModel.SDF)); - tp.printThroughput("SDF: "); + tp.execute(buildArray(FormattingModel.JODA)); + tp.printThroughput("JODA: "); + tp.execute(buildArray(FormattingModel.SDF)); + tp.printThroughput("SDF: "); - } + } - static SelectiveDateFormattingRunnable[] buildArray(FormattingModel model) { - SelectiveDateFormattingRunnable[] array = new SelectiveDateFormattingRunnable[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - array[i] = new SelectiveDateFormattingRunnable(model); + static SelectiveDateFormattingRunnable[] buildArray(FormattingModel model) { + SelectiveDateFormattingRunnable[] array = new SelectiveDateFormattingRunnable[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + array[i] = new SelectiveDateFormattingRunnable(model); + } + return array; } - return array; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/SelectiveDateFormattingRunnable.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/SelectiveDateFormattingRunnable.java index 245ad25dd93602f861689f4c4a0f298d6fca6ede..7f2eb30b426e8471a98851251303b71fd5e79a80 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/SelectiveDateFormattingRunnable.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbclassic36/SelectiveDateFormattingRunnable.java @@ -25,75 +25,75 @@ import ch.qos.logback.core.contention.RunnableWithCounterAndDone; * @author Raplh Goers * @author Ceki Gulcu */ -public class SelectiveDateFormattingRunnable extends - RunnableWithCounterAndDone { +public class SelectiveDateFormattingRunnable extends RunnableWithCounterAndDone { - public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; + public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; - enum FormattingModel { - SDF, JODA; - } + enum FormattingModel { + SDF, JODA; + } + + FormattingModel model; + static long CACHE = 0; - FormattingModel model; - static long CACHE = 0; + static SimpleDateFormat SDF = new SimpleDateFormat(ISO8601_PATTERN); - static SimpleDateFormat SDF = new SimpleDateFormat(ISO8601_PATTERN); -// static final DateTimeFormatter JODA = DateTimeFormat -// .forPattern(ISO8601_PATTERN); + // static final DateTimeFormatter JODA = DateTimeFormat + // .forPattern(ISO8601_PATTERN); - SelectiveDateFormattingRunnable(FormattingModel model) { - this.model = model; - } + SelectiveDateFormattingRunnable(FormattingModel model) { + this.model = model; + } - public void run() { - switch (model) { - case SDF: - sdfRun(); - break; - case JODA: - jodaRun(); - break; + public void run() { + switch (model) { + case SDF: + sdfRun(); + break; + case JODA: + jodaRun(); + break; + } } - } - void sdfRun() { + void sdfRun() { + + for (;;) { + synchronized (SDF) { + long now = System.currentTimeMillis(); + if (CACHE != now) { + CACHE = now; + SDF.format(now); + } + } + counter++; + if (done) { + return; + } + } + } - for (;;) { - synchronized (SDF) { - long now = System.currentTimeMillis(); - if (CACHE != now) { - CACHE = now; - SDF.format(now); + void jodaRun() { + for (;;) { + long now = System.currentTimeMillis(); + if (isCacheStale(now)) { + // JODA.print(now); + } + counter++; + if (done) { + return; + } } - } - counter++; - if (done) { - return; - } } - } - void jodaRun() { - for (;;) { - long now = System.currentTimeMillis(); - if (isCacheStale(now)) { - //JODA.print(now); - } - counter++; - if (done) { - return; - } + private static boolean isCacheStale(long now) { + // synchronized (JODA) { + // if (CACHE != now) { + // CACHE = now; + // return true; + // } + // } + return false; } - } - - private static boolean isCacheStale(long now) { -// synchronized (JODA) { -// if (CACHE != now) { -// CACHE = now; -// return true; -// } -// } - return false; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore211/Lbcore211.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore211/Lbcore211.java index d8cb621a3dae64d6264dd694e7ecc3bcee8ec683..7fd5ad1432a44f01c8a9e8ae2026f196d1f63ef2 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore211/Lbcore211.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore211/Lbcore211.java @@ -26,22 +26,22 @@ import org.slf4j.LoggerFactory; */ public class Lbcore211 { - @Test - public void lbcore211() throws JoranException { + @Test + public void lbcore211() throws JoranException { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure("/home/ceki/lbcore211.xml"); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure("/home/ceki/lbcore211.xml"); - Logger l = lc.getLogger("file.logger"); - StatusPrinter.print(lc); - for (int i = 0; i < 10; i++) { - l.info("hello " + i); - } + Logger l = lc.getLogger("file.logger"); + StatusPrinter.print(lc); + for (int i = 0; i < 10; i++) { + l.info("hello " + i); + } - lc.stop(); - } + lc.stop(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore224/Reduce.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore224/Reduce.java index 99c2031e96b33aa56deb87cc3c3479d2b599ef26..f5cef54cfbb1f52681e70dc23367fe93b99cb69c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore224/Reduce.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore224/Reduce.java @@ -24,150 +24,146 @@ import java.util.regex.Pattern; */ public class Reduce { - static int NA = -1; + static int NA = -1; - enum OperationType {LOCK, UNLOCK} - - public static void main(String[] args) throws IOException { - File inputFile = new File(args[0]); - if(!inputFile.exists()) { - throw new IllegalArgumentException("Missing file ["+args[0]+"]"); - } - List lines = readFile(inputFile); - System.out.println("Lines count=" + lines.size()); - List structuredLines = structure(lines); - List reduction = reduce(structuredLines); - if (reduction.isEmpty()) { - System.out.println("Reduction is EMPTY as it should be."); - } else { - System.out.println("Non-empty reduction!!! WTF?"); - System.out.println(reduction); + enum OperationType { + LOCK, UNLOCK } + public static void main(String[] args) throws IOException { + File inputFile = new File(args[0]); + if (!inputFile.exists()) { + throw new IllegalArgumentException("Missing file [" + args[0] + "]"); + } + List lines = readFile(inputFile); + System.out.println("Lines count=" + lines.size()); + List structuredLines = structure(lines); + List reduction = reduce(structuredLines); + if (reduction.isEmpty()) { + System.out.println("Reduction is EMPTY as it should be."); + } else { + System.out.println("Non-empty reduction!!! WTF?"); + System.out.println(reduction); + } - } + } - private static List readFile(File inputFile) throws IOException { - BufferedReader reader = null; - List lines = new ArrayList(); - try { - reader = new BufferedReader(new FileReader(inputFile)); - String line; - while ((line = reader.readLine()) != null) { - lines.add(line); - } - } finally { - if (reader != null) + private static List readFile(File inputFile) throws IOException { + BufferedReader reader = null; + List lines = new ArrayList(); try { - reader.close(); - } catch (IOException e) { + reader = new BufferedReader(new FileReader(inputFile)); + String line; + while ((line = reader.readLine()) != null) { + lines.add(line); + } + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + } } + return lines; } - return lines; - } - - private static List reduce(List structuredLines) { - List matching = new ArrayList(); - int lockIndex = 0; - while (lockIndex < structuredLines.size()) { - lockIndex = findNearestLock(structuredLines, lockIndex); - if (lockIndex == NA) - break; - else { - int unlockIndex = findNearestUnlockInSameThread(structuredLines, lockIndex); - if (unlockIndex != NA) { - matching.add(structuredLines.get(lockIndex)); - matching.add(structuredLines.get(unlockIndex)); - } - lockIndex++; - } - } - System.out.println("matching list size: " + matching.size()); - List reduction = new ArrayList(); - for (Structure s : structuredLines) { - if (!matching.contains(s)) { - reduction.add(s); - } - } - return reduction; - } + private static List reduce(List structuredLines) { + List matching = new ArrayList(); + int lockIndex = 0; + while (lockIndex < structuredLines.size()) { + lockIndex = findNearestLock(structuredLines, lockIndex); + if (lockIndex == NA) + break; + else { + int unlockIndex = findNearestUnlockInSameThread(structuredLines, lockIndex); + if (unlockIndex != NA) { + matching.add(structuredLines.get(lockIndex)); + matching.add(structuredLines.get(unlockIndex)); + } + lockIndex++; + } + } + System.out.println("matching list size: " + matching.size()); + List reduction = new ArrayList(); + for (Structure s : structuredLines) { + if (!matching.contains(s)) { + reduction.add(s); + } + } + return reduction; - private static int findNearestLock(List reduction, int index) { - for (int i = index; i < reduction.size(); i++) { - Structure s = reduction.get(i); - if (s.operationType == OperationType.LOCK) { - return i; - } - } - return NA; - } - - private static int findNearestUnlockInSameThread(List reduction, int lockIndex) { - int firstCandidateIndex = lockIndex+1; - Structure lockStructure = reduction.get(lockIndex); - for (int i = firstCandidateIndex; i < reduction.size(); i++) { - Structure s = reduction.get(i); - if (s.operationType == OperationType.UNLOCK && lockStructure.thread.equals(s.thread)) { - return i; - } } - return NA; - } - - static List structure(List lines) { - List structuredLines = new ArrayList(); - Pattern p = Pattern.compile("(\\d{2,5})\\ +(.*) (LOCK|UNLOCK)"); - - for (String line : lines) { - Matcher m = p.matcher(line); - if (m.matches()) { - String relTime = m.group(1); - String t = m.group(2); - String opStr = m.group(3); - Structure structure = buildStructure(relTime, t, opStr); - structuredLines.add(structure); - } else { - System.out.println("NON MATCHING LINE: ["+ line+"]"); - } + private static int findNearestLock(List reduction, int index) { + for (int i = index; i < reduction.size(); i++) { + Structure s = reduction.get(i); + if (s.operationType == OperationType.LOCK) { + return i; + } + } + return NA; } - return structuredLines; - } - - private static Structure buildStructure(String relTime, String t, String opStr) { - long r = Long.parseLong(relTime); - OperationType operationType; - if (opStr.equals("LOCK")) - operationType = OperationType.LOCK; - else if (opStr.equals("UNLOCK")) { - operationType = OperationType.UNLOCK; - } else { - throw new IllegalArgumentException(opStr + " is not LOCK|UNLOCK"); + + private static int findNearestUnlockInSameThread(List reduction, int lockIndex) { + int firstCandidateIndex = lockIndex + 1; + Structure lockStructure = reduction.get(lockIndex); + for (int i = firstCandidateIndex; i < reduction.size(); i++) { + Structure s = reduction.get(i); + if (s.operationType == OperationType.UNLOCK && lockStructure.thread.equals(s.thread)) { + return i; + } + } + return NA; } - return new Structure(r, t, operationType); - } + static List structure(List lines) { + List structuredLines = new ArrayList(); + Pattern p = Pattern.compile("(\\d{2,5})\\ +(.*) (LOCK|UNLOCK)"); + + for (String line : lines) { + Matcher m = p.matcher(line); + if (m.matches()) { + String relTime = m.group(1); + String t = m.group(2); + String opStr = m.group(3); + Structure structure = buildStructure(relTime, t, opStr); + structuredLines.add(structure); + } else { + System.out.println("NON MATCHING LINE: [" + line + "]"); + } - static class Structure { - long time; - String thread; - OperationType operationType; + } + return structuredLines; + } - Structure(long time, String thread, OperationType operationType) { - this.time = time; - this.thread = thread; - this.operationType = operationType; + private static Structure buildStructure(String relTime, String t, String opStr) { + long r = Long.parseLong(relTime); + OperationType operationType; + if (opStr.equals("LOCK")) + operationType = OperationType.LOCK; + else if (opStr.equals("UNLOCK")) { + operationType = OperationType.UNLOCK; + } else { + throw new IllegalArgumentException(opStr + " is not LOCK|UNLOCK"); + } + return new Structure(r, t, operationType); } - @Override - public String toString() { - return "Structure{" + - "time=" + time + - ", thread='" + thread + '\'' + - ", operationType=" + operationType + - '}'; + static class Structure { + long time; + String thread; + OperationType operationType; + + Structure(long time, String thread, OperationType operationType) { + this.time = time; + this.thread = thread; + this.operationType = operationType; + } + + @Override + public String toString() { + return "Structure{" + "time=" + time + ", thread='" + thread + '\'' + ", operationType=" + operationType + '}'; + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/Common.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/Common.java index 6ed6f7afc0fafb3f20a4c9b811ac9f7af5bc47f4..063b33e5d1e56f88b1249e711e6d9bda75993248 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/Common.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/Common.java @@ -15,7 +15,7 @@ package ch.qos.logback.classic.issue.lbcore243; public class Common { - // How many times should we try to log: - static int loop = 800*1000; + // How many times should we try to log: + static int loop = 800 * 1000; } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLog4j.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLog4j.java index cd21a4667484bb8d56390fe58991389f9c23d39f..aca9a3e71f2e5b573cfbc6479e9e43ce0e25e88f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLog4j.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLog4j.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.issue.lbcore243; - import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; @@ -21,42 +20,42 @@ import org.apache.log4j.xml.DOMConfigurator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - // WARNING This code compiles but does not measure anything useful because log4j-over-slf4j is a dependency. Log4j // should be used instead public class PerformanceComparatorLog4j { - static org.apache.log4j.Logger log4jlogger = org.apache.log4j.Logger.getLogger(PerformanceComparatorLog4j.class); - - public static void main(String[] args) throws JoranException, InterruptedException { - initLog4jWithoutImmediateFlush(); - - // Let's run once for Just In Time compiler - log4jDirectDebugCall(); - - System.out.println("###############################################"); - System.out.println("Log4j without immediate flush: " + log4jDirectDebugCall()+ " nanos per call"); - System.out.println("###############################################"); - } - - private static long log4jDirectDebugCall() { - Integer j = new Integer(2); - long start = System.nanoTime(); - for (int i = 0; i < Common.loop; i++) { - log4jlogger.debug("SEE IF THIS IS LOGGED " + j + "."); - } - return (System.nanoTime() - start) / Common.loop; - } - - static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbcore243/"; - - static void initLog4jWithoutImmediateFlush() { - DOMConfigurator domConfigurator = new DOMConfigurator(); - domConfigurator.configure(DIR_PREFIX+"log4j_without_immediateFlush.xml"); - } - static void initLog4jWithImmediateFlush() { - DOMConfigurator domConfigurator = new DOMConfigurator(); - domConfigurator.configure(DIR_PREFIX+"log4j_with_immediateFlush.xml"); - } + static org.apache.log4j.Logger log4jlogger = org.apache.log4j.Logger.getLogger(PerformanceComparatorLog4j.class); + + public static void main(String[] args) throws JoranException, InterruptedException { + initLog4jWithoutImmediateFlush(); + + // Let's run once for Just In Time compiler + log4jDirectDebugCall(); + + System.out.println("###############################################"); + System.out.println("Log4j without immediate flush: " + log4jDirectDebugCall() + " nanos per call"); + System.out.println("###############################################"); + } + + private static long log4jDirectDebugCall() { + Integer j = new Integer(2); + long start = System.nanoTime(); + for (int i = 0; i < Common.loop; i++) { + log4jlogger.debug("SEE IF THIS IS LOGGED " + j + "."); + } + return (System.nanoTime() - start) / Common.loop; + } + + static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbcore243/"; + + static void initLog4jWithoutImmediateFlush() { + DOMConfigurator domConfigurator = new DOMConfigurator(); + domConfigurator.configure(DIR_PREFIX + "log4j_without_immediateFlush.xml"); + } + + static void initLog4jWithImmediateFlush() { + DOMConfigurator domConfigurator = new DOMConfigurator(); + domConfigurator.configure(DIR_PREFIX + "log4j_with_immediateFlush.xml"); + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLogback.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLogback.java index 7ae391e0362211b5fb334baf9028d16088e1b7ab..80e4b3333837e003602da72d4e5dcb3c75432096 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLogback.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore243/PerformanceComparatorLogback.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.issue.lbcore243; - import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; @@ -25,50 +24,48 @@ import org.slf4j.LoggerFactory; //Logback without immediate flush: 1758 nanos per call public class PerformanceComparatorLogback { - static Logger logbacklogger = LoggerFactory.getLogger(PerformanceComparatorLogback.class); - - public static void main(String[] args) throws JoranException, InterruptedException { - initLogbackWithoutImmediateFlush(); - logbackParametrizedDebugCall(); + static Logger logbacklogger = LoggerFactory.getLogger(PerformanceComparatorLogback.class); - initLogbackWithImmediateFlush(); - logbackParametrizedDebugCall(); - System.out.println("###############################################"); - System.out.println("Logback with immediate flush: " + logbackParametrizedDebugCall() + " nanos per call"); + public static void main(String[] args) throws JoranException, InterruptedException { + initLogbackWithoutImmediateFlush(); + logbackParametrizedDebugCall(); - initLogbackWithoutImmediateFlush(); - System.out.println("Logback without immediate flush: " + logbackParametrizedDebugCall() + " nanos per call"); + initLogbackWithImmediateFlush(); + logbackParametrizedDebugCall(); + System.out.println("###############################################"); + System.out.println("Logback with immediate flush: " + logbackParametrizedDebugCall() + " nanos per call"); - System.out.println("###############################################"); - } + initLogbackWithoutImmediateFlush(); + System.out.println("Logback without immediate flush: " + logbackParametrizedDebugCall() + " nanos per call"); - private static long logbackParametrizedDebugCall() { - - Integer j = new Integer(2); - long start = System.nanoTime(); - for (int i = 0; i < Common.loop; i++) { - logbacklogger.debug("SEE IF THIS IS LOGGED {}.", j); + System.out.println("###############################################"); } - return (System.nanoTime() - start) / Common.loop; - } - static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbcore243/"; + private static long logbackParametrizedDebugCall() { + Integer j = new Integer(2); + long start = System.nanoTime(); + for (int i = 0; i < Common.loop; i++) { + logbacklogger.debug("SEE IF THIS IS LOGGED {}.", j); + } + return (System.nanoTime() - start) / Common.loop; + } - static void configure(String file) throws JoranException { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.reset(); - jc.doConfigure(file); - } + static String DIR_PREFIX = "src/test/java/ch/qos/logback/classic/issue/lbcore243/"; + static void configure(String file) throws JoranException { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.reset(); + jc.doConfigure(file); + } - private static void initLogbackWithoutImmediateFlush() throws JoranException { - configure(DIR_PREFIX + "logback_without_immediateFlush.xml"); - } + private static void initLogbackWithoutImmediateFlush() throws JoranException { + configure(DIR_PREFIX + "logback_without_immediateFlush.xml"); + } - private static void initLogbackWithImmediateFlush() throws JoranException { - configure(DIR_PREFIX + "logback_with_immediateFlush.xml"); - } + private static void initLogbackWithImmediateFlush() throws JoranException { + configure(DIR_PREFIX + "logback_with_immediateFlush.xml"); + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore26/Main.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore26/Main.java index a41b9e0523b108f315a390557e534c8b09e42ea8..13f8248405906c8aad6642e515140739c7072c31 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore26/Main.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore26/Main.java @@ -26,20 +26,19 @@ import ch.qos.logback.core.util.StatusPrinter; public class Main { - public static void main(String[] args) throws JoranException { - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - configurator.doConfigure(ClassicTestConstants.INPUT_PREFIX - + "issue/lbcore26.xml"); - - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - Logger logger = LoggerFactory.getLogger(Main.class); - for (int i = 0; i < 16; i++) { - logger.info("hello " + new Date()); - } + public static void main(String[] args) throws JoranException { + + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + configurator.doConfigure(ClassicTestConstants.INPUT_PREFIX + "issue/lbcore26.xml"); - } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + Logger logger = LoggerFactory.getLogger(Main.class); + for (int i = 0; i < 16; i++) { + logger.info("hello " + new Date()); + } + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/Main.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/Main.java index aa52db5a79445d4f2c2af7dc1a2f93e02fd259a1..d7416b4194d30f1320107bbac711ae733969dfd8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/Main.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/Main.java @@ -23,17 +23,17 @@ import org.slf4j.LoggerFactory; */ public class Main { - public static void main(String[] args) throws InterruptedException { + public static void main(String[] args) throws InterruptedException { - Logger logger = (Logger) LoggerFactory.getLogger(Main.class); - StatusPrinter.print((LoggerContext) LoggerFactory.getILoggerFactory()); - OThread ot = new OThread(); - ot.start(); - Thread.sleep(OThread.WAIT_MILLIS-500); - logger.info("About to interrupt"); - ot.interrupt(); - logger.info("After interrupt"); - logger.info("Leaving main"); + Logger logger = (Logger) LoggerFactory.getLogger(Main.class); + StatusPrinter.print((LoggerContext) LoggerFactory.getILoggerFactory()); + OThread ot = new OThread(); + ot.start(); + Thread.sleep(OThread.WAIT_MILLIS - 500); + logger.info("About to interrupt"); + ot.interrupt(); + logger.info("After interrupt"); + logger.info("Leaving main"); - } + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/OThread.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/OThread.java index cafed7f3098e6b14c1a41fd5670e7a8d0a733ff1..817470f0cb0d052e5739bd058f22dfc81bc99170 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/OThread.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/lbcore_155/OThread.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.issue.lbcore_155; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,33 +21,32 @@ import org.slf4j.LoggerFactory; */ public class OThread extends Thread { + static int NANOS_IN_MILLI = 1000 * 1000; - static int NANOS_IN_MILLI = 1000 * 1000; + static int WAIT_MILLIS = 10; - static int WAIT_MILLIS = 10; + Logger logger = LoggerFactory.getLogger(this.getClass()); - Logger logger = LoggerFactory.getLogger(this.getClass()); + public void run() { - public void run() { + while (!isInterrupted()) { + long start = System.nanoTime(); + for (long now = System.nanoTime(); now < start + 2 * WAIT_MILLIS * NANOS_IN_MILLI; now = System.nanoTime()) { + logger.info("in time loop"); + } - while (!isInterrupted()) { - long start = System.nanoTime(); - for (long now = System.nanoTime(); now < start + 2*WAIT_MILLIS*NANOS_IN_MILLI; now = System.nanoTime()) { - logger.info("in time loop"); - } + logger.info("before 2nd sleep"); - logger.info("before 2nd sleep"); - - try { - sleep(1000); - } catch (InterruptedException e) { - logger.info("While sleeping", e); - e.printStackTrace(); - break; - } - logger.info("after sleep"); - } - logger.info("exiting WHILE"); + try { + sleep(1000); + } catch (InterruptedException e) { + logger.info("While sleeping", e); + e.printStackTrace(); + break; + } + logger.info("after sleep"); + } + logger.info("exiting WHILE"); - } + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/ConcurrentSiftingTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/ConcurrentSiftingTest.java index cbbd506f4edacc51e534ef85b252e22c7c4c4626..e7f388d5ff5f6c4de8b04e2423a18fca9dfe0412 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/ConcurrentSiftingTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/ConcurrentSiftingTest.java @@ -28,36 +28,35 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; public class ConcurrentSiftingTest { - final static int THREAD_COUNT = 5; - static String FOLDER_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX - + "sift/"; - - LoggerContext loggerContext = new LoggerContext(); - protected Logger logger = loggerContext.getLogger(this.getClass().getName()); - protected Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - - int totalTestDuration = 50; - MultiThreadedHarness harness = new MultiThreadedHarness(totalTestDuration); - RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); - - protected void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(file); - } - - RunnableWithCounterAndDone[] buildRunnableArray() { - RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - rArray[i] = new LoggingRunnable(logger); + final static int THREAD_COUNT = 5; + static String FOLDER_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX + "sift/"; + + LoggerContext loggerContext = new LoggerContext(); + protected Logger logger = loggerContext.getLogger(this.getClass().getName()); + protected Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + + int totalTestDuration = 50; + MultiThreadedHarness harness = new MultiThreadedHarness(totalTestDuration); + RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); + + protected void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(file); + } + + RunnableWithCounterAndDone[] buildRunnableArray() { + RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + rArray[i] = new LoggingRunnable(logger); + } + return rArray; + } + + @Test + public void concurrentAccess() throws JoranException, InterruptedException { + configure(FOLDER_PREFIX + "logback_416.xml"); + harness.execute(runnableArray); + assertEquals(1, InstanceCountingAppender.INSTANCE_COUNT.get()); } - return rArray; - } - - @Test - public void concurrentAccess() throws JoranException, InterruptedException { - configure(FOLDER_PREFIX + "logback_416.xml"); - harness.execute(runnableArray); - assertEquals(1, InstanceCountingAppender.INSTANCE_COUNT.get()); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/InstanceCountingAppender.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/InstanceCountingAppender.java index dba9022c23dc8a4df551f3242172dc64178e3803..ed674668f74a579585d847439b3b1ceae06df865 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/InstanceCountingAppender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback416/InstanceCountingAppender.java @@ -19,14 +19,14 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; public class InstanceCountingAppender extends AppenderBase { - - static public AtomicInteger INSTANCE_COUNT = new AtomicInteger(0); - public InstanceCountingAppender() { - INSTANCE_COUNT.getAndIncrement(); - } + static public AtomicInteger INSTANCE_COUNT = new AtomicInteger(0); + + public InstanceCountingAppender() { + INSTANCE_COUNT.getAndIncrement(); + } + + protected void append(ILoggingEvent e) { + } - protected void append(ILoggingEvent e) { - } - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback474/LoggingAppender.java b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback474/LoggingAppender.java index 5f78f0ad3f190e40c9693a5bfecedcd79a36d80f..04fc7d4d2553c8b0062f61a2907c6492963c0a33 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback474/LoggingAppender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/issue/logback474/LoggingAppender.java @@ -27,14 +27,14 @@ import ch.qos.logback.core.AppenderBase; public class LoggingAppender extends AppenderBase { - Logger logger; + Logger logger; - public void start() { - super.start(); - logger = ((LoggerContext) getContext()).getLogger("Ignore"); - } + public void start() { + super.start(); + logger = ((LoggerContext) getContext()).getLogger("Ignore"); + } - protected void append(ILoggingEvent eventObject) { - logger.debug("Ignore this"); - } + protected void append(ILoggingEvent eventObject) { + logger.debug("Ignore this"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/jmx/JMXConfiguratorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/jmx/JMXConfiguratorTest.java index 7beee79969f2f8861e4d0335920a6a4119a01ddc..0f82581d1f7d919e565b59b66492f4bd0b3d5c13 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/jmx/JMXConfiguratorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/jmx/JMXConfiguratorTest.java @@ -39,137 +39,128 @@ import static org.slf4j.Logger.ROOT_LOGGER_NAME; public class JMXConfiguratorTest { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - LoggerContext lc = new LoggerContext(); - Logger testLogger = lc.getLogger(this.getClass()); - - List listenerList; - int diff = RandomUtil.getPositiveInt(); - - - @Before - public void setUp() throws Exception { - lc.setName("context-" + diff); - assertNotNull(mbs); - } - - @After - public void tearDown() throws Exception { - lc.stop(); - } - - @Override - public String toString() { - return this.getClass().getName() + "(" + lc.getName() + ")"; - } - - @Test - public void contextReset() throws Exception { - String randomizedObjectNameAsStr = "ch.qos.logback."+diff + ":Name=" + lc.getName() - + ",Type=" + this.getClass().getName(); - - ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, randomizedObjectNameAsStr); - JMXConfigurator jmxConfigurator = new JMXConfigurator(lc, mbs, objectName); - mbs.registerMBean(jmxConfigurator, objectName); - - listenerList = lc.getCopyOfListenerList(); - assertEquals(1, listenerList.size()); - - lc.reset(); - - // check that after lc.reset, jmxConfigurator should still be - // registered as a listener in the loggerContext and also as an - // MBean in mbs - listenerList = lc.getCopyOfListenerList(); - assertEquals(1, listenerList.size()); - assertTrue(listenerList.contains(jmxConfigurator)); - - assertTrue(mbs.isRegistered(objectName)); - } - - @Test - public void contextStop() throws Exception { - String randomizedObjectNameAsStr = "ch.qos.logback."+diff + ":Name=" + lc.getName() - + ",Type=" + this.getClass().getName(); - - ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, randomizedObjectNameAsStr); - JMXConfigurator jmxConfigurator = new JMXConfigurator(lc, mbs, objectName); - mbs.registerMBean(jmxConfigurator, objectName); - - listenerList = lc.getCopyOfListenerList(); - assertEquals(1, listenerList.size()); - - lc.stop(); - - // check that after lc.processPriorToRemoval, jmxConfigurator is no longer - // registered as a listener in the loggerContext nor as an - // MBean in mbs - listenerList = lc.getCopyOfListenerList(); - assertEquals(0, listenerList.size()); - - assertFalse(mbs.isRegistered(objectName)); - } - - @Test - public void testNonRemovalOfPreviousIntanceFromTheContextListenerList() { - String objectNameAsStr = "ch.qos.logback.toto" + ":Name=" + lc.getName() - + ",Type=" + this.getClass().getName(); - ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); - JMXConfigurator jmxConfigurator0 = new JMXConfigurator(lc, mbs, objectName); - - listenerList = lc.getCopyOfListenerList(); - assertTrue(listenerList.contains(jmxConfigurator0)); - - JMXConfigurator jmxConfigurator1 = new JMXConfigurator(lc, mbs, objectName); - listenerList = lc.getCopyOfListenerList(); - assertEquals(1, listenerList.size()); - assertTrue("old configurator should be present", listenerList - .contains(jmxConfigurator0)); - assertFalse("new configurator should be absent", listenerList - .contains(jmxConfigurator1)); - } - - @Test - public void getLoggerLevel_LBCLASSIC_78() { - String objectNameAsStr = "ch.qos"+diff + ":Name=" + lc.getName() - + ",Type=" + this.getClass().getName(); - - ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); - JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); - assertEquals("", configurator.getLoggerLevel(testLogger.getName())); - MBeanUtil.unregister(lc, mbs, on, this); - } - - - @Test - public void setLoggerLevel_LBCLASSIC_79() { - String objectNameAsStr = "ch.qos"+diff + ":Name=" + lc.getName() - + ",Type=" + this.getClass().getName(); - - ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); - JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); - configurator.setLoggerLevel(testLogger.getName(), "DEBUG"); - assertEquals(Level.DEBUG, testLogger.getLevel()); - - configurator.setLoggerLevel(testLogger.getName(), "null"); - assertNull(testLogger.getLevel()); - - MBeanUtil.unregister(lc, mbs, on, this); - } - - @Test - public void testReloadDefaultConfiguration() throws Exception { - String objectNameAsStr = "ch.qos"+diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); - - ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); - JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); - configurator.setLoggerLevel(testLogger.getName(), "DEBUG"); - assertEquals(Level.DEBUG, testLogger.getLevel()); - - configurator.reloadDefaultConfiguration(); - assertNull(testLogger.getLevel()); - assertEquals(Level.DEBUG, lc.getLogger(ROOT_LOGGER_NAME).getLevel()); - MBeanUtil.unregister(lc, mbs, on, this); - } + MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); + LoggerContext lc = new LoggerContext(); + Logger testLogger = lc.getLogger(this.getClass()); + + List listenerList; + int diff = RandomUtil.getPositiveInt(); + + @Before + public void setUp() throws Exception { + lc.setName("context-" + diff); + assertNotNull(mbs); + } + + @After + public void tearDown() throws Exception { + lc.stop(); + } + + @Override + public String toString() { + return this.getClass().getName() + "(" + lc.getName() + ")"; + } + + @Test + public void contextReset() throws Exception { + String randomizedObjectNameAsStr = "ch.qos.logback." + diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + + ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, randomizedObjectNameAsStr); + JMXConfigurator jmxConfigurator = new JMXConfigurator(lc, mbs, objectName); + mbs.registerMBean(jmxConfigurator, objectName); + + listenerList = lc.getCopyOfListenerList(); + assertEquals(1, listenerList.size()); + + lc.reset(); + + // check that after lc.reset, jmxConfigurator should still be + // registered as a listener in the loggerContext and also as an + // MBean in mbs + listenerList = lc.getCopyOfListenerList(); + assertEquals(1, listenerList.size()); + assertTrue(listenerList.contains(jmxConfigurator)); + + assertTrue(mbs.isRegistered(objectName)); + } + + @Test + public void contextStop() throws Exception { + String randomizedObjectNameAsStr = "ch.qos.logback." + diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + + ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, randomizedObjectNameAsStr); + JMXConfigurator jmxConfigurator = new JMXConfigurator(lc, mbs, objectName); + mbs.registerMBean(jmxConfigurator, objectName); + + listenerList = lc.getCopyOfListenerList(); + assertEquals(1, listenerList.size()); + + lc.stop(); + + // check that after lc.processPriorToRemoval, jmxConfigurator is no longer + // registered as a listener in the loggerContext nor as an + // MBean in mbs + listenerList = lc.getCopyOfListenerList(); + assertEquals(0, listenerList.size()); + + assertFalse(mbs.isRegistered(objectName)); + } + + @Test + public void testNonRemovalOfPreviousIntanceFromTheContextListenerList() { + String objectNameAsStr = "ch.qos.logback.toto" + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + ObjectName objectName = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); + JMXConfigurator jmxConfigurator0 = new JMXConfigurator(lc, mbs, objectName); + + listenerList = lc.getCopyOfListenerList(); + assertTrue(listenerList.contains(jmxConfigurator0)); + + JMXConfigurator jmxConfigurator1 = new JMXConfigurator(lc, mbs, objectName); + listenerList = lc.getCopyOfListenerList(); + assertEquals(1, listenerList.size()); + assertTrue("old configurator should be present", listenerList.contains(jmxConfigurator0)); + assertFalse("new configurator should be absent", listenerList.contains(jmxConfigurator1)); + } + + @Test + public void getLoggerLevel_LBCLASSIC_78() { + String objectNameAsStr = "ch.qos" + diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + + ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); + JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); + assertEquals("", configurator.getLoggerLevel(testLogger.getName())); + MBeanUtil.unregister(lc, mbs, on, this); + } + + @Test + public void setLoggerLevel_LBCLASSIC_79() { + String objectNameAsStr = "ch.qos" + diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + + ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); + JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); + configurator.setLoggerLevel(testLogger.getName(), "DEBUG"); + assertEquals(Level.DEBUG, testLogger.getLevel()); + + configurator.setLoggerLevel(testLogger.getName(), "null"); + assertNull(testLogger.getLevel()); + + MBeanUtil.unregister(lc, mbs, on, this); + } + + @Test + public void testReloadDefaultConfiguration() throws Exception { + String objectNameAsStr = "ch.qos" + diff + ":Name=" + lc.getName() + ",Type=" + this.getClass().getName(); + + ObjectName on = MBeanUtil.string2ObjectName(lc, this, objectNameAsStr); + JMXConfigurator configurator = new JMXConfigurator(lc, mbs, on); + configurator.setLoggerLevel(testLogger.getName(), "DEBUG"); + assertEquals(Level.DEBUG, testLogger.getLevel()); + + configurator.reloadDefaultConfiguration(); + assertNull(testLogger.getLevel()); + assertEquals(Level.DEBUG, lc.getLogger(ROOT_LOGGER_NAME).getLevel()); + MBeanUtil.unregister(lc, mbs, on, this); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/jmx/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/jmx/PackageTest.java index 611be0da70128f10497558299b096bbe4835c8a3..cc4654cd3f6bfd0ffe7607561a4527e8d4a9d75f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/jmx/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/jmx/PackageTest.java @@ -13,13 +13,12 @@ */ package ch.qos.logback.classic.jmx; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses(JMXConfiguratorTest.class) -public class PackageTest { - +public class PackageTest { + } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/joran/EvaluatorJoranTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/joran/EvaluatorJoranTest.java index 3823c73730fec1e842a8917bda88d7ac8f71a8f1..7c39ef2e5839e24d91abbfdf88d15c1e11dec3aa 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/joran/EvaluatorJoranTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/joran/EvaluatorJoranTest.java @@ -35,74 +35,73 @@ import ch.qos.logback.core.boolex.EvaluationException; import ch.qos.logback.core.boolex.EventEvaluator; import ch.qos.logback.core.joran.spi.JoranException; +public class EvaluatorJoranTest { -public class EvaluatorJoranTest { - - @Test - public void testSimpleEvaluator() throws NullPointerException, EvaluationException, JoranException { - JoranConfigurator jc = new JoranConfigurator(); - LoggerContext loggerContext = new LoggerContext(); - jc.setContext(loggerContext); - jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleEvaluator.xml"); - - @SuppressWarnings("unchecked") - Map> evalMap = (Map>) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); - assertNotNull(evalMap); - JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("msgEval"); - assertNotNull(evaluator); - - Logger logger = loggerContext.getLogger("xx"); - ILoggingEvent event0 = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world", null, null); - assertTrue(evaluator.evaluate(event0)); - - ILoggingEvent event1 = new LoggingEvent("foo", logger, Level.DEBUG, "random blurb", null, null); - assertFalse(evaluator.evaluate(event1)); - } - - @Test - public void testIgnoreMarker() throws NullPointerException, EvaluationException, JoranException { - JoranConfigurator jc = new JoranConfigurator(); - LoggerContext loggerContext = new LoggerContext(); - jc.setContext(loggerContext); - jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "ignore.xml"); - - @SuppressWarnings("unchecked") - Map> evalMap = (Map>) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); - assertNotNull(evalMap); - - Logger logger = loggerContext.getLogger("xx"); - - JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("IGNORE_EVAL"); - LoggingEvent event = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world",null, null); - - Marker ignoreMarker = MarkerFactory.getMarker("IGNORE"); - event.setMarker(ignoreMarker); - assertTrue(evaluator.evaluate(event)); - - logger.debug("hello", new Exception("test")); - logger.debug(ignoreMarker, "hello ignore", new Exception("test")); - - //logger.debug("hello", new Exception("test")); - - //StatusPrinter.print(loggerContext.getStatusManager()); - } - - @Test - public void testMultipleConditionsInExpression() throws NullPointerException, EvaluationException { - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger("xx"); - JaninoEventEvaluator ee = new JaninoEventEvaluator(); - ee.setName("testEval"); - ee.setContext(loggerContext); - //&& - //&& - ee.setExpression("message.contains(\"stacktrace\") && message.contains(\"logging\")"); - ee.start(); - //StatusPrinter.print(loggerContext); - - String message = "stacktrace bla bla logging"; - ILoggingEvent event = new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, message, null, null); - - assertTrue(ee.evaluate(event)); - } + @Test + public void testSimpleEvaluator() throws NullPointerException, EvaluationException, JoranException { + JoranConfigurator jc = new JoranConfigurator(); + LoggerContext loggerContext = new LoggerContext(); + jc.setContext(loggerContext); + jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleEvaluator.xml"); + + @SuppressWarnings("unchecked") + Map> evalMap = (Map>) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); + assertNotNull(evalMap); + JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("msgEval"); + assertNotNull(evaluator); + + Logger logger = loggerContext.getLogger("xx"); + ILoggingEvent event0 = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world", null, null); + assertTrue(evaluator.evaluate(event0)); + + ILoggingEvent event1 = new LoggingEvent("foo", logger, Level.DEBUG, "random blurb", null, null); + assertFalse(evaluator.evaluate(event1)); + } + + @Test + public void testIgnoreMarker() throws NullPointerException, EvaluationException, JoranException { + JoranConfigurator jc = new JoranConfigurator(); + LoggerContext loggerContext = new LoggerContext(); + jc.setContext(loggerContext); + jc.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "ignore.xml"); + + @SuppressWarnings("unchecked") + Map> evalMap = (Map>) loggerContext.getObject(CoreConstants.EVALUATOR_MAP); + assertNotNull(evalMap); + + Logger logger = loggerContext.getLogger("xx"); + + JaninoEventEvaluator evaluator = (JaninoEventEvaluator) evalMap.get("IGNORE_EVAL"); + LoggingEvent event = new LoggingEvent("foo", logger, Level.DEBUG, "Hello world", null, null); + + Marker ignoreMarker = MarkerFactory.getMarker("IGNORE"); + event.setMarker(ignoreMarker); + assertTrue(evaluator.evaluate(event)); + + logger.debug("hello", new Exception("test")); + logger.debug(ignoreMarker, "hello ignore", new Exception("test")); + + // logger.debug("hello", new Exception("test")); + + // StatusPrinter.print(loggerContext.getStatusManager()); + } + + @Test + public void testMultipleConditionsInExpression() throws NullPointerException, EvaluationException { + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger("xx"); + JaninoEventEvaluator ee = new JaninoEventEvaluator(); + ee.setName("testEval"); + ee.setContext(loggerContext); + // && + // && + ee.setExpression("message.contains(\"stacktrace\") && message.contains(\"logging\")"); + ee.start(); + // StatusPrinter.print(loggerContext); + + String message = "stacktrace bla bla logging"; + ILoggingEvent event = new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, message, null, null); + + assertTrue(ee.evaluate(event)); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/joran/JoranConfiguratorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/joran/JoranConfiguratorTest.java index afefe0e6886e6c70a302738f23bd240fb89cffde..d0696b012eee2b3892d92a38ab1add309f421af6 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/joran/JoranConfiguratorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/joran/JoranConfiguratorTest.java @@ -49,444 +49,404 @@ import static org.junit.Assert.*; public class JoranConfiguratorTest { - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(this.getClass().getName()); - Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - StatusChecker checker = new StatusChecker(loggerContext); - int diff = RandomUtil.getPositiveInt(); - - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.putProperty("diff", "" + diff); - jc.doConfigure(file); - } - - @Test - public void simpleList() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleList.xml"); - + LoggerContext loggerContext = new LoggerContext(); Logger logger = loggerContext.getLogger(this.getClass().getName()); Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - String msg = "hello world"; - logger.debug(msg); - assertEquals(1, listAppender.list.size()); - ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); - assertEquals(msg, le.getMessage()); - } - - @Test - public void level() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleLevel.xml"); - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - String msg = "hello world"; - logger.debug(msg); - assertEquals(0, listAppender.list.size()); - } - - @Test - public void additivity() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "additivity.xml"); - Logger logger = loggerContext.getLogger("additivityTest"); - assertFalse(logger.isAdditive()); - } - - @Test - public void rootLoggerLevelSettingBySystemProperty() throws JoranException { - String propertyName = "logback.level"; - - System.setProperty(propertyName, "INFO"); - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "rootLevelByProperty.xml"); - // StatusPrinter.print(loggerContext); - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - String msg = "hello world"; - logger.debug(msg); - assertEquals(0, listAppender.list.size()); - System.clearProperty(propertyName); - } - - @Test - public void loggerLevelSettingBySystemProperty() throws JoranException { - String propertyName = "logback.level"; - System.setProperty(propertyName, "DEBUG"); - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "loggerLevelByProperty.xml"); - // StatusPrinter.print(loggerContext); - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - String msg = "hello world"; - logger.debug(msg); - assertEquals(1, listAppender.list.size()); - System.clearProperty(propertyName); - } - - @Test - public void appenderRefSettingBySystemProperty() throws JoranException { - final String propertyName = "logback.appenderRef"; - System.setProperty(propertyName, "A"); - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "appenderRefByProperty.xml"); - final Logger logger = loggerContext - .getLogger("ch.qos.logback.classic.joran"); - final ListAppender listAppender = (ListAppender) logger - .getAppender("A"); - assertEquals(0, listAppender.list.size()); - final String msg = "hello world"; - logger.info(msg); - assertEquals(1, listAppender.list.size()); - System.clearProperty(propertyName); - } - - @Test - public void statusListener() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "statusListener.xml"); - } - - @Test - public void contextRename() throws JoranException { - loggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "contextRename.xml"); - assertEquals("wombat", loggerContext.getName()); - } - - @Test - public void eval() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "callerData.xml"); - - String msg = "hello world"; - logger.debug("toto"); - logger.debug(msg); - - StringListAppender slAppender = (StringListAppender) loggerContext - .getLogger("root").getAppender("STR_LIST"); - assertNotNull(slAppender); - assertEquals(2, slAppender.strList.size()); - assertTrue(slAppender.strList.get(0).contains(" DEBUG - toto")); - - String str1 = slAppender.strList.get(1); - assertTrue(str1.contains("Caller+0")); - assertTrue(str1.contains(" DEBUG - hello world")); - } - - @Test - public void turboFilter() throws JoranException { - // Although this test uses turbo filters, it only checks - // that Joran can see the xml element and create - // and place the relevant object correctly. - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turbo.xml"); - - TurboFilter filter = loggerContext.getTurboFilterList().get(0); - assertTrue(filter instanceof NOPTurboFilter); - } - - @Test - public void testTurboFilterWithStringList() throws JoranException { - // Although this test uses turbo filters, it only checks - // that Joran can see elements, and behave correctly - // that is call the addUser method and pass the correct values - // to that method. - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turbo2.xml"); - - // StatusPrinter.print(loggerContext.getStatusManager()); - - TurboFilter filter = loggerContext.getTurboFilterList().get(0); - assertTrue(filter instanceof DebugUsersTurboFilter); - DebugUsersTurboFilter dutf = (DebugUsersTurboFilter) filter; - assertEquals(2, dutf.getUsers().size()); - } - - @Test - public void testLevelFilter() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "levelFilter.xml"); - - // StatusPrinter.print(loggerContext); - - logger.warn("hello"); - logger.error("to be ignored"); - - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - - assertNotNull(listAppender); - assertEquals(1, listAppender.list.size()); - ILoggingEvent back = listAppender.list.get(0); - assertEquals(Level.WARN, back.getLevel()); - assertEquals("hello", back.getMessage()); - } - - @Test - public void testEvaluatorFilter() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "evaluatorFilter.xml"); - - // StatusPrinter.print(loggerContext); - - logger.warn("hello"); - logger.error("to be ignored"); - - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - - assertNotNull(listAppender); - assertEquals(1, listAppender.list.size()); - ILoggingEvent back = listAppender.list.get(0); - assertEquals(Level.WARN, back.getLevel()); - assertEquals("hello", back.getMessage()); - } - - @Test - public void testTurboDynamicThreshold() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "turboDynamicThreshold.xml"); - - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - - // this one should be denied - MDC.put("userId", "user1"); - logger.debug("hello user1"); - // this one should log - MDC.put("userId", "user2"); - logger.debug("hello user2"); - - assertEquals(1, listAppender.list.size()); - ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); - assertEquals("hello user2", le.getMessage()); - } - - @Test - public void testTurboDynamicThreshold2() throws JoranException { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "turboDynamicThreshold2.xml"); - - ListAppender listAppender = (ListAppender) root - .getAppender("LIST"); - assertEquals(0, listAppender.list.size()); - - // this one should log - MDC.put("userId", "user1"); - logger.debug("hello user1"); - // this one should log - MDC.put("userId", "user2"); - logger.debug("hello user2"); - // this one should fail - MDC.put("userId", "user3"); - logger.debug("hello user3"); - - assertEquals(2, listAppender.list.size()); - ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); - assertEquals("hello user1", le.getMessage()); - le = (ILoggingEvent) listAppender.list.get(1); - assertEquals("hello user2", le.getMessage()); - } - - // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter - @Test - public void autoscanShouldReconfigureOnFileChange() throws Exception { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "scan1.xml"; - configure(configFileAsStr); - - File file = new File(configFileAsStr); - file.setLastModified(System.currentTimeMillis()); - - Thread.sleep(10); - // scanning requires 16 logs - for (int i = 0; i < 16; i++) { - logger.debug("after " + i); + StatusChecker checker = new StatusChecker(loggerContext); + int diff = RandomUtil.getPositiveInt(); + + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.putProperty("diff", "" + diff); + jc.doConfigure(file); } - loggerContext.getExecutorService().shutdown(); - loggerContext.getExecutorService().awaitTermination(1000, - TimeUnit.MILLISECONDS); + @Test + public void simpleList() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleList.xml"); + + Logger logger = loggerContext.getLogger(this.getClass().getName()); + Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + String msg = "hello world"; + logger.debug(msg); + assertEquals(1, listAppender.list.size()); + ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); + assertEquals(msg, le.getMessage()); + } - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertIsErrorFree(); - checker.assertContainsMatch(CoreConstants.RESET_MSG_PREFIX); - } - - @Test - public void timestamp() throws JoranException, IOException, - InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "timestamp-context.xml"; - configure(configFileAsStr); - - String r = loggerContext.getProperty("testTimestamp"); - assertNotNull(r); - CachingDateFormatter sdf = new CachingDateFormatter("yyyy-MM"); - String expected = sdf.format(System.currentTimeMillis()); - assertEquals("expected \"" + expected + "\" but got " + r, expected, r); - } - - @Test - public void timestampLocal() throws JoranException, IOException, - InterruptedException { - - String sysProp = "ch.qos.logback.classic.joran.JoranConfiguratorTest.timestampLocal"; - System.setProperty(sysProp, ""); - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "timestamp-local.xml"; - configure(configFileAsStr); - - // It's hard to test the local variable has been set, as it's not - // visible from here. But instead we test that it's not set in the - // context. And check that a system property has been replaced with the - // contents of the local variable - - String r = loggerContext.getProperty("testTimestamp"); - assertNull(r); - - String expected = "today is " - + new SimpleDateFormat("yyyy-MM").format(new Date()); - String sysPropValue = System.getProperty(sysProp); - assertEquals(expected, sysPropValue); - } - - @Test - public void encoderCharset() throws JoranException, IOException, - InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "encoderCharset.xml"; - configure(configFileAsStr); - - ConsoleAppender consoleAppender = (ConsoleAppender) root - .getAppender("CONSOLE"); - assertNotNull(consoleAppender); - LayoutWrappingEncoder encoder = (LayoutWrappingEncoder) consoleAppender - .getEncoder(); - - assertEquals("UTF-8", encoder.getCharset().displayName()); + @Test + public void level() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "simpleLevel.xml"); + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + String msg = "hello world"; + logger.debug(msg); + assertEquals(0, listAppender.list.size()); + } - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertIsErrorFree(); - } + @Test + public void additivity() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "additivity.xml"); + Logger logger = loggerContext.getLogger("additivityTest"); + assertFalse(logger.isAdditive()); + } - void verifyJULLevel(String loggerName, Level expectedLevel) { - java.util.logging.Logger julLogger = JULHelper.asJULLogger(loggerName); - java.util.logging.Level julLevel = julLogger.getLevel(); + @Test + public void rootLoggerLevelSettingBySystemProperty() throws JoranException { + String propertyName = "logback.level"; + + System.setProperty(propertyName, "INFO"); + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "rootLevelByProperty.xml"); + // StatusPrinter.print(loggerContext); + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + String msg = "hello world"; + logger.debug(msg); + assertEquals(0, listAppender.list.size()); + System.clearProperty(propertyName); + } - if (expectedLevel == null) { - assertNull(julLevel); - } else { - assertEquals(JULHelper.asJULLevel(expectedLevel), julLevel); + @Test + public void loggerLevelSettingBySystemProperty() throws JoranException { + String propertyName = "logback.level"; + System.setProperty(propertyName, "DEBUG"); + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "loggerLevelByProperty.xml"); + // StatusPrinter.print(loggerContext); + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + String msg = "hello world"; + logger.debug(msg); + assertEquals(1, listAppender.list.size()); + System.clearProperty(propertyName); } - } - - @Test - public void levelChangePropagator0() throws JoranException, IOException, - InterruptedException { - String loggerName = "changePropagator0" + diff; - java.util.logging.Logger.getLogger(loggerName).setLevel( - java.util.logging.Level.INFO); - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "/jul/levelChangePropagator0.xml"; - configure(configFileAsStr); - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertIsErrorFree(); - verifyJULLevel(loggerName, null); - verifyJULLevel("a.b.c." + diff, Level.WARN); - verifyJULLevel(Logger.ROOT_LOGGER_NAME, Level.TRACE); - } - - @Test - public void levelChangePropagator1() throws JoranException, IOException, InterruptedException { - String loggerName = "changePropagator1" + diff; - java.util.logging.Logger logger1 = java.util.logging.Logger.getLogger(loggerName); - logger1.setLevel(java.util.logging.Level.INFO); - verifyJULLevel(loggerName, Level.INFO); - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "/jul/levelChangePropagator1.xml"; - configure(configFileAsStr); - StatusChecker checker = new StatusChecker(loggerContext); - checker.assertIsErrorFree(); - verifyJULLevel(loggerName, Level.INFO); // - verifyJULLevel("a.b.c." + diff, Level.WARN); - verifyJULLevel(Logger.ROOT_LOGGER_NAME, Level.TRACE); - } - - @Test - @Ignore - public void onConsoleRetro() throws JoranException, IOException, - InterruptedException { - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "/onConsoleRetro.xml"; - configure(configFileAsStr); - System.out.println("xxxxxxxxxxxxx"); - Thread.sleep(400); - - loggerContext.reset(); - configure(configFileAsStr); - } - - @Test - public void lbcore193() throws JoranException { - String configFileAsStr = ClassicTestConstants.ISSUES_PREFIX - + "lbcore193.xml"; - configure(configFileAsStr); - checker.asssertContainsException(ScanException.class); - checker.assertContainsMatch(Status.ERROR, - "Expecting RIGHT_PARENTHESIS token but got null"); - checker.assertContainsMatch(Status.ERROR, "See also " - + Parser.MISSING_RIGHT_PARENTHESIS); - } - - @Test - public void properties() throws JoranException { - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "properties.xml"; - assertNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); - assertNull(System.getProperty("sys")); - - configure(configFileAsStr); - assertNotNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); - assertNull(loggerContext.getProperty("transientKey1")); - assertNull(loggerContext.getProperty("transientKey2")); - assertEquals("node0", loggerContext.getProperty("nodeId")); - assertEquals("tem", System.getProperty("sys")); - assertNotNull(loggerContext.getProperty("path")); - checker.assertIsErrorFree(); - } - - // see also http://jira.qos.ch/browse/LBCORE-254 - @Test - public void sysProps() throws JoranException { - System.setProperty("k.lbcore254", ClassicTestConstants.ISSUES_PREFIX - + "lbcore254"); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - configurator.doConfigure(ClassicTestConstants.ISSUES_PREFIX - + "lbcore254.xml"); - - checker.assertIsErrorFree(); - } - - @Test - public void packageDataDisabledByConfigAttribute() throws JoranException { - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "packagingDataDisabled.xml"; - configure(configFileAsStr); - assertFalse(loggerContext.isPackagingDataEnabled()); - } - - @Test - public void packageDataEnabledByConfigAttribute() throws JoranException { - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "packagingDataEnabled.xml"; - configure(configFileAsStr); - assertTrue(loggerContext.isPackagingDataEnabled()); - } + @Test + public void appenderRefSettingBySystemProperty() throws JoranException { + final String propertyName = "logback.appenderRef"; + System.setProperty(propertyName, "A"); + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "appenderRefByProperty.xml"); + final Logger logger = loggerContext.getLogger("ch.qos.logback.classic.joran"); + final ListAppender listAppender = (ListAppender) logger.getAppender("A"); + assertEquals(0, listAppender.list.size()); + final String msg = "hello world"; + logger.info(msg); + assertEquals(1, listAppender.list.size()); + System.clearProperty(propertyName); + } + + @Test + public void statusListener() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "statusListener.xml"); + } + + @Test + public void contextRename() throws JoranException { + loggerContext.setName(CoreConstants.DEFAULT_CONTEXT_NAME); + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "contextRename.xml"); + assertEquals("wombat", loggerContext.getName()); + } + + @Test + public void eval() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "callerData.xml"); + + String msg = "hello world"; + logger.debug("toto"); + logger.debug(msg); + + StringListAppender slAppender = (StringListAppender) loggerContext.getLogger("root").getAppender("STR_LIST"); + assertNotNull(slAppender); + assertEquals(2, slAppender.strList.size()); + assertTrue(slAppender.strList.get(0).contains(" DEBUG - toto")); + + String str1 = slAppender.strList.get(1); + assertTrue(str1.contains("Caller+0")); + assertTrue(str1.contains(" DEBUG - hello world")); + } + + @Test + public void turboFilter() throws JoranException { + // Although this test uses turbo filters, it only checks + // that Joran can see the xml element and create + // and place the relevant object correctly. + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turbo.xml"); + + TurboFilter filter = loggerContext.getTurboFilterList().get(0); + assertTrue(filter instanceof NOPTurboFilter); + } + + @Test + public void testTurboFilterWithStringList() throws JoranException { + // Although this test uses turbo filters, it only checks + // that Joran can see elements, and behave correctly + // that is call the addUser method and pass the correct values + // to that method. + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turbo2.xml"); + + // StatusPrinter.print(loggerContext.getStatusManager()); + + TurboFilter filter = loggerContext.getTurboFilterList().get(0); + assertTrue(filter instanceof DebugUsersTurboFilter); + DebugUsersTurboFilter dutf = (DebugUsersTurboFilter) filter; + assertEquals(2, dutf.getUsers().size()); + } + + @Test + public void testLevelFilter() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "levelFilter.xml"); + + // StatusPrinter.print(loggerContext); + + logger.warn("hello"); + logger.error("to be ignored"); + + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + + assertNotNull(listAppender); + assertEquals(1, listAppender.list.size()); + ILoggingEvent back = listAppender.list.get(0); + assertEquals(Level.WARN, back.getLevel()); + assertEquals("hello", back.getMessage()); + } + + @Test + public void testEvaluatorFilter() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "evaluatorFilter.xml"); + + // StatusPrinter.print(loggerContext); + + logger.warn("hello"); + logger.error("to be ignored"); + + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + + assertNotNull(listAppender); + assertEquals(1, listAppender.list.size()); + ILoggingEvent back = listAppender.list.get(0); + assertEquals(Level.WARN, back.getLevel()); + assertEquals("hello", back.getMessage()); + } + + @Test + public void testTurboDynamicThreshold() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turboDynamicThreshold.xml"); + + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + + // this one should be denied + MDC.put("userId", "user1"); + logger.debug("hello user1"); + // this one should log + MDC.put("userId", "user2"); + logger.debug("hello user2"); + + assertEquals(1, listAppender.list.size()); + ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); + assertEquals("hello user2", le.getMessage()); + } + + @Test + public void testTurboDynamicThreshold2() throws JoranException { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "turboDynamicThreshold2.xml"); + + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertEquals(0, listAppender.list.size()); + + // this one should log + MDC.put("userId", "user1"); + logger.debug("hello user1"); + // this one should log + MDC.put("userId", "user2"); + logger.debug("hello user2"); + // this one should fail + MDC.put("userId", "user3"); + logger.debug("hello user3"); + + assertEquals(2, listAppender.list.size()); + ILoggingEvent le = (ILoggingEvent) listAppender.list.get(0); + assertEquals("hello user1", le.getMessage()); + le = (ILoggingEvent) listAppender.list.get(1); + assertEquals("hello user2", le.getMessage()); + } + + // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter + @Test + public void autoscanShouldReconfigureOnFileChange() throws Exception { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "scan1.xml"; + configure(configFileAsStr); + + File file = new File(configFileAsStr); + file.setLastModified(System.currentTimeMillis()); + + Thread.sleep(10); + // scanning requires 16 logs + for (int i = 0; i < 16; i++) { + logger.debug("after " + i); + } + + loggerContext.getExecutorService().shutdown(); + loggerContext.getExecutorService().awaitTermination(1000, TimeUnit.MILLISECONDS); + + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertIsErrorFree(); + checker.assertContainsMatch(CoreConstants.RESET_MSG_PREFIX); + } + + @Test + public void timestamp() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "timestamp-context.xml"; + configure(configFileAsStr); + + String r = loggerContext.getProperty("testTimestamp"); + assertNotNull(r); + CachingDateFormatter sdf = new CachingDateFormatter("yyyy-MM"); + String expected = sdf.format(System.currentTimeMillis()); + assertEquals("expected \"" + expected + "\" but got " + r, expected, r); + } + + @Test + public void timestampLocal() throws JoranException, IOException, InterruptedException { + + String sysProp = "ch.qos.logback.classic.joran.JoranConfiguratorTest.timestampLocal"; + System.setProperty(sysProp, ""); + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "timestamp-local.xml"; + configure(configFileAsStr); + + // It's hard to test the local variable has been set, as it's not + // visible from here. But instead we test that it's not set in the + // context. And check that a system property has been replaced with the + // contents of the local variable + + String r = loggerContext.getProperty("testTimestamp"); + assertNull(r); + + String expected = "today is " + new SimpleDateFormat("yyyy-MM").format(new Date()); + String sysPropValue = System.getProperty(sysProp); + assertEquals(expected, sysPropValue); + } + + @Test + public void encoderCharset() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "encoderCharset.xml"; + configure(configFileAsStr); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CONSOLE"); + assertNotNull(consoleAppender); + LayoutWrappingEncoder encoder = (LayoutWrappingEncoder) consoleAppender.getEncoder(); + + assertEquals("UTF-8", encoder.getCharset().displayName()); + + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertIsErrorFree(); + } + + void verifyJULLevel(String loggerName, Level expectedLevel) { + java.util.logging.Logger julLogger = JULHelper.asJULLogger(loggerName); + java.util.logging.Level julLevel = julLogger.getLevel(); + + if (expectedLevel == null) { + assertNull(julLevel); + } else { + assertEquals(JULHelper.asJULLevel(expectedLevel), julLevel); + } + + } + + @Test + public void levelChangePropagator0() throws JoranException, IOException, InterruptedException { + String loggerName = "changePropagator0" + diff; + java.util.logging.Logger.getLogger(loggerName).setLevel(java.util.logging.Level.INFO); + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "/jul/levelChangePropagator0.xml"; + configure(configFileAsStr); + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertIsErrorFree(); + verifyJULLevel(loggerName, null); + verifyJULLevel("a.b.c." + diff, Level.WARN); + verifyJULLevel(Logger.ROOT_LOGGER_NAME, Level.TRACE); + } + + @Test + public void levelChangePropagator1() throws JoranException, IOException, InterruptedException { + String loggerName = "changePropagator1" + diff; + java.util.logging.Logger logger1 = java.util.logging.Logger.getLogger(loggerName); + logger1.setLevel(java.util.logging.Level.INFO); + verifyJULLevel(loggerName, Level.INFO); + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "/jul/levelChangePropagator1.xml"; + configure(configFileAsStr); + StatusChecker checker = new StatusChecker(loggerContext); + checker.assertIsErrorFree(); + verifyJULLevel(loggerName, Level.INFO); // + verifyJULLevel("a.b.c." + diff, Level.WARN); + verifyJULLevel(Logger.ROOT_LOGGER_NAME, Level.TRACE); + } + + @Test + @Ignore + public void onConsoleRetro() throws JoranException, IOException, InterruptedException { + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "/onConsoleRetro.xml"; + configure(configFileAsStr); + System.out.println("xxxxxxxxxxxxx"); + Thread.sleep(400); + + loggerContext.reset(); + configure(configFileAsStr); + } + + @Test + public void lbcore193() throws JoranException { + String configFileAsStr = ClassicTestConstants.ISSUES_PREFIX + "lbcore193.xml"; + configure(configFileAsStr); + checker.asssertContainsException(ScanException.class); + checker.assertContainsMatch(Status.ERROR, "Expecting RIGHT_PARENTHESIS token but got null"); + checker.assertContainsMatch(Status.ERROR, "See also " + Parser.MISSING_RIGHT_PARENTHESIS); + } + + @Test + public void properties() throws JoranException { + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "properties.xml"; + assertNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); + assertNull(System.getProperty("sys")); + + configure(configFileAsStr); + assertNotNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); + assertNull(loggerContext.getProperty("transientKey1")); + assertNull(loggerContext.getProperty("transientKey2")); + assertEquals("node0", loggerContext.getProperty("nodeId")); + assertEquals("tem", System.getProperty("sys")); + assertNotNull(loggerContext.getProperty("path")); + checker.assertIsErrorFree(); + } + + // see also http://jira.qos.ch/browse/LBCORE-254 + @Test + public void sysProps() throws JoranException { + System.setProperty("k.lbcore254", ClassicTestConstants.ISSUES_PREFIX + "lbcore254"); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(loggerContext); + configurator.doConfigure(ClassicTestConstants.ISSUES_PREFIX + "lbcore254.xml"); + + checker.assertIsErrorFree(); + } + + @Test + public void packageDataDisabledByConfigAttribute() throws JoranException { + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "packagingDataDisabled.xml"; + configure(configFileAsStr); + assertFalse(loggerContext.isPackagingDataEnabled()); + } + + @Test + public void packageDataEnabledByConfigAttribute() throws JoranException { + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "packagingDataEnabled.xml"; + configure(configFileAsStr); + assertTrue(loggerContext.isPackagingDataEnabled()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/joran/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/joran/PackageTest.java index aa79d0922cc7fd48618e731ea10749eaec72dff3..46ff15d9035401d81a22fff091b9e9d0bf2d2a65 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/joran/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/joran/PackageTest.java @@ -18,7 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { JoranConfiguratorTest.class, EvaluatorJoranTest.class, - ch.qos.logback.classic.joran.conditional.PackageTest.class }) +@SuiteClasses({ JoranConfiguratorTest.class, EvaluatorJoranTest.class, ch.qos.logback.classic.joran.conditional.PackageTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/ConditionalTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/ConditionalTest.java index e028001a84e74b4cc6a8ad6687a3f8872c7906f5..31e71e2b6c36f131cffa86d5fc64862130196b21 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/ConditionalTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/ConditionalTest.java @@ -40,116 +40,106 @@ import ch.qos.logback.core.util.StatusPrinter; public class ConditionalTest { - LoggerContext context = new LoggerContext(); - Logger root = context.getLogger(Logger.ROOT_LOGGER_NAME); - - int diff = RandomUtil.getPositiveInt(); - String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; - - @Before - public void setUp() throws UnknownHostException { - context.setName("c" + diff); - context.putProperty("randomOutputDir", randomOutputDir); - } - - @After - public void tearDown() { - StatusPrinter.printIfErrorsOccured(context); - } - - void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(context); - jc.doConfigure(file); - } - - @SuppressWarnings("rawtypes") - @Test - public void conditionalConsoleApp_IF_THEN_True() throws JoranException, - IOException, InterruptedException { - InetAddress localhost = InetAddress.getLocalHost(); - System.out.println("In conditionalConsoleApp_IF_THEN_True, canonicalHostName=\"" + localhost.getCanonicalHostName() + "] and hostNmae=\"" + localhost.getHostName() + "\""); - context.putProperty("aHost", localhost.getHostName()); - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "conditional/conditionalConsoleApp.xml"; - configure(configFileAsStr); - FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); - assertNotNull(fileAppender); - - ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); - assertNotNull(consoleAppender); - StatusChecker checker = new StatusChecker(context); - checker.assertIsErrorFree(); - } - - @SuppressWarnings("rawtypes") - @Test - public void conditionalConsoleApp_IF_THEN_False() throws JoranException, - IOException, InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "conditional/conditionalConsoleApp.xml"; - configure(configFileAsStr); - FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); - assertNotNull(fileAppender); - - ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); - assertNull(consoleAppender); - StatusChecker checker = new StatusChecker(context); - checker.assertIsErrorFree(); - } - - @SuppressWarnings("rawtypes") - @Test - public void conditionalConsoleApp_IF_THEN_ELSE() throws JoranException, - IOException, InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "conditional/conditionalConsoleApp_ELSE.xml"; - configure(configFileAsStr); - - FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); - assertNotNull(fileAppender); - - ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); - assertNull(consoleAppender); - - ListAppender listAppender = (ListAppender) root.getAppender("LIST"); - assertNotNull(listAppender); - - // StatusPrinter.printIfErrorsOccured(context); - StatusChecker checker = new StatusChecker(context); - checker.assertIsErrorFree(); - } - - @Test - public void conditionalInclusionWithExistingFile() throws JoranException, - IOException, InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "conditional/conditionalIncludeExistingFile.xml"; - configure(configFileAsStr); - - ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); - assertNotNull(consoleAppender); - StatusChecker checker = new StatusChecker(context); - checker.assertIsErrorFree(); - } - @Test - - public void conditionalInclusionWithInexistentFile() throws JoranException, - IOException, InterruptedException { - - String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX - + "conditional/conditionalIncludeInexistentFile.xml"; - configure(configFileAsStr); - - ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); - assertNull(consoleAppender); - StatusChecker checker = new StatusChecker(context); - checker.assertIsErrorFree(); - } - + LoggerContext context = new LoggerContext(); + Logger root = context.getLogger(Logger.ROOT_LOGGER_NAME); + + int diff = RandomUtil.getPositiveInt(); + String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; + + @Before + public void setUp() throws UnknownHostException { + context.setName("c" + diff); + context.putProperty("randomOutputDir", randomOutputDir); + } + + @After + public void tearDown() { + StatusPrinter.printIfErrorsOccured(context); + } + + void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(context); + jc.doConfigure(file); + } + + @SuppressWarnings("rawtypes") + @Test + public void conditionalConsoleApp_IF_THEN_True() throws JoranException, IOException, InterruptedException { + InetAddress localhost = InetAddress.getLocalHost(); + System.out.println("In conditionalConsoleApp_IF_THEN_True, canonicalHostName=\"" + localhost.getCanonicalHostName() + "] and hostNmae=\"" + + localhost.getHostName() + "\""); + context.putProperty("aHost", localhost.getHostName()); + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp.xml"; + configure(configFileAsStr); + FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); + assertNotNull(fileAppender); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); + assertNotNull(consoleAppender); + StatusChecker checker = new StatusChecker(context); + checker.assertIsErrorFree(); + } + + @SuppressWarnings("rawtypes") + @Test + public void conditionalConsoleApp_IF_THEN_False() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp.xml"; + configure(configFileAsStr); + FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); + assertNotNull(fileAppender); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); + assertNull(consoleAppender); + StatusChecker checker = new StatusChecker(context); + checker.assertIsErrorFree(); + } + + @SuppressWarnings("rawtypes") + @Test + public void conditionalConsoleApp_IF_THEN_ELSE() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalConsoleApp_ELSE.xml"; + configure(configFileAsStr); + + FileAppender fileAppender = (FileAppender) root.getAppender("FILE"); + assertNotNull(fileAppender); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); + assertNull(consoleAppender); + + ListAppender listAppender = (ListAppender) root.getAppender("LIST"); + assertNotNull(listAppender); + + // StatusPrinter.printIfErrorsOccured(context); + StatusChecker checker = new StatusChecker(context); + checker.assertIsErrorFree(); + } + + @Test + public void conditionalInclusionWithExistingFile() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalIncludeExistingFile.xml"; + configure(configFileAsStr); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); + assertNotNull(consoleAppender); + StatusChecker checker = new StatusChecker(context); + checker.assertIsErrorFree(); + } + + @Test + public void conditionalInclusionWithInexistentFile() throws JoranException, IOException, InterruptedException { + + String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "conditional/conditionalIncludeInexistentFile.xml"; + configure(configFileAsStr); + + ConsoleAppender consoleAppender = (ConsoleAppender) root.getAppender("CON"); + assertNull(consoleAppender); + StatusChecker checker = new StatusChecker(context); + checker.assertIsErrorFree(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/PackageTest.java index 135da48ae8847ab2cdd14e47cf51c29208147b53..c5b46918d1cb8891cf45056a8a12489ac0fc2235 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/joran/conditional/PackageTest.java @@ -17,8 +17,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; - @RunWith(Suite.class) -@SuiteClasses( { ConditionalTest.class}) +@SuiteClasses({ ConditionalTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/jul/LevelChangePropagatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/jul/LevelChangePropagatorTest.java index c3317440040c305a29ce402f541e3ae9349f240d..9e0177e8b8b70efbacc482ffe01c45b00db37e05 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/jul/LevelChangePropagatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/jul/LevelChangePropagatorTest.java @@ -26,72 +26,72 @@ import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; public class LevelChangePropagatorTest { - int rand = RandomUtil.getPositiveInt(); - LoggerContext loggerContext = new LoggerContext(); - LevelChangePropagator levelChangePropagator = new LevelChangePropagator(); - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @Before - public void setUp() { - levelChangePropagator.setContext(loggerContext); - loggerContext.addListener(levelChangePropagator); - } - - void checkLevelChange(String loggerName, Level level) { - Logger logger = loggerContext.getLogger(loggerName); - logger.setLevel(level); - java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); - java.util.logging.Level julLevel = JULHelper.asJULLevel(level); - - assertEquals(julLevel, julLogger.getLevel()); - } - - @Test - public void smoke() { - checkLevelChange("a", Level.INFO); - checkLevelChange("a.b", Level.DEBUG); - } - - @Test - public void root() { - checkLevelChange(Logger.ROOT_LOGGER_NAME, Level.TRACE); - } - - // see http://jira.qos.ch/browse/LBCLASSIC-256 - @Test - public void gc() { - Logger logger = loggerContext.getLogger("gc"+rand); - logger.setLevel(Level.INFO); - // invoke GC so that the relevant julLogger can be garbage collected. - System.gc(); - java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); - java.util.logging.Level julLevel = JULHelper.asJULLevel(Level.INFO); - - assertEquals(julLevel, julLogger.getLevel()); - } - - @Test - public void julHelperAsJulLevelRejectsNull() { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Unexpected level [null]"); - JULHelper.asJULLevel(null); - } - - @Test - public void settingLevelToNullGetsParentLevel() { - // first set level of "a" (the parent) to DEBUG - Logger parent = loggerContext.getLogger("a"); - parent.setLevel(Level.DEBUG); - - // then set level of "a.b" (child logger of a) to null - // for b to inherit its parent's level - Logger child = loggerContext.getLogger("a.b"); - child.setLevel(Level.INFO); - child.setLevel(null); - - assertEquals(parent.getEffectiveLevel(), child.getEffectiveLevel()); - assertEquals(Level.DEBUG, child.getEffectiveLevel()); - } + int rand = RandomUtil.getPositiveInt(); + LoggerContext loggerContext = new LoggerContext(); + LevelChangePropagator levelChangePropagator = new LevelChangePropagator(); + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Before + public void setUp() { + levelChangePropagator.setContext(loggerContext); + loggerContext.addListener(levelChangePropagator); + } + + void checkLevelChange(String loggerName, Level level) { + Logger logger = loggerContext.getLogger(loggerName); + logger.setLevel(level); + java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); + java.util.logging.Level julLevel = JULHelper.asJULLevel(level); + + assertEquals(julLevel, julLogger.getLevel()); + } + + @Test + public void smoke() { + checkLevelChange("a", Level.INFO); + checkLevelChange("a.b", Level.DEBUG); + } + + @Test + public void root() { + checkLevelChange(Logger.ROOT_LOGGER_NAME, Level.TRACE); + } + + // see http://jira.qos.ch/browse/LBCLASSIC-256 + @Test + public void gc() { + Logger logger = loggerContext.getLogger("gc" + rand); + logger.setLevel(Level.INFO); + // invoke GC so that the relevant julLogger can be garbage collected. + System.gc(); + java.util.logging.Logger julLogger = JULHelper.asJULLogger(logger); + java.util.logging.Level julLevel = JULHelper.asJULLevel(Level.INFO); + + assertEquals(julLevel, julLogger.getLevel()); + } + + @Test + public void julHelperAsJulLevelRejectsNull() { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("Unexpected level [null]"); + JULHelper.asJULLevel(null); + } + + @Test + public void settingLevelToNullGetsParentLevel() { + // first set level of "a" (the parent) to DEBUG + Logger parent = loggerContext.getLogger("a"); + parent.setLevel(Level.DEBUG); + + // then set level of "a.b" (child logger of a) to null + // for b to inherit its parent's level + Logger child = loggerContext.getLogger("a.b"); + child.setLevel(Level.INFO); + child.setLevel(null); + + assertEquals(parent.getEffectiveLevel(), child.getEffectiveLevel()); + assertEquals(Level.DEBUG, child.getEffectiveLevel()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/jul/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/jul/PackageTest.java index 8570d823ee303436bcc4bfe61ab8d7b46b1bf602..80e669bbd98fc9ac5cbb1c9e3c3742c327b75c31 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/jul/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/jul/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({LevelChangePropagatorTest.class}) +@SuiteClasses({ LevelChangePropagatorTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/log4j/XMLLayoutTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/log4j/XMLLayoutTest.java index 5455c92a021872900598620d28ada8a0a6d17ca4..1efa6cc912fd1d9eabf1729b8ec138680d99625a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/log4j/XMLLayoutTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/log4j/XMLLayoutTest.java @@ -49,167 +49,161 @@ import ch.qos.logback.classic.spi.LoggingEvent; */ public class XMLLayoutTest { - private static final String DOCTYPE = - ""; - private static final String NAMESPACE = "http://jakarta.apache.org/log4j/"; - private static final String DTD_URI = "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"; - - private static final String MDC_KEY = "key <&>'\"]]>"; - private static final String MDC_VALUE = "value <&>'\"]]>"; - - private static final String MESSAGE = "test message, <&>'\""; - - private LoggerContext lc; - private Logger root; - private XMLLayout layout; - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName("default"); - - layout = new XMLLayout(); - layout.setLocationInfo(true); - layout.setContext(lc); - layout.setProperties(true); - layout.setLocationInfo(true); - layout.start(); - - root = lc.getLogger(Logger.ROOT_LOGGER_NAME); - - } - - @After - public void tearDown() throws Exception { - lc = null; - layout = null; - MDC.clear(); - } - - @Test - public void testDoLayout() throws Exception { - ILoggingEvent le = createLoggingEvent(); - - String result = DOCTYPE+""; - if (layout.getFileHeader() != null) { - result += layout.getFileHeader(); - } - if (layout.getPresentationHeader() != null) { - result += layout.getPresentationHeader(); - } - result += layout.doLayout(le); - if (layout.getPresentationFooter() != null) { - result += layout.getPresentationFooter(); - } - if (layout.getFileFooter() != null) { - result += layout.getFileFooter(); + private static final String DOCTYPE = ""; + private static final String NAMESPACE = "http://jakarta.apache.org/log4j/"; + private static final String DTD_URI = "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd"; + + private static final String MDC_KEY = "key <&>'\"]]>"; + private static final String MDC_VALUE = "value <&>'\"]]>"; + + private static final String MESSAGE = "test message, <&>'\""; + + private LoggerContext lc; + private Logger root; + private XMLLayout layout; + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + lc.setName("default"); + + layout = new XMLLayout(); + layout.setLocationInfo(true); + layout.setContext(lc); + layout.setProperties(true); + layout.setLocationInfo(true); + layout.start(); + + root = lc.getLogger(Logger.ROOT_LOGGER_NAME); + } - result += ""; - - Document document = parse(result); - - XPath xpath = this.newXPath(); - - // Test log4j:event: - NodeList eventNodes = (NodeList) xpath.compile("//log4j:event") - .evaluate(document, XPathConstants.NODESET); - Assert.assertEquals(1, eventNodes.getLength()); - - // Test log4g:message: - Assert.assertEquals(MESSAGE, - xpath.compile("//log4j:message").evaluate(document, XPathConstants.STRING)); - - // Test log4j:data: - NodeList dataNodes = (NodeList) xpath.compile("//log4j:data") - .evaluate(document, XPathConstants.NODESET); - boolean foundMdc = false; - for (int i = 0; i != dataNodes.getLength(); ++i) { - Node dataNode = dataNodes.item(i); - if (dataNode.getAttributes().getNamedItem("name").getNodeValue().equals(MDC_KEY)) { - foundMdc = true; - Assert.assertEquals(MDC_VALUE, dataNode.getAttributes().getNamedItem("value").getNodeValue()); - break; - } + + @After + public void tearDown() throws Exception { + lc = null; + layout = null; + MDC.clear(); } - Assert.assertTrue(foundMdc); - } - - /** - * Create a XPath instance with xmlns:log4j="http://jakarta.apache.org/log4j/" - * - * @return XPath instance with log4 namespace - */ - private XPath newXPath() { - XPathFactory xPathfactory = XPathFactory.newInstance(); - XPath xpath = xPathfactory.newXPath(); - - xpath.setNamespaceContext(new NamespaceContext() { - @SuppressWarnings("rawtypes") - public Iterator getPrefixes(String namespaceURI) { - throw new UnsupportedOperationException(); - } - - public String getPrefix(String namespaceURI) { - throw new UnsupportedOperationException(); - } - - public String getNamespaceURI(String prefix) { - if ("log4j".equals(prefix)) { - return NAMESPACE; - } else { - return XMLConstants.NULL_NS_URI; + + @Test + public void testDoLayout() throws Exception { + ILoggingEvent le = createLoggingEvent(); + + String result = DOCTYPE + ""; + if (layout.getFileHeader() != null) { + result += layout.getFileHeader(); + } + if (layout.getPresentationHeader() != null) { + result += layout.getPresentationHeader(); } - } - }); - - return xpath; - } - - private LoggingEvent createLoggingEvent() { - MDC.put(MDC_KEY, MDC_VALUE); - LoggingEvent event = new LoggingEvent("com.example.XMLLayoutTest-<&>'\"]]>", root, - Level.DEBUG, MESSAGE, - new RuntimeException("Dummy exception: <&>'\"]]>"), null); - event.setThreadName("Dummy thread <&>'\""); - - StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); - StackTraceElement ste2 = new StackTraceElement("c2", "m2", "f2", 2); - event.setCallerData(new StackTraceElement[]{ ste1, ste2} ); - - return event; - } - - /** - * Parse and validate Log4j XML - * - * @param output Log4j XML - * @return Document - * @throws Exception - */ - private Document parse(String output) throws Exception { - - // Lookup the DTD in log4j.jar: - EntityResolver resolver = new EntityResolver() { - public InputSource resolveEntity(String publicId, String systemId) { - if (publicId == null && systemId != null && systemId.equals(DTD_URI)) { - final String path = "/org/apache/log4j/xml/log4j.dtd"; - InputStream in = - this.getClass().getResourceAsStream(path); - return new InputSource(in); - } else { - throw new RuntimeException("Not found"); + result += layout.doLayout(le); + if (layout.getPresentationFooter() != null) { + result += layout.getPresentationFooter(); } - } - }; + if (layout.getFileFooter() != null) { + result += layout.getFileFooter(); + } + result += ""; + + Document document = parse(result); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - factory.setValidating(true); + XPath xpath = this.newXPath(); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.setEntityResolver(resolver); + // Test log4j:event: + NodeList eventNodes = (NodeList) xpath.compile("//log4j:event").evaluate(document, XPathConstants.NODESET); + Assert.assertEquals(1, eventNodes.getLength()); - return builder.parse(new ByteArrayInputStream(output.getBytes("UTF-8"))); - } + // Test log4g:message: + Assert.assertEquals(MESSAGE, xpath.compile("//log4j:message").evaluate(document, XPathConstants.STRING)); + + // Test log4j:data: + NodeList dataNodes = (NodeList) xpath.compile("//log4j:data").evaluate(document, XPathConstants.NODESET); + boolean foundMdc = false; + for (int i = 0; i != dataNodes.getLength(); ++i) { + Node dataNode = dataNodes.item(i); + if (dataNode.getAttributes().getNamedItem("name").getNodeValue().equals(MDC_KEY)) { + foundMdc = true; + Assert.assertEquals(MDC_VALUE, dataNode.getAttributes().getNamedItem("value").getNodeValue()); + break; + } + } + Assert.assertTrue(foundMdc); + } + + /** + * Create a XPath instance with xmlns:log4j="http://jakarta.apache.org/log4j/" + * + * @return XPath instance with log4 namespace + */ + private XPath newXPath() { + XPathFactory xPathfactory = XPathFactory.newInstance(); + XPath xpath = xPathfactory.newXPath(); + + xpath.setNamespaceContext(new NamespaceContext() { + @SuppressWarnings("rawtypes") + public Iterator getPrefixes(String namespaceURI) { + throw new UnsupportedOperationException(); + } + + public String getPrefix(String namespaceURI) { + throw new UnsupportedOperationException(); + } + + public String getNamespaceURI(String prefix) { + if ("log4j".equals(prefix)) { + return NAMESPACE; + } else { + return XMLConstants.NULL_NS_URI; + } + } + }); + + return xpath; + } + + private LoggingEvent createLoggingEvent() { + MDC.put(MDC_KEY, MDC_VALUE); + LoggingEvent event = new LoggingEvent("com.example.XMLLayoutTest-<&>'\"]]>", root, Level.DEBUG, MESSAGE, new RuntimeException( + "Dummy exception: <&>'\"]]>"), null); + event.setThreadName("Dummy thread <&>'\""); + + StackTraceElement ste1 = new StackTraceElement("c1", "m1", "f1", 1); + StackTraceElement ste2 = new StackTraceElement("c2", "m2", "f2", 2); + event.setCallerData(new StackTraceElement[] { ste1, ste2 }); + + return event; + } + + /** + * Parse and validate Log4j XML + * + * @param output Log4j XML + * @return Document + * @throws Exception + */ + private Document parse(String output) throws Exception { + + // Lookup the DTD in log4j.jar: + EntityResolver resolver = new EntityResolver() { + public InputSource resolveEntity(String publicId, String systemId) { + if (publicId == null && systemId != null && systemId.equals(DTD_URI)) { + final String path = "/org/apache/log4j/xml/log4j.dtd"; + InputStream in = this.getClass().getResourceAsStream(path); + return new InputSource(in); + } else { + throw new RuntimeException("Not found"); + } + } + }; + + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setValidating(true); + + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.setEntityResolver(resolver); + + return builder.parse(new ByteArrayInputStream(output.getBytes("UTF-8"))); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/Checker.java b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/Checker.java index 1a993041e62728ecf9581e32311e9f35cec2934e..e6f4b622138ef01cc7caf3cb1abc04aa589f05a5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/Checker.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/Checker.java @@ -20,69 +20,60 @@ import java.util.regex.Pattern; public class Checker { - static long LEN; - static String FILENAME; + static long LEN; + static String FILENAME; - static void usage(String msg) { - System.err.println(msg); - System.err - .println("Usage: java " - + Checker.class.getName() - + " runLength filename stamp0 stamp1 ..stampN\n" - + " runLength (integer) the number of logs to generate perthread\n" - + " filename (string) the filename where to write\n" - + " stamp0 JVM instance stamp0\n" - + " stamp1 JVM instance stamp1\n"); - System.exit(1); - } - - public static void main(String[] argv) throws Exception { - if (argv.length < 3) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + Checker.class.getName() + " runLength filename stamp0 stamp1 ..stampN\n" + + " runLength (integer) the number of logs to generate perthread\n" + " filename (string) the filename where to write\n" + + " stamp0 JVM instance stamp0\n" + " stamp1 JVM instance stamp1\n"); + System.exit(1); } - LEN = Integer.parseInt(argv[0]); - FILENAME = argv[1]; + public static void main(String[] argv) throws Exception { + if (argv.length < 3) { + usage("Wrong number of arguments."); + } + + LEN = Integer.parseInt(argv[0]); + FILENAME = argv[1]; - for (int i = 2; i < argv.length; i++) { - check(argv[i], FILENAME, true); + for (int i = 2; i < argv.length; i++) { + check(argv[i], FILENAME, true); + } } - } - static void check(String stamp, String filename, boolean safetyMode) - throws Exception { + static void check(String stamp, String filename, boolean safetyMode) throws Exception { - FileReader fr = new FileReader(FILENAME); - BufferedReader br = new BufferedReader(fr); + FileReader fr = new FileReader(FILENAME); + BufferedReader br = new BufferedReader(fr); - String regExp = "^" + stamp + " DEBUG - " + LoggingThread.msgLong - + " (\\d+)$"; - Pattern p = Pattern.compile(regExp); + String regExp = "^" + stamp + " DEBUG - " + LoggingThread.msgLong + " (\\d+)$"; + Pattern p = Pattern.compile(regExp); - String line; - int expected = 0; - while ((line = br.readLine()) != null) { - Matcher m = p.matcher(line); - if (m.matches()) { - String g = m.group(1); - int num = Integer.parseInt(g); - if (num != expected) { - System.err.println("ERROR: out of sequence line: "); - System.err.println(line); - return; + String line; + int expected = 0; + while ((line = br.readLine()) != null) { + Matcher m = p.matcher(line); + if (m.matches()) { + String g = m.group(1); + int num = Integer.parseInt(g); + if (num != expected) { + System.err.println("ERROR: out of sequence line: "); + System.err.println(line); + return; + } + expected++; + } } - expected++; - } - } - if (expected != LEN) { - System.err.println("ERROR: For JVM stamp " + stamp + " found " + expected - + " was expecting " + LEN); - } else { - System.out.println("For JVM stamp " + stamp + " found " + LEN - + " lines in correct sequence"); + if (expected != LEN) { + System.err.println("ERROR: For JVM stamp " + stamp + " found " + expected + " was expecting " + LEN); + } else { + System.out.println("For JVM stamp " + stamp + " found " + LEN + " lines in correct sequence"); + } + fr.close(); + br.close(); } - fr.close(); - br.close(); - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/FileAppenderPerf.java b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/FileAppenderPerf.java index c7266dbfa98cbcd9f59cadde9c6db97748102fc6..2565a773978f5627c4579c3d496e9d65489a66dd 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/FileAppenderPerf.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/FileAppenderPerf.java @@ -22,76 +22,72 @@ import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.testUtil.RandomUtil; public class FileAppenderPerf { - static String msgLong = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; + static String msgLong = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; - static long LEN = 100 * 1000; - static int DIFF = RandomUtil.getPositiveInt() % 1000; - static String FILENAME; + static long LEN = 100 * 1000; + static int DIFF = RandomUtil.getPositiveInt() % 1000; + static String FILENAME; - static LoggerContext buildLoggerContext(String filename, boolean safetyMode) { - LoggerContext loggerContext = new LoggerContext(); + static LoggerContext buildLoggerContext(String filename, boolean safetyMode) { + LoggerContext loggerContext = new LoggerContext(); - FileAppender fa = new FileAppender(); + FileAppender fa = new FileAppender(); - PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); - patternLayout.setPattern("%5p %c - %m%n"); - patternLayout.setContext(loggerContext); - patternLayout.start(); + PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); + patternLayout.setPattern("%5p %c - %m%n"); + patternLayout.setContext(loggerContext); + patternLayout.start(); - fa.setEncoder(patternLayout); - fa.setFile(filename); - fa.setAppend(false); - fa.setPrudent(safetyMode); - fa.setContext(loggerContext); - fa.start(); + fa.setEncoder(patternLayout); + fa.setFile(filename); + fa.setAppend(false); + fa.setPrudent(safetyMode); + fa.setContext(loggerContext); + fa.start(); - ch.qos.logback.classic.Logger root = loggerContext - .getLogger(Logger.ROOT_LOGGER_NAME); - root.addAppender(fa); + ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + root.addAppender(fa); - return loggerContext; - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + FileAppenderPerf.class.getName() - + " filename"); - - System.exit(1); - } - - public static void main(String[] argv) throws Exception { - if (argv.length > 1) { - usage("Wrong number of arguments."); + return loggerContext; } - if (argv.length == 0) { - FILENAME = DIFF+""; - } else { - FILENAME = argv[0]; + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + FileAppenderPerf.class.getName() + " filename"); + + System.exit(1); } - perfCase(false); - perfCase(true); - } + public static void main(String[] argv) throws Exception { + if (argv.length > 1) { + usage("Wrong number of arguments."); + } - static void perfCase(boolean safetyMode) throws Exception { - LoggerContext lc = buildLoggerContext(FILENAME + "-" + safetyMode + ".log", - safetyMode); - Logger logger = lc.getLogger(FileAppenderPerf.class); + if (argv.length == 0) { + FILENAME = DIFF + ""; + } else { + FILENAME = argv[0]; + } - long start = System.nanoTime(); - for (int i = 0; i < LEN; i++) { - logger.debug(msgLong + " " + i); + perfCase(false); + perfCase(true); } - // in microseconds - double durationPerLog = (System.nanoTime() - start) / (LEN * 1000.0); - lc.stop(); + static void perfCase(boolean safetyMode) throws Exception { + LoggerContext lc = buildLoggerContext(FILENAME + "-" + safetyMode + ".log", safetyMode); + Logger logger = lc.getLogger(FileAppenderPerf.class); - System.out.println("Average duration of " + (durationPerLog) - + " microseconds per log. Prudent mode=" + safetyMode); - System.out.println("------------------------------------------------"); - } + long start = System.nanoTime(); + for (int i = 0; i < LEN; i++) { + logger.debug(msgLong + " " + i); + } + // in microseconds + double durationPerLog = (System.nanoTime() - start) / (LEN * 1000.0); + + lc.stop(); + + System.out.println("Average duration of " + (durationPerLog) + " microseconds per log. Prudent mode=" + safetyMode); + System.out.println("------------------------------------------------"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/LoggingThread.java b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/LoggingThread.java index 7c868376246afa3fac626ff329a2d99348547dfa..6afd767117e8b6d61e84c0efef4b7fc0081c00bf 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/LoggingThread.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/LoggingThread.java @@ -16,33 +16,32 @@ package ch.qos.logback.classic.multiJVM; import org.slf4j.Logger; public class LoggingThread extends Thread { - static String msgLong = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + static String msgLong = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - final long len; - final Logger logger; - private double durationPerLog; + final long len; + final Logger logger; + private double durationPerLog; - public LoggingThread(Logger logger, long len) { - this.logger = logger; - this.len = len; - } + public LoggingThread(Logger logger, long len) { + this.logger = logger; + this.len = len; + } + + public void run() { + long before = System.nanoTime(); + for (int i = 0; i < len; i++) { + logger.debug(msgLong + " " + i); + // try { + // Thread.sleep(100); + // } catch (InterruptedException e) { + // } + } + // in microseconds + durationPerLog = (System.nanoTime() - before) / (len * 1000.0); + } - public void run() { - long before = System.nanoTime(); - for (int i = 0; i < len; i++) { - logger.debug(msgLong + " " + i); -// try { -// Thread.sleep(100); -// } catch (InterruptedException e) { -// } + public double getDurationPerLogInMicroseconds() { + return durationPerLog; } - // in microseconds - durationPerLog = (System.nanoTime() - before) / (len * 1000.0); - } - public double getDurationPerLogInMicroseconds() { - return durationPerLog; - } - - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeFileAppender.java b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeFileAppender.java index 03a7fb7dc339367abad8ac77f196f39115a4bc9a..94f14bc6240e906b2a0f78a9e9c9f0e17cee965d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeFileAppender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeFileAppender.java @@ -28,69 +28,63 @@ import ch.qos.logback.core.FileAppender; */ public class SafeModeFileAppender { - static long LEN; - static String FILENAME; - static String STAMP; + static long LEN; + static String FILENAME; + static String STAMP; + + static public void main(String[] argv) throws Exception { + if (argv.length != 3) { + usage("Wrong number of arguments."); + } + + STAMP = argv[0]; + LEN = Integer.parseInt(argv[1]); + FILENAME = argv[2]; + writeContinously(STAMP, FILENAME, true); + } - static public void main(String[] argv) throws Exception { - if (argv.length != 3) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SafeModeFileAppender.class.getName() + " stamp runLength filename\n" + " stamp JVM instance stamp\n" + + " runLength (integer) the number of logs to generate perthread" + " filename (string) the filename where to write\n"); + System.exit(1); } - STAMP = argv[0]; - LEN = Integer.parseInt(argv[1]); - FILENAME = argv[2]; - writeContinously(STAMP, FILENAME, true); - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SafeModeFileAppender.class.getName() - + " stamp runLength filename\n" + " stamp JVM instance stamp\n" - + " runLength (integer) the number of logs to generate perthread" - + " filename (string) the filename where to write\n"); - System.exit(1); - } - - static LoggerContext buildLoggerContext(String stamp, String filename, - boolean safetyMode) { - LoggerContext loggerContext = new LoggerContext(); - - FileAppender fa = new FileAppender(); - - PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); - patternLayout.setPattern(stamp + " %5p - %m%n"); - patternLayout.setContext(loggerContext); - patternLayout.start(); - - fa.setEncoder(patternLayout); - fa.setFile(filename); - fa.setAppend(true); - fa.setPrudent(safetyMode); - fa.setContext(loggerContext); - fa.start(); - - ch.qos.logback.classic.Logger root = loggerContext - .getLogger(Logger.ROOT_LOGGER_NAME); - root.addAppender(fa); - - return loggerContext; - } - - static void writeContinously(String stamp, String filename, boolean safetyMode) - throws Exception { - LoggerContext lc = buildLoggerContext(stamp, filename, safetyMode); - Logger logger = lc.getLogger(SafeModeFileAppender.class); - - long before = System.nanoTime(); - for (int i = 0; i < LEN; i++) { - logger.debug(LoggingThread.msgLong + " " + i); + static LoggerContext buildLoggerContext(String stamp, String filename, boolean safetyMode) { + LoggerContext loggerContext = new LoggerContext(); + + FileAppender fa = new FileAppender(); + + PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); + patternLayout.setPattern(stamp + " %5p - %m%n"); + patternLayout.setContext(loggerContext); + patternLayout.start(); + + fa.setEncoder(patternLayout); + fa.setFile(filename); + fa.setAppend(true); + fa.setPrudent(safetyMode); + fa.setContext(loggerContext); + fa.start(); + + ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + root.addAppender(fa); + + return loggerContext; } - lc.stop(); - double durationPerLog = (System.nanoTime() - before) / (LEN * 1000.0); - System.out.println("Average duration of " + (durationPerLog) - + " microseconds per log. Safety mode " + safetyMode); - System.out.println("------------------------------------------------"); - } + static void writeContinously(String stamp, String filename, boolean safetyMode) throws Exception { + LoggerContext lc = buildLoggerContext(stamp, filename, safetyMode); + Logger logger = lc.getLogger(SafeModeFileAppender.class); + + long before = System.nanoTime(); + for (int i = 0; i < LEN; i++) { + logger.debug(LoggingThread.msgLong + " " + i); + } + lc.stop(); + double durationPerLog = (System.nanoTime() - before) / (LEN * 1000.0); + + System.out.println("Average duration of " + (durationPerLog) + " microseconds per log. Safety mode " + safetyMode); + System.out.println("------------------------------------------------"); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeRollingFileAppender.java b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeRollingFileAppender.java index 8154d06361f1771df0476f0b4cfb8bebbe853ece..6021d67401cb9f7ddf20534da268d2dc1ccae86e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeRollingFileAppender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/multiJVM/SafeModeRollingFileAppender.java @@ -30,82 +30,75 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class SafeModeRollingFileAppender { - static long LEN; - static String FILENAME; - static String STAMP; - - static final String DATE_PATTERN = "yyyy-MM-dd_HH_mm_ss"; - - static public void main(String[] argv) throws Exception { - if (argv.length != 3) { - usage("Wrong number of arguments."); + static long LEN; + static String FILENAME; + static String STAMP; + + static final String DATE_PATTERN = "yyyy-MM-dd_HH_mm_ss"; + + static public void main(String[] argv) throws Exception { + if (argv.length != 3) { + usage("Wrong number of arguments."); + } + + STAMP = argv[0]; + LEN = Integer.parseInt(argv[1]); + FILENAME = argv[2]; + writeContinously(STAMP, FILENAME, true); + } + + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SafeModeRollingFileAppender.class.getName() + " stamp runLength filename\n" + " stamp JVM instance stamp\n" + + " runLength (integer) the number of logs to generate perthread" + " filename (string) the filename where to write\n"); + System.exit(1); + } + + static LoggerContext buildLoggerContext(String stamp, String filename, boolean safetyMode) { + LoggerContext loggerContext = new LoggerContext(); + + RollingFileAppender rfa = new RollingFileAppender(); + PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); + patternLayout.setPattern(stamp + " %5p - %-50m%n"); + patternLayout.setContext(loggerContext); + patternLayout.start(); + + rfa.setEncoder(patternLayout); + + rfa.setAppend(true); + rfa.setPrudent(safetyMode); + rfa.setContext(loggerContext); + + TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); + + tbrp.setContext(loggerContext); + tbrp.setFileNamePattern(filename + "-%d{" + DATE_PATTERN + "}.log"); + tbrp.setParent(rfa); + tbrp.start(); + + rfa.setRollingPolicy(tbrp); + + rfa.start(); + + ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + root.addAppender(rfa); + + return loggerContext; } - STAMP = argv[0]; - LEN = Integer.parseInt(argv[1]); - FILENAME = argv[2]; - writeContinously(STAMP, FILENAME, true); - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SafeModeRollingFileAppender.class.getName() - + " stamp runLength filename\n" + " stamp JVM instance stamp\n" - + " runLength (integer) the number of logs to generate perthread" - + " filename (string) the filename where to write\n"); - System.exit(1); - } - - static LoggerContext buildLoggerContext(String stamp, String filename, - boolean safetyMode) { - LoggerContext loggerContext = new LoggerContext(); - - RollingFileAppender rfa = new RollingFileAppender(); - PatternLayoutEncoder patternLayout = new PatternLayoutEncoder(); - patternLayout.setPattern(stamp + " %5p - %-50m%n"); - patternLayout.setContext(loggerContext); - patternLayout.start(); - - rfa.setEncoder(patternLayout); - - rfa.setAppend(true); - rfa.setPrudent(safetyMode); - rfa.setContext(loggerContext); - - TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); - - tbrp.setContext(loggerContext); - tbrp.setFileNamePattern(filename+"-%d{"+DATE_PATTERN+"}.log"); - tbrp.setParent(rfa); - tbrp.start(); - - rfa.setRollingPolicy(tbrp); - - - rfa.start(); - - ch.qos.logback.classic.Logger root = loggerContext - .getLogger(Logger.ROOT_LOGGER_NAME); - root.addAppender(rfa); - - return loggerContext; - } - - static void writeContinously(String stamp, String filename, boolean safetyMode) - throws Exception { - LoggerContext lc = buildLoggerContext(stamp, filename, safetyMode); - Logger logger = lc.getLogger(SafeModeRollingFileAppender.class); - - long before = System.nanoTime(); - for (int i = 0; i < LEN; i++) { - logger.debug(LoggingThread.msgLong + " " + i); + static void writeContinously(String stamp, String filename, boolean safetyMode) throws Exception { + LoggerContext lc = buildLoggerContext(stamp, filename, safetyMode); + Logger logger = lc.getLogger(SafeModeRollingFileAppender.class); + + long before = System.nanoTime(); + for (int i = 0; i < LEN; i++) { + logger.debug(LoggingThread.msgLong + " " + i); + } + lc.stop(); + StatusPrinter.print(lc); + double durationPerLog = (System.nanoTime() - before) / (LEN * 1000.0); + + System.out.println("Average duration of " + (durationPerLog) + " microseconds per log. Safety mode " + safetyMode); + System.out.println("------------------------------------------------"); } - lc.stop(); - StatusPrinter.print(lc); - double durationPerLog = (System.nanoTime() - before) / (LEN * 1000.0); - - System.out.println("Average duration of " + (durationPerLog) - + " microseconds per log. Safety mode " + safetyMode); - System.out.println("------------------------------------------------"); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/CounterBasedEvaluator.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/CounterBasedEvaluator.java index bce416cf711aa75d9b6152352dd3e9b9b1a7237d..99653a84bed49a88091dbebc636085d42a4d1fcb 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/CounterBasedEvaluator.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/CounterBasedEvaluator.java @@ -25,51 +25,49 @@ import ch.qos.logback.core.spi.ContextAwareBase; */ public class CounterBasedEvaluator extends ContextAwareBase implements EventEvaluator { - static int DEFAULT_LIMIT = 1024; - int limit = DEFAULT_LIMIT; - int counter = 0; - String name; - boolean started; + static int DEFAULT_LIMIT = 1024; + int limit = DEFAULT_LIMIT; + int counter = 0; + String name; + boolean started; - public boolean evaluate(Object event) throws NullPointerException, - EvaluationException { - counter++; + public boolean evaluate(Object event) throws NullPointerException, EvaluationException { + counter++; - if (counter == limit) { - counter = 0; - return true; - } else { - return false; + if (counter == limit) { + counter = 0; + return true; + } else { + return false; + } } - } - public String getName() { - return name; - } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } - public void setName(String name) { - this.name = name; - } + public boolean isStarted() { + return started; + } - public boolean isStarted() { - return started; - } + public void start() { + started = true; + } - public void start() { - started = true; - } + public void stop() { + started = false; + } - public void stop() { - started = false; - } + public int getLimit() { + return limit; + } - public int getLimit() { - return limit; - } + public void setLimit(int limit) { + this.limit = limit; + } - public void setLimit(int limit) { - this.limit = limit; - } - - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/DilutedSMTPAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/DilutedSMTPAppenderTest.java index aabb7eb9bcfb400e4881e402058e336fc9d051bb..21e5ab14902696bf9437d1b1a6881c16fe68718c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/DilutedSMTPAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/DilutedSMTPAppenderTest.java @@ -35,81 +35,78 @@ import ch.qos.logback.core.Layout; public class DilutedSMTPAppenderTest { - SMTPAppender appender; - CyclicBufferTracker cbTracker; - CyclicBuffer cb; - - @Before - public void setUp() throws Exception { - LoggerContext lc = new LoggerContext(); - appender = new SMTPAppender(); - appender.setContext(lc); - appender.setName("smtp"); - appender.setFrom("user@host.dom"); - appender.setLayout(buildLayout(lc)); - appender.setSMTPHost("mail2.qos.ch"); - appender.setSubject("logging report"); - appender.addTo("sebastien.nospam@qos.ch"); - appender.start(); - cbTracker = appender.getCyclicBufferTracker(); - cb = cbTracker.getOrCreate("", 0); - - } - - private static Layout buildLayout(LoggerContext lc) { - PatternLayout layout = new PatternLayout(); - layout.setContext(lc); - layout.setFileHeader("Some header\n"); - layout.setPattern("%-4relative [%thread] %-5level %class - %msg%n"); - layout.setFileFooter("Some footer"); - layout.start(); - return layout; - } - - @After - public void tearDown() throws Exception { - appender = null; - } - - @Test - public void testStart() { - assertEquals("sebastien.nospam@qos.ch%nopex", appender.getToAsListOfString().get(0)); - - assertEquals("logging report", appender.getSubject()); - - assertTrue(appender.isStarted()); - } - - @Test - public void testAppendNonTriggeringEvent() { - LoggingEvent event = new LoggingEvent(); - event.setThreadName("thead name"); - event.setLevel(Level.DEBUG); - appender.subAppend(cb, event); - assertEquals(1, cb.length()); - } - - @Test - public void testEntryConditionsCheck() { - appender.checkEntryConditions(); - assertEquals(0, appender.getContext().getStatusManager().getCount()); - } - - @Test - public void testTriggeringPolicy() { - appender.setEvaluator(null); - appender.checkEntryConditions(); - assertEquals(1, appender.getContext().getStatusManager().getCount()); - } - - @Test - public void testEntryConditionsCheckNoLayout() { - appender.setLayout(null); - appender.checkEntryConditions(); - assertEquals(1, appender.getContext().getStatusManager().getCount()); - } - - - - + SMTPAppender appender; + CyclicBufferTracker cbTracker; + CyclicBuffer cb; + + @Before + public void setUp() throws Exception { + LoggerContext lc = new LoggerContext(); + appender = new SMTPAppender(); + appender.setContext(lc); + appender.setName("smtp"); + appender.setFrom("user@host.dom"); + appender.setLayout(buildLayout(lc)); + appender.setSMTPHost("mail2.qos.ch"); + appender.setSubject("logging report"); + appender.addTo("sebastien.nospam@qos.ch"); + appender.start(); + cbTracker = appender.getCyclicBufferTracker(); + cb = cbTracker.getOrCreate("", 0); + + } + + private static Layout buildLayout(LoggerContext lc) { + PatternLayout layout = new PatternLayout(); + layout.setContext(lc); + layout.setFileHeader("Some header\n"); + layout.setPattern("%-4relative [%thread] %-5level %class - %msg%n"); + layout.setFileFooter("Some footer"); + layout.start(); + return layout; + } + + @After + public void tearDown() throws Exception { + appender = null; + } + + @Test + public void testStart() { + assertEquals("sebastien.nospam@qos.ch%nopex", appender.getToAsListOfString().get(0)); + + assertEquals("logging report", appender.getSubject()); + + assertTrue(appender.isStarted()); + } + + @Test + public void testAppendNonTriggeringEvent() { + LoggingEvent event = new LoggingEvent(); + event.setThreadName("thead name"); + event.setLevel(Level.DEBUG); + appender.subAppend(cb, event); + assertEquals(1, cb.length()); + } + + @Test + public void testEntryConditionsCheck() { + appender.checkEntryConditions(); + assertEquals(0, appender.getContext().getStatusManager().getCount()); + } + + @Test + public void testTriggeringPolicy() { + appender.setEvaluator(null); + appender.checkEntryConditions(); + assertEquals(1, appender.getContext().getStatusManager().getCount()); + } + + @Test + public void testEntryConditionsCheckNoLayout() { + appender.setLayout(null); + appender.checkEntryConditions(); + assertEquals(1, appender.getContext().getStatusManager().getCount()); + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/ExternalMockSocketServer.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/ExternalMockSocketServer.java index 90849630c98a8675c896572a11ad1f282d11c1ec..463ba1c91e732023e7fe28cc3f9731aa0959f1bc 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/ExternalMockSocketServer.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/ExternalMockSocketServer.java @@ -21,73 +21,71 @@ import java.util.List; public class ExternalMockSocketServer { - static final String LOGGINGEVENT = "LoggingEvent"; - static final String LOGGINGEVENT2 = "LoggingEvent2"; - static final String MINIMALEXT = "MinimalExt"; - static final String MINIMALSER = "MinimalSer"; + static final String LOGGINGEVENT = "LoggingEvent"; + static final String LOGGINGEVENT2 = "LoggingEvent2"; + static final String MINIMALEXT = "MinimalExt"; + static final String MINIMALSER = "MinimalSer"; - static final int PORT = 4560; + static final int PORT = 4560; - //static int loopLen; - static int clientNumber; + // static int loopLen; + static int clientNumber; - static List msgList = new ArrayList(); - static boolean finished = false; + static List msgList = new ArrayList(); + static boolean finished = false; - String className = LOGGINGEVENT; + String className = LOGGINGEVENT; - public static void main(String[] args) { - if (args.length == 1) { - clientNumber = Integer.parseInt(args[0]); - //loopLen = Integer.parseInt((args[1])); - runServer(); - } else { - usage("Wrong number of arguments."); - } - } + public static void main(String[] args) { + if (args.length == 1) { + clientNumber = Integer.parseInt(args[0]); + // loopLen = Integer.parseInt((args[1])); + runServer(); + } else { + usage("Wrong number of arguments."); + } + } - static void usage(String msg) { - System.err.println(msg); - System.err - .println("Usage: java " + ExternalMockSocketServer.class.getName() - + " loopNumber"); - System.exit(1); - } + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + ExternalMockSocketServer.class.getName() + " loopNumber"); + System.exit(1); + } - static void runServer() { + static void runServer() { - try { - System.out.println("Starting Server..."); - ServerSocket serverSocket = new ServerSocket(PORT); - System.out.println("Listening on port " + PORT); - for (int j = 0; j < clientNumber; j++) { - Socket socket = serverSocket.accept(); - System.out.println("New client accepted."); - System.out.println("Connected to client at " + socket.getInetAddress()); + try { + System.out.println("Starting Server..."); + ServerSocket serverSocket = new ServerSocket(PORT); + System.out.println("Listening on port " + PORT); + for (int j = 0; j < clientNumber; j++) { + Socket socket = serverSocket.accept(); + System.out.println("New client accepted."); + System.out.println("Connected to client at " + socket.getInetAddress()); - InputStream is = socket.getInputStream(); - long sum = 0; - - while (true) { - // this call is blocking - int val = is.read(); - if(val == -1) { - break; - } - // if a byte is available, we skip it. - // this allows to pass all available bytes in a quick manner. - int a = is.available(); - sum += a + 1; - is.skip(a); - } - System.out.println(sum/1000 + " KB"); - } - serverSocket.close(); - } catch (Exception se) { - se.printStackTrace(); - } - System.out.println("Server finished."); - finished = true; - } + InputStream is = socket.getInputStream(); + long sum = 0; + + while (true) { + // this call is blocking + int val = is.read(); + if (val == -1) { + break; + } + // if a byte is available, we skip it. + // this allows to pass all available bytes in a quick manner. + int a = is.available(); + sum += a + 1; + is.skip(a); + } + System.out.println(sum / 1000 + " KB"); + } + serverSocket.close(); + } catch (Exception se) { + se.printStackTrace(); + } + System.out.println("Server finished."); + finished = true; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTest.java index 44967e929ef67687c7622a886807d09bc93ababa..c7c332e6e002356c0e07df33abe6cd07bf15565d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTest.java @@ -31,113 +31,113 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; public class JMSQueueAppenderTest extends TestCase { - ch.qos.logback.core.Context context; - JMSQueueAppender appender; - PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - - @Override - protected void setUp() throws Exception { - context = new ContextBase(); - appender = new JMSQueueAppender(); - appender.setContext(context); - appender.setName("jmsQueue"); - appender.qcfBindingName = "queueCnxFactory"; - appender.queueBindingName = "testQueue"; - appender.setProviderURL("url"); - appender.setInitialContextFactoryName(MockInitialContextFactory.class.getName()); - - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(appender.qcfBindingName, new MockQueueConnectionFactory()); - mic.map.put(appender.queueBindingName, new MockQueue(appender.queueBindingName)); - - super.setUp(); - } - - @Override - protected void tearDown() throws Exception { - appender = null; - context = null; - super.tearDown(); - } - - public void testAppendOk() { - appender.start(); - - ILoggingEvent le = createLoggingEvent(); - appender.append(le); - - MockQueueSender qs = (MockQueueSender)appender.queueSender; - assertEquals(1, qs.getMessageList().size()); - ObjectMessage message = (ObjectMessage) qs.getMessageList().get(0); - try { - Serializable witness = pst.transform(le); - assertEquals(witness, message.getObject()); - } catch (Exception e) { - fail(); + ch.qos.logback.core.Context context; + JMSQueueAppender appender; + PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + @Override + protected void setUp() throws Exception { + context = new ContextBase(); + appender = new JMSQueueAppender(); + appender.setContext(context); + appender.setName("jmsQueue"); + appender.qcfBindingName = "queueCnxFactory"; + appender.queueBindingName = "testQueue"; + appender.setProviderURL("url"); + appender.setInitialContextFactoryName(MockInitialContextFactory.class.getName()); + + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(appender.qcfBindingName, new MockQueueConnectionFactory()); + mic.map.put(appender.queueBindingName, new MockQueue(appender.queueBindingName)); + + super.setUp(); } - } - - public void testAppendFailure() { - appender.start(); - - //make sure the append method does not work - appender.queueSender = null; - - ILoggingEvent le = createLoggingEvent(); - for (int i = 1; i <= 3; i++) { - appender.append(le); - assertEquals(i, context.getStatusManager().getCount()); - assertTrue(appender.isStarted()); + + @Override + protected void tearDown() throws Exception { + appender = null; + context = null; + super.tearDown(); } - appender.append(le); - assertEquals(4, context.getStatusManager().getCount()); - assertFalse(appender.isStarted()); - } - - public void testStartMinimalInfo() { - //let's leave only what's in the setup() - //method, minus the providerURL - appender.setProviderURL(null); - appender.start(); - - assertTrue(appender.isStarted()); - - try { - assertEquals(appender.queueBindingName, appender.queueSender.getQueue().getQueueName()); - } catch (Exception e) { - fail(); + + public void testAppendOk() { + appender.start(); + + ILoggingEvent le = createLoggingEvent(); + appender.append(le); + + MockQueueSender qs = (MockQueueSender) appender.queueSender; + assertEquals(1, qs.getMessageList().size()); + ObjectMessage message = (ObjectMessage) qs.getMessageList().get(0); + try { + Serializable witness = pst.transform(le); + assertEquals(witness, message.getObject()); + } catch (Exception e) { + fail(); + } } - } - - public void testStartUserPass() { - appender.setUserName("test"); - appender.setPassword("test"); - - appender.start(); - - assertTrue(appender.isStarted()); - - try { - assertEquals(appender.queueBindingName, appender.queueSender.getQueue().getQueueName()); - } catch (Exception e) { - fail(); + + public void testAppendFailure() { + appender.start(); + + // make sure the append method does not work + appender.queueSender = null; + + ILoggingEvent le = createLoggingEvent(); + for (int i = 1; i <= 3; i++) { + appender.append(le); + assertEquals(i, context.getStatusManager().getCount()); + assertTrue(appender.isStarted()); + } + appender.append(le); + assertEquals(4, context.getStatusManager().getCount()); + assertFalse(appender.isStarted()); + } + + public void testStartMinimalInfo() { + // let's leave only what's in the setup() + // method, minus the providerURL + appender.setProviderURL(null); + appender.start(); + + assertTrue(appender.isStarted()); + + try { + assertEquals(appender.queueBindingName, appender.queueSender.getQueue().getQueueName()); + } catch (Exception e) { + fail(); + } + } + + public void testStartUserPass() { + appender.setUserName("test"); + appender.setPassword("test"); + + appender.start(); + + assertTrue(appender.isStarted()); + + try { + assertEquals(appender.queueBindingName, appender.queueSender.getQueue().getQueueName()); + } catch (Exception e) { + fail(); + } + } + + public void testStartFails() { + appender.queueBindingName = null; + + appender.start(); + + assertFalse(appender.isStarted()); + } + + private ILoggingEvent createLoggingEvent() { + LoggingEvent le = new LoggingEvent(); + le.setLevel(Level.DEBUG); + le.setMessage("test message"); + le.setTimeStamp(System.currentTimeMillis()); + le.setThreadName(Thread.currentThread().getName()); + return le; } - } - - public void testStartFails() { - appender.queueBindingName = null; - - appender.start(); - - assertFalse(appender.isStarted()); - } - - private ILoggingEvent createLoggingEvent() { - LoggingEvent le = new LoggingEvent(); - le.setLevel(Level.DEBUG); - le.setMessage("test message"); - le.setTimeStamp(System.currentTimeMillis()); - le.setThreadName(Thread.currentThread().getName()); - return le; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTestApp.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTestApp.java index 875c3942498af355e1216c722e2e5897258402f0..7d4ebf4835ad707e8bdf433e92ecafb74c53eaef 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTestApp.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSQueueAppenderTestApp.java @@ -20,42 +20,42 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.util.StatusPrinter; public class JMSQueueAppenderTestApp { - - public static void main(String[] args) { - Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicAppenderTestApp.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - - JMSQueueAppender appender = new JMSQueueAppender(); - appender.setContext(lc); - appender.setName("jmsQueue"); - appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - //appender.setPassword(""); - appender.setProviderURL("tcp://localhost:61616"); - //appender.setSecurityCredentials(""); - //appender.setSecurityPrincipalName(""); - appender.setQueueBindingName("MyQueue"); - appender.setQueueConnectionFactoryBindingName("ConnectionFactory"); - //appender.setURLPkgPrefixes(""); - //appender.setUserName(""); - - appender.start(); - logger.addAppender(appender); - - //JIT - for (int i = 0; i < 10000; i++) { - logger.debug("** Hello world. n=" + i); - } - - long before = System.nanoTime(); - for (int i = 0; i < 10000; i++) { - logger.debug("** Hello world. n=" + i); + + public static void main(String[] args) { + Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicAppenderTestApp.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + + JMSQueueAppender appender = new JMSQueueAppender(); + appender.setContext(lc); + appender.setName("jmsQueue"); + appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + // appender.setPassword(""); + appender.setProviderURL("tcp://localhost:61616"); + // appender.setSecurityCredentials(""); + // appender.setSecurityPrincipalName(""); + appender.setQueueBindingName("MyQueue"); + appender.setQueueConnectionFactoryBindingName("ConnectionFactory"); + // appender.setURLPkgPrefixes(""); + // appender.setUserName(""); + + appender.start(); + logger.addAppender(appender); + + // JIT + for (int i = 0; i < 10000; i++) { + logger.debug("** Hello world. n=" + i); + } + + long before = System.nanoTime(); + for (int i = 0; i < 10000; i++) { + logger.debug("** Hello world. n=" + i); + } + long after = System.nanoTime(); + + System.out.println("Time per logs for 10'000 logs: " + (after - before) / 10000); + + StatusPrinter.print(lc.getStatusManager()); } - long after = System.nanoTime(); - - System.out.println("Time per logs for 10'000 logs: " + (after-before)/10000); - - StatusPrinter.print(lc.getStatusManager()); - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTest.java index a4c34838a59c6ccab7fded6f331c803b4510a715..fd6e771212a9a3a126f7ec141f9e63838efd0a7b 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTest.java @@ -39,210 +39,192 @@ import ch.qos.logback.classic.util.MockInitialContextFactory; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.spi.PreSerializationTransformer; -public class JMSTopicAppenderTest { - - ch.qos.logback.core.Context context; - JMSTopicAppender appender; - PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - - - @Before - public void setUp() throws Exception { - context = new ContextBase(); - appender = new JMSTopicAppender(); - appender.setContext(context); - appender.setName("jmsTopic"); - appender.tcfBindingName = "topicCnxFactory"; - appender.topicBindingName = "testTopic"; - appender.setProviderURL("url"); - appender.setInitialContextFactoryName(MockInitialContextFactory.class.getName()); - - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(appender.tcfBindingName, new MockTopicConnectionFactory()); - mic.map.put(appender.topicBindingName, new MockTopic(appender.topicBindingName)); - - } - - - @After - public void tearDown() throws Exception { - appender = null; - context = null; - } - - @Test - public void testAppendOk() { - appender.start(); - - ILoggingEvent le = createLoggingEvent(); - appender.append(le); - - MockTopicPublisher tp = (MockTopicPublisher)appender.topicPublisher; - assertEquals(1, tp.getMessageList().size()); - ObjectMessage message = (ObjectMessage) tp.getMessageList().get(0); - try { - Serializable witness = pst.transform(le); - assertEquals(witness, message.getObject()); - } catch (Exception e) { - fail(); +public class JMSTopicAppenderTest { + + ch.qos.logback.core.Context context; + JMSTopicAppender appender; + PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + @Before + public void setUp() throws Exception { + context = new ContextBase(); + appender = new JMSTopicAppender(); + appender.setContext(context); + appender.setName("jmsTopic"); + appender.tcfBindingName = "topicCnxFactory"; + appender.topicBindingName = "testTopic"; + appender.setProviderURL("url"); + appender.setInitialContextFactoryName(MockInitialContextFactory.class.getName()); + + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(appender.tcfBindingName, new MockTopicConnectionFactory()); + mic.map.put(appender.topicBindingName, new MockTopic(appender.topicBindingName)); + + } + + @After + public void tearDown() throws Exception { + appender = null; + context = null; + } + + @Test + public void testAppendOk() { + appender.start(); + + ILoggingEvent le = createLoggingEvent(); + appender.append(le); + + MockTopicPublisher tp = (MockTopicPublisher) appender.topicPublisher; + assertEquals(1, tp.getMessageList().size()); + ObjectMessage message = (ObjectMessage) tp.getMessageList().get(0); + try { + Serializable witness = pst.transform(le); + assertEquals(witness, message.getObject()); + } catch (Exception e) { + fail(); + } + } + + @Test + public void testAppendFailure() { + appender.start(); + + // make sure the append method does not work + appender.topicPublisher = null; + + ILoggingEvent le = createLoggingEvent(); + for (int i = 1; i <= 3; i++) { + appender.append(le); + assertEquals(i, context.getStatusManager().getCount()); + assertTrue(appender.isStarted()); + } + appender.append(le); + assertEquals(4, context.getStatusManager().getCount()); + assertFalse(appender.isStarted()); } - } - - @Test - public void testAppendFailure() { - appender.start(); - - //make sure the append method does not work - appender.topicPublisher = null; - - ILoggingEvent le = createLoggingEvent(); - for (int i = 1; i <= 3; i++) { - appender.append(le); - assertEquals(i, context.getStatusManager().getCount()); - assertTrue(appender.isStarted()); + + @Test + public void testBuildEnvProperties() { + appender.setInitialContextFactoryName("icfn"); + appender.setProviderURL("url"); + appender.setURLPkgPrefixes("pkgPref"); + appender.setSecurityPrincipalName("user"); + appender.setSecurityCredentials("cred"); + + Properties props = appender.buildEnvProperties(); + assertEquals(5, props.size()); + assertEquals(appender.getInitialContextFactoryName(), props.getProperty(Context.INITIAL_CONTEXT_FACTORY)); + assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); + assertEquals(appender.getURLPkgPrefixes(), props.getProperty(Context.URL_PKG_PREFIXES)); + assertEquals(appender.getSecurityPrincipalName(), props.getProperty(Context.SECURITY_PRINCIPAL)); + assertEquals(appender.getSecurityCredentials(), props.getProperty(Context.SECURITY_CREDENTIALS)); + } + + @Test + public void testBuildEnvPropertiesWithNullProviderURL() { + appender.setInitialContextFactoryName("icfn"); + appender.setProviderURL(null); + appender.setURLPkgPrefixes("pkgPref"); + appender.setSecurityPrincipalName("user"); + appender.setSecurityCredentials("cred"); + + Properties props = appender.buildEnvProperties(); + assertEquals(4, props.size()); + assertEquals(appender.getInitialContextFactoryName(), props.getProperty(Context.INITIAL_CONTEXT_FACTORY)); + assertEquals(null, props.getProperty(Context.PROVIDER_URL)); + assertEquals(appender.getURLPkgPrefixes(), props.getProperty(Context.URL_PKG_PREFIXES)); + assertEquals(appender.getSecurityPrincipalName(), props.getProperty(Context.SECURITY_PRINCIPAL)); + assertEquals(appender.getSecurityCredentials(), props.getProperty(Context.SECURITY_CREDENTIALS)); + + assertEquals(1, context.getStatusManager().getCount()); } - appender.append(le); - assertEquals(4, context.getStatusManager().getCount()); - assertFalse(appender.isStarted()); - } - - @Test - public void testBuildEnvProperties() { - appender.setInitialContextFactoryName("icfn"); - appender.setProviderURL("url"); - appender.setURLPkgPrefixes("pkgPref"); - appender.setSecurityPrincipalName("user"); - appender.setSecurityCredentials("cred"); - - Properties props = appender.buildEnvProperties(); - assertEquals(5, props.size()); - assertEquals(appender.getInitialContextFactoryName(), props - .getProperty(Context.INITIAL_CONTEXT_FACTORY)); - assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); - assertEquals(appender.getURLPkgPrefixes(), props - .getProperty(Context.URL_PKG_PREFIXES)); - assertEquals(appender.getSecurityPrincipalName(), props - .getProperty(Context.SECURITY_PRINCIPAL)); - assertEquals(appender.getSecurityCredentials(), props - .getProperty(Context.SECURITY_CREDENTIALS)); - } - - @Test - public void testBuildEnvPropertiesWithNullProviderURL() { - appender.setInitialContextFactoryName("icfn"); - appender.setProviderURL(null); - appender.setURLPkgPrefixes("pkgPref"); - appender.setSecurityPrincipalName("user"); - appender.setSecurityCredentials("cred"); - - Properties props = appender.buildEnvProperties(); - assertEquals(4, props.size()); - assertEquals(appender.getInitialContextFactoryName(), props - .getProperty(Context.INITIAL_CONTEXT_FACTORY)); - assertEquals(null, props.getProperty(Context.PROVIDER_URL)); - assertEquals(appender.getURLPkgPrefixes(), props - .getProperty(Context.URL_PKG_PREFIXES)); - assertEquals(appender.getSecurityPrincipalName(), props - .getProperty(Context.SECURITY_PRINCIPAL)); - assertEquals(appender.getSecurityCredentials(), props - .getProperty(Context.SECURITY_CREDENTIALS)); - - assertEquals(1, context.getStatusManager().getCount()); - } - - @Test - public void testBuildEnvPropertiesWithNullCredentials() { - appender.setInitialContextFactoryName("icfn"); - appender.setProviderURL("url"); - appender.setURLPkgPrefixes("pkgPref"); - appender.setSecurityPrincipalName("user"); - appender.setSecurityCredentials(null); - - Properties props = appender.buildEnvProperties(); - assertEquals(4, props.size()); - assertEquals(appender.getInitialContextFactoryName(), props - .getProperty(Context.INITIAL_CONTEXT_FACTORY)); - assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); - assertEquals(appender.getURLPkgPrefixes(), props - .getProperty(Context.URL_PKG_PREFIXES)); - assertEquals(appender.getSecurityPrincipalName(), props - .getProperty(Context.SECURITY_PRINCIPAL)); - assertEquals(null, props - .getProperty(Context.SECURITY_CREDENTIALS)); - - assertEquals(1, context.getStatusManager().getCount()); - } - - @Test - public void testBuildEnvPropertiesWithPkgNull() { - appender.setInitialContextFactoryName("icfn"); - appender.setProviderURL("url"); - appender.setURLPkgPrefixes(null); - appender.setSecurityPrincipalName("user"); - appender.setSecurityCredentials("cred"); - - Properties props = appender.buildEnvProperties(); - assertEquals(4, props.size()); - assertEquals(appender.getInitialContextFactoryName(), props - .getProperty(Context.INITIAL_CONTEXT_FACTORY)); - assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); - assertEquals(null, props - .getProperty(Context.URL_PKG_PREFIXES)); - assertEquals(appender.getSecurityPrincipalName(), props - .getProperty(Context.SECURITY_PRINCIPAL)); - assertEquals(appender.getSecurityCredentials(), props - .getProperty(Context.SECURITY_CREDENTIALS)); - - assertEquals(0, context.getStatusManager().getCount()); - } - - @Test - public void testStartMinimalInfo() { - //let's leave only what's in the setup() - //method, minus the providerURL - appender.setProviderURL(null); - appender.start(); - - assertTrue(appender.isStarted()); - - try { - assertEquals(appender.topicBindingName, appender.topicPublisher.getTopic().getTopicName()); - } catch (Exception e) { - fail(); + + @Test + public void testBuildEnvPropertiesWithNullCredentials() { + appender.setInitialContextFactoryName("icfn"); + appender.setProviderURL("url"); + appender.setURLPkgPrefixes("pkgPref"); + appender.setSecurityPrincipalName("user"); + appender.setSecurityCredentials(null); + + Properties props = appender.buildEnvProperties(); + assertEquals(4, props.size()); + assertEquals(appender.getInitialContextFactoryName(), props.getProperty(Context.INITIAL_CONTEXT_FACTORY)); + assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); + assertEquals(appender.getURLPkgPrefixes(), props.getProperty(Context.URL_PKG_PREFIXES)); + assertEquals(appender.getSecurityPrincipalName(), props.getProperty(Context.SECURITY_PRINCIPAL)); + assertEquals(null, props.getProperty(Context.SECURITY_CREDENTIALS)); + + assertEquals(1, context.getStatusManager().getCount()); } - } - - @Test - public void testStartUserPass() { - appender.setUserName("test"); - appender.setPassword("test"); - - appender.start(); - - assertTrue(appender.isStarted()); - - try { - assertEquals(appender.topicBindingName, appender.topicPublisher.getTopic().getTopicName()); - } catch (Exception e) { - fail(); + + @Test + public void testBuildEnvPropertiesWithPkgNull() { + appender.setInitialContextFactoryName("icfn"); + appender.setProviderURL("url"); + appender.setURLPkgPrefixes(null); + appender.setSecurityPrincipalName("user"); + appender.setSecurityCredentials("cred"); + + Properties props = appender.buildEnvProperties(); + assertEquals(4, props.size()); + assertEquals(appender.getInitialContextFactoryName(), props.getProperty(Context.INITIAL_CONTEXT_FACTORY)); + assertEquals(appender.getProviderURL(), props.getProperty(Context.PROVIDER_URL)); + assertEquals(null, props.getProperty(Context.URL_PKG_PREFIXES)); + assertEquals(appender.getSecurityPrincipalName(), props.getProperty(Context.SECURITY_PRINCIPAL)); + assertEquals(appender.getSecurityCredentials(), props.getProperty(Context.SECURITY_CREDENTIALS)); + + assertEquals(0, context.getStatusManager().getCount()); + } + + @Test + public void testStartMinimalInfo() { + // let's leave only what's in the setup() + // method, minus the providerURL + appender.setProviderURL(null); + appender.start(); + + assertTrue(appender.isStarted()); + + try { + assertEquals(appender.topicBindingName, appender.topicPublisher.getTopic().getTopicName()); + } catch (Exception e) { + fail(); + } + } + + @Test + public void testStartUserPass() { + appender.setUserName("test"); + appender.setPassword("test"); + + appender.start(); + + assertTrue(appender.isStarted()); + + try { + assertEquals(appender.topicBindingName, appender.topicPublisher.getTopic().getTopicName()); + } catch (Exception e) { + fail(); + } + } + + @Test + public void testStartFails() { + appender.topicBindingName = null; + + appender.start(); + + assertFalse(appender.isStarted()); + } + + private ILoggingEvent createLoggingEvent() { + LoggingEvent le = new LoggingEvent(); + le.setLevel(Level.DEBUG); + le.setMessage("test message"); + le.setTimeStamp(System.currentTimeMillis()); + le.setThreadName(Thread.currentThread().getName()); + return le; } - } - - @Test - public void testStartFails() { - appender.topicBindingName = null; - - appender.start(); - - assertFalse(appender.isStarted()); - } - - private ILoggingEvent createLoggingEvent() { - LoggingEvent le = new LoggingEvent(); - le.setLevel(Level.DEBUG); - le.setMessage("test message"); - le.setTimeStamp(System.currentTimeMillis()); - le.setThreadName(Thread.currentThread().getName()); - return le; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTestApp.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTestApp.java index 41be25c9917ca73b684897d5eaf950f65f54acd0..3d85d8d922e474445de69269d4572519cd32d841 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTestApp.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/JMSTopicAppenderTestApp.java @@ -20,43 +20,42 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.util.StatusPrinter; public class JMSTopicAppenderTestApp { - - public static void main(String[] args) { - Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicAppenderTestApp.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - - JMSTopicAppender appender = new JMSTopicAppender(); - appender.setContext(lc); - appender.setName("jmsTopic"); - appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory"); - //appender.setPassword(""); - appender.setProviderURL("tcp://localhost:61616"); - //appender.setSecurityCredentials(""); - //appender.setSecurityPrincipalName(""); - appender.setTopicBindingName("MyTopic"); - appender.setTopicConnectionFactoryBindingName("ConnectionFactory"); - //appender.setURLPkgPrefixes(""); - //appender.setUserName(""); - - appender.start(); - logger.addAppender(appender); - - - //JIT - for (int i = 0; i < 10000; i++) { - logger.debug("** Hello world. n=" + i); - } - - long before = System.nanoTime(); - for (int i = 0; i < 10000; i++) { - logger.debug("** Hello world. n=" + i); + + public static void main(String[] args) { + Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicAppenderTestApp.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + + JMSTopicAppender appender = new JMSTopicAppender(); + appender.setContext(lc); + appender.setName("jmsTopic"); + appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory"); + // appender.setPassword(""); + appender.setProviderURL("tcp://localhost:61616"); + // appender.setSecurityCredentials(""); + // appender.setSecurityPrincipalName(""); + appender.setTopicBindingName("MyTopic"); + appender.setTopicConnectionFactoryBindingName("ConnectionFactory"); + // appender.setURLPkgPrefixes(""); + // appender.setUserName(""); + + appender.start(); + logger.addAppender(appender); + + // JIT + for (int i = 0; i < 10000; i++) { + logger.debug("** Hello world. n=" + i); + } + + long before = System.nanoTime(); + for (int i = 0; i < 10000; i++) { + logger.debug("** Hello world. n=" + i); + } + long after = System.nanoTime(); + + System.out.println("Time per logs for 10'000 logs: " + (after - before) / 10000); + + StatusPrinter.print(lc.getStatusManager()); } - long after = System.nanoTime(); - - System.out.println("Time per logs for 10'000 logs: " + (after-before)/10000); - - StatusPrinter.print(lc.getStatusManager()); - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/NOPOutputStream.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/NOPOutputStream.java index 8274aacbd78c9c45ed38a332cbd24e780359f465..d8388da705fd6df28f23ebae6cb0563dfbff65d2 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/NOPOutputStream.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/NOPOutputStream.java @@ -18,25 +18,24 @@ import java.io.OutputStream; public class NOPOutputStream extends OutputStream { - long count; - - @Override - public void write(int b) throws IOException { - count++; - // do nothing - } - - public long getCount() { - return count; - } - - public long size() { - return count; - } - - - public void reset() { - count = 0; - } + long count; + + @Override + public void write(int b) throws IOException { + count++; + // do nothing + } + + public long getCount() { + return count; + } + + public long size() { + return count; + } + + public void reset() { + count = 0; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/PackageTest.java index 9a27825fa78a20b7b2e4b6a36cd552c80dfe1148..884fa2c05a3775d2177d32d96ec53d5459b5f497 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/PackageTest.java @@ -18,9 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { SyslogAppenderTest.class, DilutedSMTPAppenderTest.class, - JMSQueueAppenderTest.class, JMSTopicAppenderTest.class, - SMTPAppender_GreenTest.class, SMTPAppender_SubethaSMTPTest.class, - SocketReceiverTest.class, SSLSocketReceiverTest.class }) +@SuiteClasses({ SyslogAppenderTest.class, DilutedSMTPAppenderTest.class, JMSQueueAppenderTest.class, JMSTopicAppenderTest.class, SMTPAppender_GreenTest.class, + SMTPAppender_SubethaSMTPTest.class, SocketReceiverTest.class, SSLSocketReceiverTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java index 8d67bed38ffd0ca4dd1c5b657f743d1e7da02737..cdc86d45c4eeb734f133a67bd4597ed84ef062f2 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_GreenTest.java @@ -53,321 +53,316 @@ import static org.junit.Assert.*; public class SMTPAppender_GreenTest { - static final String HEADER = "HEADER\n"; - static final String FOOTER = "FOOTER\n"; - static final String DEFAULT_PATTERN = "%-4relative %mdc [%thread] %-5level %class - %msg%n"; - - static final boolean SYNCHRONOUS = false; - static final boolean ASYNCHRONOUS = true; - - int port = RandomUtil.getRandomServerPort(); - // GreenMail cannot be static. As a shared server induces race conditions - GreenMail greenMailServer; - - SMTPAppender smtpAppender; - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(this.getClass()); - - - @Before - public void setUp() throws Exception { - - StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new OnConsoleStatusListener()); - MDC.clear(); - ServerSetup serverSetup = new ServerSetup(port, "localhost", - ServerSetup.PROTOCOL_SMTP); - greenMailServer = new GreenMail(serverSetup); - greenMailServer.start(); - // give the server a head start - if (EnvUtilForTests.isRunningOnSlowJenkins()) { - Thread.sleep(2000); - } else { - Thread.sleep(50); + static final String HEADER = "HEADER\n"; + static final String FOOTER = "FOOTER\n"; + static final String DEFAULT_PATTERN = "%-4relative %mdc [%thread] %-5level %class - %msg%n"; + + static final boolean SYNCHRONOUS = false; + static final boolean ASYNCHRONOUS = true; + + int port = RandomUtil.getRandomServerPort(); + // GreenMail cannot be static. As a shared server induces race conditions + GreenMail greenMailServer; + + SMTPAppender smtpAppender; + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(this.getClass()); + + @Before + public void setUp() throws Exception { + + StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new OnConsoleStatusListener()); + MDC.clear(); + ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP); + greenMailServer = new GreenMail(serverSetup); + greenMailServer.start(); + // give the server a head start + if (EnvUtilForTests.isRunningOnSlowJenkins()) { + Thread.sleep(2000); + } else { + Thread.sleep(50); + } } - } - - @After - public void tearDown() throws Exception { - greenMailServer.stop(); - } - - void buildSMTPAppender(String subject, boolean synchronicity) throws Exception { - smtpAppender = new SMTPAppender(); - smtpAppender.setContext(loggerContext); - smtpAppender.setName("smtp"); - smtpAppender.setFrom("user@host.dom"); - smtpAppender.setSMTPHost("localhost"); - smtpAppender.setSMTPPort(port); - smtpAppender.setSubject(subject); - smtpAppender.addTo("nospam@qos.ch"); - smtpAppender.setAsynchronousSending(synchronicity); - } - - private Layout buildPatternLayout(String pattern) { - PatternLayout layout = new PatternLayout(); - layout.setContext(loggerContext); - layout.setFileHeader(HEADER); - layout.setOutputPatternAsHeader(false); - layout.setPattern(pattern); - layout.setFileFooter(FOOTER); - layout.start(); - return layout; - } - - private Layout buildHTMLLayout() { - HTMLLayout layout = new HTMLLayout(); - layout.setContext(loggerContext); - layout.setPattern("%level%class%msg"); - layout.start(); - return layout; - } - - private void waitForServerToReceiveEmails(int emailCount) throws InterruptedException { - greenMailServer.waitForIncomingEmail(5000, emailCount); - } - - private MimeMultipart verifyAndExtractMimeMultipart(String subject) throws MessagingException, - IOException, InterruptedException { - int oldCount = 0; - int expectedEmailCount = 1; - // wait for the server to receive the messages - waitForServerToReceiveEmails(expectedEmailCount); - MimeMessage[] mma = greenMailServer.getReceivedMessages(); - assertNotNull(mma); - assertEquals(expectedEmailCount, mma.length); - MimeMessage mm = mma[oldCount]; - // http://jira.qos.ch/browse/LBCLASSIC-67 - assertEquals(subject, mm.getSubject()); - return (MimeMultipart) mm.getContent(); - } - - void waitUntilEmailIsSent() throws InterruptedException { - loggerContext.getExecutorService().shutdown(); - loggerContext.getExecutorService().awaitTermination(1000, TimeUnit.MILLISECONDS); - } - - @Test - public void synchronousSmoke() throws Exception { - String subject = "synchronousSmoke"; - buildSMTPAppender(subject, SYNCHRONOUS); - - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - MimeMultipart mp = verifyAndExtractMimeMultipart(subject); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertTrue(body.startsWith(HEADER.trim())); - assertTrue(body.endsWith(FOOTER.trim())); - } - - @Test - public void asynchronousSmoke() throws Exception { - String subject = "asynchronousSmoke"; - buildSMTPAppender(subject, ASYNCHRONOUS); - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - waitUntilEmailIsSent(); - MimeMultipart mp = verifyAndExtractMimeMultipart(subject); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertTrue(body.startsWith(HEADER.trim())); - assertTrue(body.endsWith(FOOTER.trim())); - } - - // See also http://jira.qos.ch/browse/LOGBACK-734 - @Test - public void callerDataShouldBeCorrectlySetWithAsynchronousSending() throws Exception { - String subject = "LOGBACK-734"; - buildSMTPAppender("LOGBACK-734", ASYNCHRONOUS); - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.setIncludeCallerData(true); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("LOGBACK-734"); - logger.error("callerData", new Exception("ShouldBeCorrectlySetWithAsynchronousSending")); - - waitUntilEmailIsSent(); - MimeMultipart mp = verifyAndExtractMimeMultipart(subject); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertTrue("actual [" + body + "]", body.contains("DEBUG " + this.getClass().getName() + " - LOGBACK-734")); - } - - // lost MDC - @Test - public void LBCLASSIC_104() throws Exception { - String subject = "LBCLASSIC_104"; - buildSMTPAppender(subject, SYNCHRONOUS); - smtpAppender.setAsynchronousSending(false); - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.start(); - logger.addAppender(smtpAppender); - MDC.put("key", "val"); - logger.debug("LBCLASSIC_104"); - MDC.clear(); - logger.error("en error", new Exception("test")); - - MimeMultipart mp = verifyAndExtractMimeMultipart(subject); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertTrue(body.startsWith(HEADER.trim())); - System.out.println(body); - assertTrue(body.contains("key=val")); - assertTrue(body.endsWith(FOOTER.trim())); - } - - @Test - public void html() throws Exception { - String subject = "html"; - buildSMTPAppender(subject, SYNCHRONOUS); - smtpAppender.setAsynchronousSending(false); - smtpAppender.setLayout(buildHTMLLayout()); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("html"); - logger.error("en error", new Exception("an exception")); - - MimeMultipart mp = verifyAndExtractMimeMultipart(subject); - - // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd - SAXReader reader = new SAXReader(); - reader.setValidation(true); - reader.setEntityResolver(new XHTMLEntityResolver()); - byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream()); - ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes); - try { - reader.read(bais); - } catch (DocumentException de) { - System.out.println("incoming message:"); - System.out.println(new String(messageBytes)); - throw de; + + @After + public void tearDown() throws Exception { + greenMailServer.stop(); + } + + void buildSMTPAppender(String subject, boolean synchronicity) throws Exception { + smtpAppender = new SMTPAppender(); + smtpAppender.setContext(loggerContext); + smtpAppender.setName("smtp"); + smtpAppender.setFrom("user@host.dom"); + smtpAppender.setSMTPHost("localhost"); + smtpAppender.setSMTPPort(port); + smtpAppender.setSubject(subject); + smtpAppender.addTo("nospam@qos.ch"); + smtpAppender.setAsynchronousSending(synchronicity); + } + + private Layout buildPatternLayout(String pattern) { + PatternLayout layout = new PatternLayout(); + layout.setContext(loggerContext); + layout.setFileHeader(HEADER); + layout.setOutputPatternAsHeader(false); + layout.setPattern(pattern); + layout.setFileFooter(FOOTER); + layout.start(); + return layout; + } + + private Layout buildHTMLLayout() { + HTMLLayout layout = new HTMLLayout(); + layout.setContext(loggerContext); + layout.setPattern("%level%class%msg"); + layout.start(); + return layout; + } + + private void waitForServerToReceiveEmails(int emailCount) throws InterruptedException { + greenMailServer.waitForIncomingEmail(5000, emailCount); } - } - private byte[] getAsByteArray(InputStream inputStream) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + private MimeMultipart verifyAndExtractMimeMultipart(String subject) throws MessagingException, IOException, InterruptedException { + int oldCount = 0; + int expectedEmailCount = 1; + // wait for the server to receive the messages + waitForServerToReceiveEmails(expectedEmailCount); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); + assertNotNull(mma); + assertEquals(expectedEmailCount, mma.length); + MimeMessage mm = mma[oldCount]; + // http://jira.qos.ch/browse/LBCLASSIC-67 + assertEquals(subject, mm.getSubject()); + return (MimeMultipart) mm.getContent(); + } + + void waitUntilEmailIsSent() throws InterruptedException { + loggerContext.getExecutorService().shutdown(); + loggerContext.getExecutorService().awaitTermination(1000, TimeUnit.MILLISECONDS); + } + + @Test + public void synchronousSmoke() throws Exception { + String subject = "synchronousSmoke"; + buildSMTPAppender(subject, SYNCHRONOUS); + + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + MimeMultipart mp = verifyAndExtractMimeMultipart(subject); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertTrue(body.startsWith(HEADER.trim())); + assertTrue(body.endsWith(FOOTER.trim())); + } + + @Test + public void asynchronousSmoke() throws Exception { + String subject = "asynchronousSmoke"; + buildSMTPAppender(subject, ASYNCHRONOUS); + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + waitUntilEmailIsSent(); + MimeMultipart mp = verifyAndExtractMimeMultipart(subject); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertTrue(body.startsWith(HEADER.trim())); + assertTrue(body.endsWith(FOOTER.trim())); + } + + // See also http://jira.qos.ch/browse/LOGBACK-734 + @Test + public void callerDataShouldBeCorrectlySetWithAsynchronousSending() throws Exception { + String subject = "LOGBACK-734"; + buildSMTPAppender("LOGBACK-734", ASYNCHRONOUS); + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.setIncludeCallerData(true); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("LOGBACK-734"); + logger.error("callerData", new Exception("ShouldBeCorrectlySetWithAsynchronousSending")); + + waitUntilEmailIsSent(); + MimeMultipart mp = verifyAndExtractMimeMultipart(subject); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertTrue("actual [" + body + "]", body.contains("DEBUG " + this.getClass().getName() + " - LOGBACK-734")); + } + + // lost MDC + @Test + public void LBCLASSIC_104() throws Exception { + String subject = "LBCLASSIC_104"; + buildSMTPAppender(subject, SYNCHRONOUS); + smtpAppender.setAsynchronousSending(false); + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.start(); + logger.addAppender(smtpAppender); + MDC.put("key", "val"); + logger.debug("LBCLASSIC_104"); + MDC.clear(); + logger.error("en error", new Exception("test")); + + MimeMultipart mp = verifyAndExtractMimeMultipart(subject); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertTrue(body.startsWith(HEADER.trim())); + System.out.println(body); + assertTrue(body.contains("key=val")); + assertTrue(body.endsWith(FOOTER.trim())); + } + + @Test + public void html() throws Exception { + String subject = "html"; + buildSMTPAppender(subject, SYNCHRONOUS); + smtpAppender.setAsynchronousSending(false); + smtpAppender.setLayout(buildHTMLLayout()); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("html"); + logger.error("en error", new Exception("an exception")); + + MimeMultipart mp = verifyAndExtractMimeMultipart(subject); + + // verifyAndExtractMimeMultipart strict adherence to xhtml1-strict.dtd + SAXReader reader = new SAXReader(); + reader.setValidation(true); + reader.setEntityResolver(new XHTMLEntityResolver()); + byte[] messageBytes = getAsByteArray(mp.getBodyPart(0).getInputStream()); + ByteArrayInputStream bais = new ByteArrayInputStream(messageBytes); + try { + reader.read(bais); + } catch (DocumentException de) { + System.out.println("incoming message:"); + System.out.println(new String(messageBytes)); + throw de; + } + } + + private byte[] getAsByteArray(InputStream inputStream) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + byte[] buffer = new byte[1024]; + int n = -1; + while ((n = inputStream.read(buffer)) != -1) { + baos.write(buffer, 0, n); + } + return baos.toByteArray(); + } + + private void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + loggerContext.putProperty("port", "" + port); + jc.doConfigure(file); + } + + @Test + public void testCustomEvaluator() throws Exception { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customEvaluator.xml"); + + logger.debug("test"); + String msg2 = "CustomEvaluator"; + logger.debug(msg2); + logger.debug("invisible"); + waitUntilEmailIsSent(); + MimeMultipart mp = verifyAndExtractMimeMultipart("testCustomEvaluator " + this.getClass().getName() + " - " + msg2); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertEquals("testCustomEvaluator", body); + } + + @Test + public void testCustomBufferSize() throws Exception { + configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "smtp/customBufferSize.xml"); + + logger.debug("invisible1"); + logger.debug("invisible2"); + String msg = "hello"; + logger.error(msg); + waitUntilEmailIsSent(); + MimeMultipart mp = verifyAndExtractMimeMultipart("testCustomBufferSize " + this.getClass().getName() + " - " + msg); + String body = GreenMailUtil.getBody(mp.getBodyPart(0)); + assertEquals(msg, body); + } + + // this test fails intermittently on Jenkins. + @Test + public void testMultipleTo() throws Exception { + buildSMTPAppender("testMultipleTo", SYNCHRONOUS); + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + // buildSMTPAppender() already added one destination address + smtpAppender.addTo("Test , other-test@example.com"); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("testMultipleTo hello"); + logger.error("testMultipleTo en error", new Exception("an exception")); + Thread.yield(); + int expectedEmailCount = 3; + waitForServerToReceiveEmails(expectedEmailCount); + MimeMessage[] mma = greenMailServer.getReceivedMessages(); + assertNotNull(mma); + assertEquals(expectedEmailCount, mma.length); + } + + // http://jira.qos.ch/browse/LBCLASSIC-221 + @Test + public void bufferShouldBeResetBetweenMessages() throws Exception { + buildSMTPAppender("bufferShouldBeResetBetweenMessages", SYNCHRONOUS); + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.start(); + logger.addAppender(smtpAppender); + String msg0 = "hello zero"; + logger.debug(msg0); + logger.error("error zero"); + + String msg1 = "hello one"; + logger.debug(msg1); + logger.error("error one"); + + Thread.yield(); + int oldCount = 0; + int expectedEmailCount = oldCount + 2; + waitForServerToReceiveEmails(expectedEmailCount); + + MimeMessage[] mma = greenMailServer.getReceivedMessages(); + assertNotNull(mma); + assertEquals(expectedEmailCount, mma.length); + + MimeMessage mm0 = mma[oldCount]; + MimeMultipart content0 = (MimeMultipart) mm0.getContent(); + String body0 = GreenMailUtil.getBody(content0.getBodyPart(0)); + + MimeMessage mm1 = mma[oldCount + 1]; + MimeMultipart content1 = (MimeMultipart) mm1.getContent(); + String body1 = GreenMailUtil.getBody(content1.getBodyPart(0)); + // second body should not contain content from first message + assertFalse(body1.contains(msg0)); + } - byte[] buffer = new byte[1024]; - int n = -1; - while ((n = inputStream.read(buffer)) != -1) { - baos.write(buffer, 0, n); + @Test + public void multiLineSubjectTruncatedAtFirstNewLine() throws Exception { + String line1 = "line 1 of subject"; + String subject = line1 + "\nline 2 of subject\n"; + buildSMTPAppender(subject, ASYNCHRONOUS); + + smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); + smtpAppender.start(); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + Thread.yield(); + waitUntilEmailIsSent(); + waitForServerToReceiveEmails(1); + + MimeMessage[] mma = greenMailServer.getReceivedMessages(); + assertEquals(1, mma.length); + assertEquals(line1, mma[0].getSubject()); } - return baos.toByteArray(); - } - - private void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - loggerContext.putProperty("port", "" + port); - jc.doConfigure(file); - } - - @Test - public void testCustomEvaluator() throws Exception { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "smtp/customEvaluator.xml"); - - logger.debug("test"); - String msg2 = "CustomEvaluator"; - logger.debug(msg2); - logger.debug("invisible"); - waitUntilEmailIsSent(); - MimeMultipart mp = verifyAndExtractMimeMultipart("testCustomEvaluator " + this.getClass().getName() + " - " + msg2); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertEquals("testCustomEvaluator", body); - } - - @Test - public void testCustomBufferSize() throws Exception { - configure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "smtp/customBufferSize.xml"); - - logger.debug("invisible1"); - logger.debug("invisible2"); - String msg = "hello"; - logger.error(msg); - waitUntilEmailIsSent(); - MimeMultipart mp = verifyAndExtractMimeMultipart("testCustomBufferSize " + this.getClass().getName() + " - " + msg); - String body = GreenMailUtil.getBody(mp.getBodyPart(0)); - assertEquals(msg, body); - } - - // this test fails intermittently on Jenkins. - @Test - public void testMultipleTo() throws Exception { - buildSMTPAppender("testMultipleTo", SYNCHRONOUS); - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - // buildSMTPAppender() already added one destination address - smtpAppender.addTo("Test , other-test@example.com"); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("testMultipleTo hello"); - logger.error("testMultipleTo en error", new Exception("an exception")); - Thread.yield(); - int expectedEmailCount = 3; - waitForServerToReceiveEmails(expectedEmailCount); - MimeMessage[] mma = greenMailServer.getReceivedMessages(); - assertNotNull(mma); - assertEquals(expectedEmailCount, mma.length); - } - - // http://jira.qos.ch/browse/LBCLASSIC-221 - @Test - public void bufferShouldBeResetBetweenMessages() throws Exception { - buildSMTPAppender("bufferShouldBeResetBetweenMessages", SYNCHRONOUS); - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.start(); - logger.addAppender(smtpAppender); - String msg0 = "hello zero"; - logger.debug(msg0); - logger.error("error zero"); - - String msg1 = "hello one"; - logger.debug(msg1); - logger.error("error one"); - - Thread.yield(); - int oldCount = 0; - int expectedEmailCount = oldCount + 2; - waitForServerToReceiveEmails(expectedEmailCount); - - MimeMessage[] mma = greenMailServer.getReceivedMessages(); - assertNotNull(mma); - assertEquals(expectedEmailCount, mma.length); - - MimeMessage mm0 = mma[oldCount]; - MimeMultipart content0 = (MimeMultipart) mm0.getContent(); - String body0 = GreenMailUtil.getBody(content0.getBodyPart(0)); - - MimeMessage mm1 = mma[oldCount + 1]; - MimeMultipart content1 = (MimeMultipart) mm1.getContent(); - String body1 = GreenMailUtil.getBody(content1.getBodyPart(0)); - // second body should not contain content from first message - assertFalse(body1.contains(msg0)); - } - - @Test - public void multiLineSubjectTruncatedAtFirstNewLine() throws Exception { - String line1 = "line 1 of subject"; - String subject = line1 + "\nline 2 of subject\n"; - buildSMTPAppender(subject, ASYNCHRONOUS); - - smtpAppender.setLayout(buildPatternLayout(DEFAULT_PATTERN)); - smtpAppender.start(); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - Thread.yield(); - waitUntilEmailIsSent(); - waitForServerToReceiveEmails(1); - - MimeMessage[] mma = greenMailServer.getReceivedMessages(); - assertEquals(1, mma.length); - assertEquals(line1, mma[0].getSubject()); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_SubethaSMTPTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_SubethaSMTPTest.java index c8e8d58e0547f42e3cce905e9e0e8ab65ee3c7d6..7111e464cae00c055408274a06cf3032b5474a26 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_SubethaSMTPTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SMTPAppender_SubethaSMTPTest.java @@ -51,320 +51,315 @@ import ch.qos.logback.core.Layout; import ch.qos.logback.core.util.StatusPrinter; public class SMTPAppender_SubethaSMTPTest { - static final String TEST_SUBJECT = "test subject"; - static final String HEADER = "HEADER\n"; - static final String FOOTER = "FOOTER\n"; - - static int DIFF = 1024 + new Random().nextInt(30000); - static Wiser WISER; - - SMTPAppender smtpAppender; - LoggerContext loggerContext = new LoggerContext(); - - int numberOfOldMessages; - - - @BeforeClass - static public void beforeClass() { - WISER = new Wiser(); - WISER.setPort(DIFF); - WISER.start(); - } - - @AfterClass - static public void afterClass() throws Exception { - WISER.stop(); - } - - @Before - public void setUp() throws Exception { - numberOfOldMessages = WISER.getMessages().size(); - buildSMTPAppender(); - } - - @After - public void tearDown() { - // clear any authentication handler factory - MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); - mla.setAuthenticationHandlerFactory(null); - } - - void buildSMTPAppender() throws Exception { - smtpAppender = new SMTPAppender(); - smtpAppender.setContext(loggerContext); - smtpAppender.setName("smtp"); - smtpAppender.setFrom("user@host.dom"); - smtpAppender.setSMTPHost("localhost"); - smtpAppender.setSMTPPort(DIFF); - smtpAppender.setSubject(TEST_SUBJECT); - smtpAppender.addTo("noreply@qos.ch"); - } - - private Layout buildPatternLayout(LoggerContext lc) { - PatternLayout layout = new PatternLayout(); - layout.setContext(lc); - layout.setFileHeader(HEADER); - layout.setPattern("%-4relative [%thread] %-5level %logger %class - %msg%n"); - layout.setFileFooter(FOOTER); - layout.start(); - return layout; - } - - private Layout buildHTMLLayout(LoggerContext lc) { - HTMLLayout layout = new HTMLLayout(); - layout.setContext(lc); - // layout.setFileHeader(HEADER); - layout.setPattern("%level%class%msg"); - // layout.setFileFooter(FOOTER); - layout.start(); - return layout; - } - - - private static String getWholeMessage(Part msg) { - try { - ByteArrayOutputStream bodyOut = new ByteArrayOutputStream(); - msg.writeTo(bodyOut); - return bodyOut.toString("US-ASCII").trim(); - } catch (Exception e) { - throw new RuntimeException(e); + static final String TEST_SUBJECT = "test subject"; + static final String HEADER = "HEADER\n"; + static final String FOOTER = "FOOTER\n"; + + static int DIFF = 1024 + new Random().nextInt(30000); + static Wiser WISER; + + SMTPAppender smtpAppender; + LoggerContext loggerContext = new LoggerContext(); + + int numberOfOldMessages; + + @BeforeClass + static public void beforeClass() { + WISER = new Wiser(); + WISER.setPort(DIFF); + WISER.start(); + } + + @AfterClass + static public void afterClass() throws Exception { + WISER.stop(); + } + + @Before + public void setUp() throws Exception { + numberOfOldMessages = WISER.getMessages().size(); + buildSMTPAppender(); + } + + @After + public void tearDown() { + // clear any authentication handler factory + MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); + mla.setAuthenticationHandlerFactory(null); + } + + void buildSMTPAppender() throws Exception { + smtpAppender = new SMTPAppender(); + smtpAppender.setContext(loggerContext); + smtpAppender.setName("smtp"); + smtpAppender.setFrom("user@host.dom"); + smtpAppender.setSMTPHost("localhost"); + smtpAppender.setSMTPPort(DIFF); + smtpAppender.setSubject(TEST_SUBJECT); + smtpAppender.addTo("noreply@qos.ch"); + } + + private Layout buildPatternLayout(LoggerContext lc) { + PatternLayout layout = new PatternLayout(); + layout.setContext(lc); + layout.setFileHeader(HEADER); + layout.setPattern("%-4relative [%thread] %-5level %logger %class - %msg%n"); + layout.setFileFooter(FOOTER); + layout.start(); + return layout; + } + + private Layout buildHTMLLayout(LoggerContext lc) { + HTMLLayout layout = new HTMLLayout(); + layout.setContext(lc); + // layout.setFileHeader(HEADER); + layout.setPattern("%level%class%msg"); + // layout.setFileFooter(FOOTER); + layout.start(); + return layout; + } + + private static String getWholeMessage(Part msg) { + try { + ByteArrayOutputStream bodyOut = new ByteArrayOutputStream(); + msg.writeTo(bodyOut); + return bodyOut.toString("US-ASCII").trim(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + void waitUntilEmailIsSent() throws Exception { + System.out.println("About to wait for sending thread to finish"); + loggerContext.getExecutorService().shutdown(); + loggerContext.getExecutorService().awaitTermination(3000, TimeUnit.MILLISECONDS); + } + + private static String getBody(Part msg) { + String all = getWholeMessage(msg); + int i = all.indexOf("\r\n\r\n"); + return all.substring(i + 4, all.length()); + } + + @Test + public void smoke() throws Exception { + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + waitUntilEmailIsSent(); + System.out.println("*** " + ((ThreadPoolExecutor) loggerContext.getExecutorService()).getCompletedTaskCount()); + List wiserMsgList = WISER.getMessages(); + + assertNotNull(wiserMsgList); + assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); + WiserMessage wm = wiserMsgList.get(numberOfOldMessages); + // http://jira.qos.ch/browse/LBCLASSIC-67 + MimeMessage mm = wm.getMimeMessage(); + assertEquals(TEST_SUBJECT, mm.getSubject()); + + MimeMultipart mp = (MimeMultipart) mm.getContent(); + String body = getBody(mp.getBodyPart(0)); + System.out.println("[" + body); + assertTrue(body.startsWith(HEADER.trim())); + assertTrue(body.endsWith(FOOTER.trim())); + } + + @Test + public void html() throws Exception { + + smtpAppender.setLayout(buildHTMLLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + waitUntilEmailIsSent(); + + List wiserMsgList = WISER.getMessages(); + + assertNotNull(wiserMsgList); + assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); + WiserMessage wm = wiserMsgList.get(numberOfOldMessages); + MimeMessage mm = wm.getMimeMessage(); + assertEquals(TEST_SUBJECT, mm.getSubject()); + + MimeMultipart mp = (MimeMultipart) mm.getContent(); + + // verify strict adherence to xhtml1-strict.dtd + SAXReader reader = new SAXReader(); + reader.setValidation(true); + reader.setEntityResolver(new XHTMLEntityResolver()); + reader.read(mp.getBodyPart(0).getInputStream()); + // System.out.println(GreenMailUtil.getBody(mp.getBodyPart(0))); + } + + @Test + /** + * Checks that even when many events are processed, the output is still + * conforms to xhtml-strict.dtd. + * + * Note that SMTPAppender only keeps only 500 or so (=buffer size) events. So + * the generated output will be rather short. + */ + public void htmlLong() throws Exception { + smtpAppender.setLayout(buildHTMLLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + for (int i = 0; i < CoreConstants.TABLE_ROW_LIMIT * 3; i++) { + logger.debug("hello " + i); + } + logger.error("en error", new Exception("an exception")); + waitUntilEmailIsSent(); + List wiserMsgList = WISER.getMessages(); + + assertNotNull(wiserMsgList); + assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); + WiserMessage wm = wiserMsgList.get(numberOfOldMessages); + MimeMessage mm = wm.getMimeMessage(); + assertEquals(TEST_SUBJECT, mm.getSubject()); + + MimeMultipart mp = (MimeMultipart) mm.getContent(); + + // verify strict adherence to xhtml1-strict.dtd + SAXReader reader = new SAXReader(); + reader.setValidation(true); + reader.setEntityResolver(new XHTMLEntityResolver()); + reader.read(mp.getBodyPart(0).getInputStream()); } - } - - void waitUntilEmailIsSent() throws Exception { - System.out.println("About to wait for sending thread to finish"); - loggerContext.getExecutorService().shutdown(); - loggerContext.getExecutorService().awaitTermination(3000, TimeUnit.MILLISECONDS); - } - - private static String getBody(Part msg) { - String all = getWholeMessage(msg); - int i = all.indexOf("\r\n\r\n"); - return all.substring(i + 4, all.length()); - } - - @Test - public void smoke() throws Exception { - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - waitUntilEmailIsSent(); - System.out.println("*** " + ((ThreadPoolExecutor) loggerContext.getExecutorService()).getCompletedTaskCount()); - List wiserMsgList = WISER.getMessages(); - - assertNotNull(wiserMsgList); - assertEquals(numberOfOldMessages+1, wiserMsgList.size()); - WiserMessage wm = wiserMsgList.get(numberOfOldMessages); - // http://jira.qos.ch/browse/LBCLASSIC-67 - MimeMessage mm = wm.getMimeMessage(); - assertEquals(TEST_SUBJECT, mm.getSubject()); - - MimeMultipart mp = (MimeMultipart) mm.getContent(); - String body = getBody(mp.getBodyPart(0)); - System.out.println("[" + body); - assertTrue(body.startsWith(HEADER.trim())); - assertTrue(body.endsWith(FOOTER.trim())); - } - - - @Test - public void html() throws Exception { - - smtpAppender.setLayout(buildHTMLLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - waitUntilEmailIsSent(); - - List wiserMsgList = WISER.getMessages(); - - assertNotNull(wiserMsgList); - assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); - WiserMessage wm = wiserMsgList.get(numberOfOldMessages); - MimeMessage mm = wm.getMimeMessage(); - assertEquals(TEST_SUBJECT, mm.getSubject()); - - MimeMultipart mp = (MimeMultipart) mm.getContent(); - - // verify strict adherence to xhtml1-strict.dtd - SAXReader reader = new SAXReader(); - reader.setValidation(true); - reader.setEntityResolver(new XHTMLEntityResolver()); - reader.read(mp.getBodyPart(0).getInputStream()); - // System.out.println(GreenMailUtil.getBody(mp.getBodyPart(0))); - } - - @Test - /** - * Checks that even when many events are processed, the output is still - * conforms to xhtml-strict.dtd. - * - * Note that SMTPAppender only keeps only 500 or so (=buffer size) events. So - * the generated output will be rather short. - */ - public void htmlLong() throws Exception { - smtpAppender.setLayout(buildHTMLLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - for (int i = 0; i < CoreConstants.TABLE_ROW_LIMIT * 3; i++) { - logger.debug("hello " + i); + + @Test + public void authenticated() throws Exception { + MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); + mla.setAuthenticationHandlerFactory(new TrivialAuthHandlerFactory()); + + smtpAppender.setUsername("x"); + smtpAppender.setPassword("x"); + + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + waitUntilEmailIsSent(); + List wiserMsgList = WISER.getMessages(); + + assertNotNull(wiserMsgList); + assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); + WiserMessage wm = wiserMsgList.get(numberOfOldMessages); + // http://jira.qos.ch/browse/LBCLASSIC-67 + MimeMessage mm = wm.getMimeMessage(); + assertEquals(TEST_SUBJECT, mm.getSubject()); + + MimeMultipart mp = (MimeMultipart) mm.getContent(); + String body = getBody(mp.getBodyPart(0)); + assertTrue(body.startsWith(HEADER.trim())); + assertTrue(body.endsWith(FOOTER.trim())); + } + + @Test + @Ignore + // Unfortunately, there seems to be a problem with SubethaSMTP's implementation + // of startTLS. The same SMTPAppender code works fine when tested with gmail. + public void authenticatedSSL() throws Exception { + MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); + mla.setAuthenticationHandlerFactory(new TrivialAuthHandlerFactory()); + + smtpAppender.setSTARTTLS(true); + smtpAppender.setUsername("xx"); + smtpAppender.setPassword("xx"); + + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + waitUntilEmailIsSent(); + List wiserMsgList = WISER.getMessages(); + + assertNotNull(wiserMsgList); + assertEquals(1, wiserMsgList.size()); + } + + @Test + @Ignore + public void authenticatedGmailStartTLS() throws Exception { + smtpAppender.setSMTPHost("smtp.gmail.com"); + smtpAppender.setSMTPPort(587); + + smtpAppender.addTo("XXX@gmail.com"); + smtpAppender.setSTARTTLS(true); + smtpAppender.setUsername("XXX@gmail.com"); + smtpAppender.setPassword("XXX"); + + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("authenticatedGmailSTARTTLS"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + StatusPrinter.print(loggerContext); } - logger.error("en error", new Exception("an exception")); - waitUntilEmailIsSent(); - List wiserMsgList = WISER.getMessages(); - - assertNotNull(wiserMsgList); - assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); - WiserMessage wm = wiserMsgList.get(numberOfOldMessages); - MimeMessage mm = wm.getMimeMessage(); - assertEquals(TEST_SUBJECT, mm.getSubject()); - - MimeMultipart mp = (MimeMultipart) mm.getContent(); - - // verify strict adherence to xhtml1-strict.dtd - SAXReader reader = new SAXReader(); - reader.setValidation(true); - reader.setEntityResolver(new XHTMLEntityResolver()); - reader.read(mp.getBodyPart(0).getInputStream()); - } - - @Test - public void authenticated() throws Exception { - MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); - mla.setAuthenticationHandlerFactory(new TrivialAuthHandlerFactory()); - - smtpAppender.setUsername("x"); - smtpAppender.setPassword("x"); - - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - waitUntilEmailIsSent(); - List wiserMsgList = WISER.getMessages(); - - assertNotNull(wiserMsgList); - assertEquals(numberOfOldMessages + 1, wiserMsgList.size()); - WiserMessage wm = wiserMsgList.get(numberOfOldMessages); - // http://jira.qos.ch/browse/LBCLASSIC-67 - MimeMessage mm = wm.getMimeMessage(); - assertEquals(TEST_SUBJECT, mm.getSubject()); - - MimeMultipart mp = (MimeMultipart) mm.getContent(); - String body = getBody(mp.getBodyPart(0)); - assertTrue(body.startsWith(HEADER.trim())); - assertTrue(body.endsWith(FOOTER.trim())); - } - - @Test - @Ignore - // Unfortunately, there seems to be a problem with SubethaSMTP's implementation - // of startTLS. The same SMTPAppender code works fine when tested with gmail. - public void authenticatedSSL() throws Exception { - MessageListenerAdapter mla = (MessageListenerAdapter) WISER.getServer().getMessageHandlerFactory(); - mla.setAuthenticationHandlerFactory(new TrivialAuthHandlerFactory()); - - - smtpAppender.setSTARTTLS(true); - smtpAppender.setUsername("xx"); - smtpAppender.setPassword("xx"); - - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - waitUntilEmailIsSent(); - List wiserMsgList = WISER.getMessages(); - - assertNotNull(wiserMsgList); - assertEquals(1, wiserMsgList.size()); - } - - @Test - @Ignore - public void authenticatedGmailStartTLS() throws Exception { - smtpAppender.setSMTPHost("smtp.gmail.com"); - smtpAppender.setSMTPPort(587); - - smtpAppender.addTo("XXX@gmail.com"); - smtpAppender.setSTARTTLS(true); - smtpAppender.setUsername("XXX@gmail.com"); - smtpAppender.setPassword("XXX"); - - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("authenticatedGmailSTARTTLS"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - StatusPrinter.print(loggerContext); - } - - @Test - @Ignore - public void authenticatedGmail_SSL() throws Exception { - smtpAppender.setSMTPHost("smtp.gmail.com"); - smtpAppender.setSMTPPort(465); - - smtpAppender.addTo("XXX@gmail.com"); - smtpAppender.setSSL(true); - smtpAppender.setUsername("XXX@gmail.com"); - smtpAppender.setPassword("XXX"); - - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("authenticatedGmail_SSL"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - - StatusPrinter.print(loggerContext); - } - - @Test - public void testMultipleTo() throws Exception { - smtpAppender.setLayout(buildPatternLayout(loggerContext)); - smtpAppender.addTo("Test , other-test@example.com"); - smtpAppender.start(); - Logger logger = loggerContext.getLogger("test"); - logger.addAppender(smtpAppender); - logger.debug("hello"); - logger.error("en error", new Exception("an exception")); - waitUntilEmailIsSent(); - - List wiserMsgList = WISER.getMessages(); - assertNotNull(wiserMsgList); - assertEquals(numberOfOldMessages + 3, wiserMsgList.size()); - } - - public class TrivialAuthHandlerFactory implements AuthenticationHandlerFactory { - public AuthenticationHandler create() { - PluginAuthenticationHandler ret = new PluginAuthenticationHandler(); - UsernamePasswordValidator validator = new UsernamePasswordValidator() { - public void login(String username, String password) - throws LoginFailedException { - if (!username.equals(password)) { - throw new LoginFailedException("username=" + username + ", password=" + password); - } + + @Test + @Ignore + public void authenticatedGmail_SSL() throws Exception { + smtpAppender.setSMTPHost("smtp.gmail.com"); + smtpAppender.setSMTPPort(465); + + smtpAppender.addTo("XXX@gmail.com"); + smtpAppender.setSSL(true); + smtpAppender.setUsername("XXX@gmail.com"); + smtpAppender.setPassword("XXX"); + + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("authenticatedGmail_SSL"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + + StatusPrinter.print(loggerContext); + } + + @Test + public void testMultipleTo() throws Exception { + smtpAppender.setLayout(buildPatternLayout(loggerContext)); + smtpAppender.addTo("Test , other-test@example.com"); + smtpAppender.start(); + Logger logger = loggerContext.getLogger("test"); + logger.addAppender(smtpAppender); + logger.debug("hello"); + logger.error("en error", new Exception("an exception")); + waitUntilEmailIsSent(); + + List wiserMsgList = WISER.getMessages(); + assertNotNull(wiserMsgList); + assertEquals(numberOfOldMessages + 3, wiserMsgList.size()); + } + + public class TrivialAuthHandlerFactory implements AuthenticationHandlerFactory { + public AuthenticationHandler create() { + PluginAuthenticationHandler ret = new PluginAuthenticationHandler(); + UsernamePasswordValidator validator = new UsernamePasswordValidator() { + public void login(String username, String password) throws LoginFailedException { + if (!username.equals(password)) { + throw new LoginFailedException("username=" + username + ", password=" + password); + } + } + }; + ret.addPlugin(new PlainAuthenticationHandler(validator)); + ret.addPlugin(new LoginAuthenticationHandler(validator)); + return ret; } - }; - ret.addPlugin(new PlainAuthenticationHandler(validator)); - ret.addPlugin(new LoginAuthenticationHandler(validator)); - return ret; } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SSLSocketReceiverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SSLSocketReceiverTest.java index 3896e48f7bb91a0c0b5d856d51603e3eeb350e08..d35cffda3b51ad477340cca715576ad83c35fb76 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SSLSocketReceiverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SSLSocketReceiverTest.java @@ -30,22 +30,21 @@ import ch.qos.logback.classic.LoggerContext; */ public class SSLSocketReceiverTest { - private SSLSocketReceiver remote = - new SSLSocketReceiver(); - - @Before - public void setUp() throws Exception { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - remote.setContext(lc); - } - - @Test - public void testUsingDefaultConfig() throws Exception { - // should be able to start successfully with no SSL configuration at all - remote.setRemoteHost(InetAddress.getLocalHost().getHostAddress()); - remote.setPort(6000); - remote.start(); - assertNotNull(remote.getSocketFactory()); - } - + private SSLSocketReceiver remote = new SSLSocketReceiver(); + + @Before + public void setUp() throws Exception { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + remote.setContext(lc); + } + + @Test + public void testUsingDefaultConfig() throws Exception { + // should be able to start successfully with no SSL configuration at all + remote.setRemoteHost(InetAddress.getLocalHost().getHostAddress()); + remote.setPort(6000); + remote.start(); + assertNotNull(remote.getSocketFactory()); + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SerializationPerfTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SerializationPerfTest.java index 20a2f17dce2aaa14a155f8e48fad21522d6260f2..20d1f809a48b2246990c268d00eeb50e899a077a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SerializationPerfTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SerializationPerfTest.java @@ -24,180 +24,176 @@ import ch.qos.logback.classic.net.testObjectBuilders.TrivialLoggingEventVOBuilde public class SerializationPerfTest extends TestCase { - ObjectOutputStream oos; - - int loopNumber = 10000; - int resetFrequency = 100; - int pauseFrequency = 10; - long pauseLengthInMillis = 20; - - /** - *

- * Run the test with a MockSocketServer or with a NOPOutputStream - * - *

- * Run with external mock can be done using the ExternalMockSocketServer. It - * needs to be launched from a separate JVM. The ExternalMockSocketServer does - * not consume the events but passes through the available bytes that it is - * receiving. - * - *

- * For example, with 4 test methods, you can launch the - * ExternalMockSocketServer this way: - *

- *

- * java ch.qos.logback.classic.net.ExternalMockSocketServer 4 - *

- */ - boolean runWithExternalMockServer = true; - - /** - * Last results: - * Data sent mesured in kilobytes. - * Avg time mesured in microsecs. - * - * NOPOutputStream: - * | | Runs | Avg time | Data sent | - * | MinimalObj Ext | 10000 | | | - * | MinimalObj Ser | 10000 | | | - * | LoggEvent Ext | 10000 | | | - * | LoggEvent Ser | 10000 | | | - * - * External MockServer with 45 letters-long message: on localhost - * (always the same message) - * | | Runs | Avg time | Data sent | - * | MinimalObj Ext | 10000 | - | - | - * | MinimalObj Ser | 10000 | 74 | 248 | - * | LoggEvent Ext | 10000 | - | - | - * | LoggEvent Ser | 10000 | 156 | 835 | - * pauseFrequency = 10 and pauseLengthInMillis = 20 - * - * External MockServer with 45 letters-long message: on localhost - * (different message each time) - * | | Runs | Avg time | Data sent | - * | MinimalObj Ext | 10000 | | | - * | MinimalObj Ser | 10000 | 73 | 1139 | - * | LoggEvent Ext | 10000 | | | - * | LoggEvent Ser | 10000 | 162 | 1752 | - * pauseFrequency = 10 and pauseLengthInMillis = 20 - * - * External MockServer with 45 letters-long message: on PIXIE - * (always the same message) - * | | Runs | Avg time | Data sent | - * | MinimalObj Ext | 10000 | - | - | - * | MinimalObj Ser | 10000 | 29 | 248 | - * | LoggEvent Ext | 10000 | - | - | - * | LoggEvent Ser | 10000 | 42 | 835 | - * pauseFrequency = 10 and pauseLengthInMillis = 20 - * - * External MockServer with 45 letters-long message: on PIXIE - * (different message each time) - * | | Runs | Avg time | Data sent | - * | MinimalObj Ext | 10000 | | | - * | MinimalObj Ser | 10000 | 27 | 1139 | - * | LoggEvent Ext | 10000 | | | - * | LoggEvent Ser | 10000 | 44 | 1752 | - * pauseFrequency = 10 and pauseLengthInMillis = 20 - * - */ - - public void setUp() throws Exception { - super.setUp(); - if (runWithExternalMockServer) { - oos = new ObjectOutputStream(new Socket("localhost", - ExternalMockSocketServer.PORT).getOutputStream()); - } else { - oos = new ObjectOutputStream(new NOPOutputStream()); - } - } - - public void tearDown() throws Exception { - super.tearDown(); - oos.close(); - oos = null; - } - - public void runPerfTest(Builder builder, String label) throws Exception { - // long time1 = System.nanoTime(); - - // Object builtObject = builder.build(1); - - // first run for just in time compiler - int resetCounter = 0; - int pauseCounter = 0; - for (int i = 0; i < loopNumber; i++) { - try { - oos.writeObject(builder.build(i)); - oos.flush(); - if (++resetCounter >= resetFrequency) { - oos.reset(); - resetCounter = 0; - } - if (++pauseCounter >= pauseFrequency) { - Thread.sleep(pauseLengthInMillis); - pauseCounter = 0; + ObjectOutputStream oos; + + int loopNumber = 10000; + int resetFrequency = 100; + int pauseFrequency = 10; + long pauseLengthInMillis = 20; + + /** + *

+ * Run the test with a MockSocketServer or with a NOPOutputStream + * + *

+ * Run with external mock can be done using the ExternalMockSocketServer. It + * needs to be launched from a separate JVM. The ExternalMockSocketServer does + * not consume the events but passes through the available bytes that it is + * receiving. + * + *

+ * For example, with 4 test methods, you can launch the + * ExternalMockSocketServer this way: + *

+ *

+ * java ch.qos.logback.classic.net.ExternalMockSocketServer 4 + *

+ */ + boolean runWithExternalMockServer = true; + + /** + * Last results: + * Data sent mesured in kilobytes. + * Avg time mesured in microsecs. + * + * NOPOutputStream: + * | | Runs | Avg time | Data sent | + * | MinimalObj Ext | 10000 | | | + * | MinimalObj Ser | 10000 | | | + * | LoggEvent Ext | 10000 | | | + * | LoggEvent Ser | 10000 | | | + * + * External MockServer with 45 letters-long message: on localhost + * (always the same message) + * | | Runs | Avg time | Data sent | + * | MinimalObj Ext | 10000 | - | - | + * | MinimalObj Ser | 10000 | 74 | 248 | + * | LoggEvent Ext | 10000 | - | - | + * | LoggEvent Ser | 10000 | 156 | 835 | + * pauseFrequency = 10 and pauseLengthInMillis = 20 + * + * External MockServer with 45 letters-long message: on localhost + * (different message each time) + * | | Runs | Avg time | Data sent | + * | MinimalObj Ext | 10000 | | | + * | MinimalObj Ser | 10000 | 73 | 1139 | + * | LoggEvent Ext | 10000 | | | + * | LoggEvent Ser | 10000 | 162 | 1752 | + * pauseFrequency = 10 and pauseLengthInMillis = 20 + * + * External MockServer with 45 letters-long message: on PIXIE + * (always the same message) + * | | Runs | Avg time | Data sent | + * | MinimalObj Ext | 10000 | - | - | + * | MinimalObj Ser | 10000 | 29 | 248 | + * | LoggEvent Ext | 10000 | - | - | + * | LoggEvent Ser | 10000 | 42 | 835 | + * pauseFrequency = 10 and pauseLengthInMillis = 20 + * + * External MockServer with 45 letters-long message: on PIXIE + * (different message each time) + * | | Runs | Avg time | Data sent | + * | MinimalObj Ext | 10000 | | | + * | MinimalObj Ser | 10000 | 27 | 1139 | + * | LoggEvent Ext | 10000 | | | + * | LoggEvent Ser | 10000 | 44 | 1752 | + * pauseFrequency = 10 and pauseLengthInMillis = 20 + * + */ + + public void setUp() throws Exception { + super.setUp(); + if (runWithExternalMockServer) { + oos = new ObjectOutputStream(new Socket("localhost", ExternalMockSocketServer.PORT).getOutputStream()); + } else { + oos = new ObjectOutputStream(new NOPOutputStream()); } + } - } catch (IOException ex) { - fail(ex.getMessage()); - } + public void tearDown() throws Exception { + super.tearDown(); + oos.close(); + oos = null; } - // second run - Long t1; - Long t2; - Long total = 0L; - resetCounter = 0; - pauseCounter = 0; - // System.out.println("Beginning mesured run"); - for (int i = 0; i < loopNumber; i++) { - try { - t1 = System.nanoTime(); - oos.writeObject(builder.build(i)); - oos.flush(); - t2 = System.nanoTime(); - total += (t2 - t1); - if (++resetCounter >= resetFrequency) { - oos.reset(); - resetCounter = 0; + public void runPerfTest(Builder builder, String label) throws Exception { + // long time1 = System.nanoTime(); + + // Object builtObject = builder.build(1); + + // first run for just in time compiler + int resetCounter = 0; + int pauseCounter = 0; + for (int i = 0; i < loopNumber; i++) { + try { + oos.writeObject(builder.build(i)); + oos.flush(); + if (++resetCounter >= resetFrequency) { + oos.reset(); + resetCounter = 0; + } + if (++pauseCounter >= pauseFrequency) { + Thread.sleep(pauseLengthInMillis); + pauseCounter = 0; + } + + } catch (IOException ex) { + fail(ex.getMessage()); + } } - if (++pauseCounter >= pauseFrequency) { - Thread.sleep(pauseLengthInMillis); - pauseCounter = 0; + + // second run + Long t1; + Long t2; + Long total = 0L; + resetCounter = 0; + pauseCounter = 0; + // System.out.println("Beginning mesured run"); + for (int i = 0; i < loopNumber; i++) { + try { + t1 = System.nanoTime(); + oos.writeObject(builder.build(i)); + oos.flush(); + t2 = System.nanoTime(); + total += (t2 - t1); + if (++resetCounter >= resetFrequency) { + oos.reset(); + resetCounter = 0; + } + if (++pauseCounter >= pauseFrequency) { + Thread.sleep(pauseLengthInMillis); + pauseCounter = 0; + } + } catch (IOException ex) { + fail(ex.getMessage()); + } } - } catch (IOException ex) { - fail(ex.getMessage()); - } + total /= 1000; + System.out.println(label + " : average time = " + total / loopNumber + " microsecs after " + loopNumber + " writes."); + + // long time2 = System.nanoTime(); + // System.out.println("********* -> Time needed to run the test method: " + + // Long.toString(time2-time1)); + } + + // public void testWithMinimalExternalization() throws Exception { + // Builder builder = new MinimalExtBuilder(); + // runPerfTest(builder, "Minimal object externalization"); + // } + + public void testWithMinimalSerialization() throws Exception { + Builder builder = new MinimalSerBuilder(); + runPerfTest(builder, "Minimal object serialization"); + } + + // public void testWithExternalization() throws Exception { + // Builder builder = new LoggingEventExtBuilder(); + // runPerfTest(builder, "LoggingEvent object externalization"); + // } + + public void testWithSerialization() throws Exception { + Builder builder = new TrivialLoggingEventVOBuilder(); + runPerfTest(builder, "LoggingEventVO object serialization"); } - total /= 1000; - System.out.println(label + " : average time = " + total / loopNumber - + " microsecs after " + loopNumber + " writes."); - - // long time2 = System.nanoTime(); - // System.out.println("********* -> Time needed to run the test method: " + - // Long.toString(time2-time1)); - } - - // public void testWithMinimalExternalization() throws Exception { - // Builder builder = new MinimalExtBuilder(); - // runPerfTest(builder, "Minimal object externalization"); - // } - - public void testWithMinimalSerialization() throws Exception { - Builder builder = new MinimalSerBuilder(); - runPerfTest(builder, "Minimal object serialization"); - } - - // public void testWithExternalization() throws Exception { - // Builder builder = new LoggingEventExtBuilder(); - // runPerfTest(builder, "LoggingEvent object externalization"); - // } - - public void testWithSerialization() throws Exception { - Builder builder = new TrivialLoggingEventVOBuilder(); - runPerfTest(builder, "LoggingEventVO object serialization"); - } - - - + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketAppenderMessageLossTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketAppenderMessageLossTest.java index 6a49c0cb6a5e23669d11bf769f3c7a7aee61be0f..b9300c1a97e6af6718ebec847c00ee7a4a592dab 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketAppenderMessageLossTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketAppenderMessageLossTest.java @@ -30,100 +30,98 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SocketAppenderMessageLossTest { - int runLen = 100; - Duration reconnectionDelay = new Duration(1000); + int runLen = 100; + Duration reconnectionDelay = new Duration(1000); - @Test(timeout = 1000) - public void synchronousSocketAppender() throws Exception { + @Test(timeout = 1000) + public void synchronousSocketAppender() throws Exception { - SocketAppender socketAppender = new SocketAppender(); - socketAppender.setReconnectionDelay(reconnectionDelay); - socketAppender.setIncludeCallerData(true); + SocketAppender socketAppender = new SocketAppender(); + socketAppender.setReconnectionDelay(reconnectionDelay); + socketAppender.setIncludeCallerData(true); - runTest(socketAppender); - } - - @Test(timeout = 1000) - public void smallQueueSocketAppender() throws Exception { - - SocketAppender socketAppender = new SocketAppender(); - socketAppender.setReconnectionDelay(reconnectionDelay); - socketAppender.setQueueSize(runLen/10); + runTest(socketAppender); + } - runTest(socketAppender); - } + @Test(timeout = 1000) + public void smallQueueSocketAppender() throws Exception { - @Test(timeout = 1000) - public void largeQueueSocketAppender() throws Exception { - SocketAppender socketAppender = new SocketAppender(); - socketAppender.setReconnectionDelay(reconnectionDelay); - socketAppender.setQueueSize(runLen*5); + SocketAppender socketAppender = new SocketAppender(); + socketAppender.setReconnectionDelay(reconnectionDelay); + socketAppender.setQueueSize(runLen / 10); - runTest(socketAppender); - } + runTest(socketAppender); + } - // appender used to signal when the N'th event (as set in the latch) is received by the server - // this allows us to have test which are both more robust and quicker. - static public class ListAppenderWithLatch extends AppenderBase { - public List list = new ArrayList(); - CountDownLatch latch; + @Test(timeout = 1000) + public void largeQueueSocketAppender() throws Exception { + SocketAppender socketAppender = new SocketAppender(); + socketAppender.setReconnectionDelay(reconnectionDelay); + socketAppender.setQueueSize(runLen * 5); - ListAppenderWithLatch(CountDownLatch latch) { - this.latch = latch; + runTest(socketAppender); } - protected void append(ILoggingEvent e) { - list.add(e); - latch.countDown(); - } - } + // appender used to signal when the N'th event (as set in the latch) is received by the server + // this allows us to have test which are both more robust and quicker. + static public class ListAppenderWithLatch extends AppenderBase { + public List list = new ArrayList(); + CountDownLatch latch; - public void runTest(SocketAppender socketAppender) throws Exception { - final int port = RandomUtil.getRandomServerPort(); + ListAppenderWithLatch(CountDownLatch latch) { + this.latch = latch; + } - LoggerContext serverLoggerContext = new LoggerContext(); - serverLoggerContext.setName("serverLoggerContext"); + protected void append(ILoggingEvent e) { + list.add(e); + latch.countDown(); + } + } - CountDownLatch allMessagesReceivedLatch = new CountDownLatch(runLen); - ListAppenderWithLatch listAppender = new ListAppenderWithLatch(allMessagesReceivedLatch); - listAppender.setContext(serverLoggerContext); - listAppender.start(); + public void runTest(SocketAppender socketAppender) throws Exception { + final int port = RandomUtil.getRandomServerPort(); - Logger serverLogger = serverLoggerContext.getLogger(getClass()); - serverLogger.setAdditive(false); - serverLogger.addAppender(listAppender); + LoggerContext serverLoggerContext = new LoggerContext(); + serverLoggerContext.setName("serverLoggerContext"); + CountDownLatch allMessagesReceivedLatch = new CountDownLatch(runLen); + ListAppenderWithLatch listAppender = new ListAppenderWithLatch(allMessagesReceivedLatch); + listAppender.setContext(serverLoggerContext); + listAppender.start(); - LoggerContext loggerContext = new LoggerContext(); - loggerContext.setName("clientLoggerContext"); - socketAppender.setContext(loggerContext); + Logger serverLogger = serverLoggerContext.getLogger(getClass()); + serverLogger.setAdditive(false); + serverLogger.addAppender(listAppender); - CountDownLatch latch = new CountDownLatch(1); - SimpleSocketServer simpleSocketServer = new SimpleSocketServer(serverLoggerContext, port); - simpleSocketServer.start(); - simpleSocketServer.setLatch(latch); + LoggerContext loggerContext = new LoggerContext(); + loggerContext.setName("clientLoggerContext"); + socketAppender.setContext(loggerContext); - latch.await(); + CountDownLatch latch = new CountDownLatch(1); + SimpleSocketServer simpleSocketServer = new SimpleSocketServer(serverLoggerContext, port); + simpleSocketServer.start(); + simpleSocketServer.setLatch(latch); - socketAppender.setPort(port); - socketAppender.setRemoteHost("localhost"); - socketAppender.setReconnectionDelay(reconnectionDelay); - socketAppender.start(); - assertTrue(socketAppender.isStarted()); + latch.await(); - Logger logger = loggerContext.getLogger(getClass()); - logger.setAdditive(false); - logger.addAppender(socketAppender); + socketAppender.setPort(port); + socketAppender.setRemoteHost("localhost"); + socketAppender.setReconnectionDelay(reconnectionDelay); + socketAppender.start(); + assertTrue(socketAppender.isStarted()); + Logger logger = loggerContext.getLogger(getClass()); + logger.setAdditive(false); + logger.addAppender(socketAppender); - for (int i = 0; i < runLen; ++i) { - logger.info("hello"); - } + for (int i = 0; i < runLen; ++i) { + logger.info("hello"); + } - allMessagesReceivedLatch.await(); + allMessagesReceivedLatch.await(); - assertEquals(runLen, listAppender.list.size()); - loggerContext.stop(); - simpleSocketServer.close(); - } + assertEquals(runLen, listAppender.list.size()); + loggerContext.stop(); + simpleSocketServer.close(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketMin.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketMin.java index cb9f7f794956e390bdcf31814c43b4b1426e0d2c..bf4546b7b81394b0ce47d959728316fe158ef7db 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketMin.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketMin.java @@ -22,88 +22,86 @@ import ch.qos.logback.classic.Logger; public class SocketMin { - static Logger logger = (Logger) LoggerFactory.getLogger(SocketMin.class - .getName()); - static SocketAppender s; + static Logger logger = (Logger) LoggerFactory.getLogger(SocketMin.class.getName()); + static SocketAppender s; - public static void main(String argv[]) { - if (argv.length == 3) { - init(argv[0], argv[1]); - } else { - usage("Wrong number of arguments."); - } + public static void main(String argv[]) { + if (argv.length == 3) { + init(argv[0], argv[1]); + } else { + usage("Wrong number of arguments."); + } - // NDC.push("some context"); - if (argv[2].equals("true")) { - loop(); - } else { - test(); - } + // NDC.push("some context"); + if (argv[2].equals("true")) { + loop(); + } else { + test(); + } - s.stop(); - } + s.stop(); + } - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SocketMin.class - + " host port true|false"); - System.exit(1); - } + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SocketMin.class + " host port true|false"); + System.exit(1); + } - static void init(String host, String portStr) { - Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - BasicConfigurator.configure(root.getLoggerContext()); - try { - int port = Integer.parseInt(portStr); - logger.info("Creating socket appender (" + host + "," + port + ")."); - s = new SocketAppender(); - s.setRemoteHost(host); - s.setPort(port); - s.setName("S"); - root.addAppender(s); - } catch (java.lang.NumberFormatException e) { - e.printStackTrace(); - usage("Could not interpret port number [" + portStr + "]."); - } catch (Exception e) { - System.err.println("Could not start!"); - e.printStackTrace(); - System.exit(1); + static void init(String host, String portStr) { + Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + BasicConfigurator.configure(root.getLoggerContext()); + try { + int port = Integer.parseInt(portStr); + logger.info("Creating socket appender (" + host + "," + port + ")."); + s = new SocketAppender(); + s.setRemoteHost(host); + s.setPort(port); + s.setName("S"); + root.addAppender(s); + } catch (java.lang.NumberFormatException e) { + e.printStackTrace(); + usage("Could not interpret port number [" + portStr + "]."); + } catch (Exception e) { + System.err.println("Could not start!"); + e.printStackTrace(); + System.exit(1); + } } - } - static void loop() { - Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - InputStreamReader in = new InputStreamReader(System.in); - System.out.println("Type 'q' to quit"); - int i; - int k = 0; - while (true) { - logger.debug("Message " + k++); - logger.info("Message " + k++); - logger.warn("Message " + k++); - logger.error("Message " + k++, new Exception("Just testing")); - try { - i = in.read(); - } catch (Exception e) { - return; - } - if (i == -1) - break; - if (i == 'q') - break; - if (i == 'r') { - System.out.println("Removing appender S"); - root.detachAppender("S"); - } + static void loop() { + Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + InputStreamReader in = new InputStreamReader(System.in); + System.out.println("Type 'q' to quit"); + int i; + int k = 0; + while (true) { + logger.debug("Message " + k++); + logger.info("Message " + k++); + logger.warn("Message " + k++); + logger.error("Message " + k++, new Exception("Just testing")); + try { + i = in.read(); + } catch (Exception e) { + return; + } + if (i == -1) + break; + if (i == 'q') + break; + if (i == 'r') { + System.out.println("Removing appender S"); + root.detachAppender("S"); + } + } } - } - static void test() { - int i = 0; - logger.debug("Message " + i++); - logger.info("Message " + i++); - logger.warn("Message " + i++); - logger.error("Message " + i++); - logger.debug("Message " + i++, new Exception("Just testing.")); - } + static void test() { + int i = 0; + logger.debug("Message " + i++); + logger.info("Message " + i++); + logger.warn("Message " + i++); + logger.error("Message " + i++); + logger.debug("Message " + i++, new Exception("Just testing.")); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketReceiverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketReceiverTest.java index 4ac332d1aefdb717677329af915e6a47dafe6452..000c6de783c6e0d81df8383708247b5ec63ba388 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketReceiverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SocketReceiverTest.java @@ -52,238 +52,228 @@ import ch.qos.logback.core.status.Status; */ public class SocketReceiverTest { - private static final int DELAY = 1000; - private static final String TEST_HOST_NAME = "NOT.A.VALID.HOST.NAME"; - - - private ServerSocket serverSocket; - private Socket socket; - private MockSocketFactory socketFactory = new MockSocketFactory(); - private MockSocketConnector connector; - private MockAppender appender; - private LoggerContext lc; - private Logger logger; - - private InstrumentedSocketReceiver receiver = - new InstrumentedSocketReceiver(); - - @Before - public void setUp() throws Exception { - serverSocket = ServerSocketUtil.createServerSocket(); - socket = new Socket(serverSocket.getInetAddress(), - serverSocket.getLocalPort()); - connector = new MockSocketConnector(socket); - - lc = new LoggerContext(); - lc.reset(); - receiver.setContext(lc); - appender = new MockAppender(); - appender.start(); - logger = lc.getLogger(getClass()); - logger.addAppender(appender); - } - - @After - public void tearDown() throws Exception { - receiver.stop(); - ExecutorService executor = lc.getExecutorService(); - executor.shutdownNow(); - assertTrue(executor.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); - socket.close(); - serverSocket.close(); - lc.stop(); - } - - @Test - public void testStartNoRemoteAddress() throws Exception { - receiver.start(); - assertFalse(receiver.isStarted()); - int count = lc.getStatusManager().getCount(); - Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); - assertTrue(status.getMessage().contains("host")); - } - - @Test - public void testStartNoPort() throws Exception { - receiver.setRemoteHost(TEST_HOST_NAME); - receiver.start(); - assertFalse(receiver.isStarted()); - int count = lc.getStatusManager().getCount(); - Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); - assertTrue(status.getMessage().contains("port")); - } - - @Test - public void testStartUnknownHost() throws Exception { - receiver.setPort(6000); - receiver.setRemoteHost(TEST_HOST_NAME); - receiver.start(); - assertFalse(receiver.isStarted()); - int count = lc.getStatusManager().getCount(); - Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); - assertTrue(status.getMessage().contains("unknown host")); - } - - @Test - public void testStartStop() throws Exception { - receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); - receiver.setPort(6000); - receiver.setAcceptConnectionTimeout(DELAY / 2); - receiver.start(); - assertTrue(receiver.isStarted()); - receiver.awaitConnectorCreated(DELAY); - receiver.stop(); - assertFalse(receiver.isStarted()); - } - - @Test - public void testServerSlowToAcceptConnection() throws Exception { - receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); - receiver.setPort(6000); - receiver.setAcceptConnectionTimeout(DELAY / 4); - receiver.start(); - assertTrue(receiver.awaitConnectorCreated(DELAY / 2)); - // note that we don't call serverSocket.accept() here - // but processPriorToRemoval (in tearDown) should still clean up everything - } - - @Test - public void testServerDropsConnection() throws Exception { - receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); - receiver.setPort(6000); - receiver.start(); - assertTrue(receiver.awaitConnectorCreated(DELAY)); - Socket socket = serverSocket.accept(); - socket.close(); - } - - @Test - public void testDispatchEventForEnabledLevel() throws Exception { - receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); - receiver.setPort(6000); - receiver.start(); - assertTrue(receiver.awaitConnectorCreated(DELAY)); - Socket socket = serverSocket.accept(); - - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - - logger.setLevel(Level.DEBUG); - ILoggingEvent event = new LoggingEvent(logger.getName(), logger, - Level.DEBUG, "test message", null, new Object[0]); - - LoggingEventVO eventVO = LoggingEventVO.build(event); - oos.writeObject(eventVO); - oos.flush(); - - ILoggingEvent rcvdEvent = appender.awaitAppend(DELAY); - assertNotNull(rcvdEvent); - assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); - assertEquals(event.getLevel(), rcvdEvent.getLevel()); - assertEquals(event.getMessage(), rcvdEvent.getMessage()); - } - - @Test - public void testNoDispatchEventForDisabledLevel() throws Exception { - receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); - receiver.setPort(6000); - receiver.start(); - assertTrue(receiver.awaitConnectorCreated(DELAY)); - Socket socket = serverSocket.accept(); - - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - - logger.setLevel(Level.INFO); - ILoggingEvent event = new LoggingEvent(logger.getName(), logger, - Level.DEBUG, "test message", null, new Object[0]); - - LoggingEventVO eventVO = LoggingEventVO.build(event); - oos.writeObject(eventVO); - oos.flush(); - - assertNull(appender.awaitAppend(DELAY)); - } - - /** - * A {@link SocketReceiver} with instrumentation for unit testing. - */ - private class InstrumentedSocketReceiver extends SocketReceiver { - - private boolean connectorCreated; - - @Override - protected synchronized SocketConnector newConnector( - InetAddress address, int port, int initialDelay, int retryDelay) { - connectorCreated = true; - notifyAll(); - return connector; + private static final int DELAY = 1000; + private static final String TEST_HOST_NAME = "NOT.A.VALID.HOST.NAME"; + + private ServerSocket serverSocket; + private Socket socket; + private MockSocketFactory socketFactory = new MockSocketFactory(); + private MockSocketConnector connector; + private MockAppender appender; + private LoggerContext lc; + private Logger logger; + + private InstrumentedSocketReceiver receiver = new InstrumentedSocketReceiver(); + + @Before + public void setUp() throws Exception { + serverSocket = ServerSocketUtil.createServerSocket(); + socket = new Socket(serverSocket.getInetAddress(), serverSocket.getLocalPort()); + connector = new MockSocketConnector(socket); + + lc = new LoggerContext(); + lc.reset(); + receiver.setContext(lc); + appender = new MockAppender(); + appender.start(); + logger = lc.getLogger(getClass()); + logger.addAppender(appender); } - @Override - protected SocketFactory getSocketFactory() { - return socketFactory; + @After + public void tearDown() throws Exception { + receiver.stop(); + ExecutorService executor = lc.getExecutorService(); + executor.shutdownNow(); + assertTrue(executor.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); + socket.close(); + serverSocket.close(); + lc.stop(); } - public synchronized boolean awaitConnectorCreated(long delay) - throws InterruptedException { - while (!connectorCreated) { - wait(delay); - } - return connectorCreated; + @Test + public void testStartNoRemoteAddress() throws Exception { + receiver.start(); + assertFalse(receiver.isStarted()); + int count = lc.getStatusManager().getCount(); + Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); + assertTrue(status.getMessage().contains("host")); } - } - - /** - * A {@link SocketConnector} with instrumentation for unit testing. - */ - private static class MockSocketConnector implements SocketConnector { - - private final Socket socket; - - public MockSocketConnector(Socket socket) { - this.socket = socket; + @Test + public void testStartNoPort() throws Exception { + receiver.setRemoteHost(TEST_HOST_NAME); + receiver.start(); + assertFalse(receiver.isStarted()); + int count = lc.getStatusManager().getCount(); + Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); + assertTrue(status.getMessage().contains("port")); } - public Socket call() throws InterruptedException { - return socket; + @Test + public void testStartUnknownHost() throws Exception { + receiver.setPort(6000); + receiver.setRemoteHost(TEST_HOST_NAME); + receiver.start(); + assertFalse(receiver.isStarted()); + int count = lc.getStatusManager().getCount(); + Status status = lc.getStatusManager().getCopyOfStatusList().get(count - 1); + assertTrue(status.getMessage().contains("unknown host")); } - public void setExceptionHandler(ExceptionHandler exceptionHandler) { + @Test + public void testStartStop() throws Exception { + receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); + receiver.setPort(6000); + receiver.setAcceptConnectionTimeout(DELAY / 2); + receiver.start(); + assertTrue(receiver.isStarted()); + receiver.awaitConnectorCreated(DELAY); + receiver.stop(); + assertFalse(receiver.isStarted()); } - public void setSocketFactory(SocketFactory socketFactory) { + @Test + public void testServerSlowToAcceptConnection() throws Exception { + receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); + receiver.setPort(6000); + receiver.setAcceptConnectionTimeout(DELAY / 4); + receiver.start(); + assertTrue(receiver.awaitConnectorCreated(DELAY / 2)); + // note that we don't call serverSocket.accept() here + // but processPriorToRemoval (in tearDown) should still clean up everything } - } + @Test + public void testServerDropsConnection() throws Exception { + receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); + receiver.setPort(6000); + receiver.start(); + assertTrue(receiver.awaitConnectorCreated(DELAY)); + Socket socket = serverSocket.accept(); + socket.close(); + } + + @Test + public void testDispatchEventForEnabledLevel() throws Exception { + receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); + receiver.setPort(6000); + receiver.start(); + assertTrue(receiver.awaitConnectorCreated(DELAY)); + Socket socket = serverSocket.accept(); + + ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); + + logger.setLevel(Level.DEBUG); + ILoggingEvent event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); - /** - * A no-op {@link SocketFactory} to support unit testing. - */ - private static class MockSocketFactory extends SocketFactory { + LoggingEventVO eventVO = LoggingEventVO.build(event); + oos.writeObject(eventVO); + oos.flush(); - @Override - public Socket createSocket(InetAddress address, int port, - InetAddress localAddress, int localPort) throws IOException { - throw new UnsupportedOperationException(); + ILoggingEvent rcvdEvent = appender.awaitAppend(DELAY); + assertNotNull(rcvdEvent); + assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); + assertEquals(event.getLevel(), rcvdEvent.getLevel()); + assertEquals(event.getMessage(), rcvdEvent.getMessage()); } - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - throw new UnsupportedOperationException(); + @Test + public void testNoDispatchEventForDisabledLevel() throws Exception { + receiver.setRemoteHost(InetAddress.getLocalHost().getHostName()); + receiver.setPort(6000); + receiver.start(); + assertTrue(receiver.awaitConnectorCreated(DELAY)); + Socket socket = serverSocket.accept(); + + ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); + + logger.setLevel(Level.INFO); + ILoggingEvent event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); + + LoggingEventVO eventVO = LoggingEventVO.build(event); + oos.writeObject(eventVO); + oos.flush(); + + assertNull(appender.awaitAppend(DELAY)); } - @Override - public Socket createSocket(String host, int port, InetAddress localHost, - int localPort) throws IOException, UnknownHostException { - throw new UnsupportedOperationException(); + /** + * A {@link SocketReceiver} with instrumentation for unit testing. + */ + private class InstrumentedSocketReceiver extends SocketReceiver { + + private boolean connectorCreated; + + @Override + protected synchronized SocketConnector newConnector(InetAddress address, int port, int initialDelay, int retryDelay) { + connectorCreated = true; + notifyAll(); + return connector; + } + + @Override + protected SocketFactory getSocketFactory() { + return socketFactory; + } + + public synchronized boolean awaitConnectorCreated(long delay) throws InterruptedException { + while (!connectorCreated) { + wait(delay); + } + return connectorCreated; + } + } - @Override - public Socket createSocket(String host, int port) throws IOException, - UnknownHostException { - throw new UnsupportedOperationException(); + /** + * A {@link SocketConnector} with instrumentation for unit testing. + */ + private static class MockSocketConnector implements SocketConnector { + + private final Socket socket; + + public MockSocketConnector(Socket socket) { + this.socket = socket; + } + + public Socket call() throws InterruptedException { + return socket; + } + + public void setExceptionHandler(ExceptionHandler exceptionHandler) { + } + + public void setSocketFactory(SocketFactory socketFactory) { + } + } - - } - + + /** + * A no-op {@link SocketFactory} to support unit testing. + */ + private static class MockSocketFactory extends SocketFactory { + + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { + throw new UnsupportedOperationException(); + } + + @Override + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + throw new UnsupportedOperationException(); + } + + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/SyslogAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/SyslogAppenderTest.java index 2b9a9abbc5c5f6ecd944207ef452dec9f182979e..94670a8f31bea1b378a82ad674cb8a774997491b 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/SyslogAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/SyslogAppenderTest.java @@ -37,243 +37,228 @@ import java.nio.charset.Charset; public class SyslogAppenderTest { - private static final String SYSLOG_PREFIX_REGEX = "<\\d{2}>\\w{3} [\\d ]\\d \\d{2}(:\\d{2}){2} [\\w.-]* "; - - LoggerContext lc = new LoggerContext(); - SyslogAppender sa = new SyslogAppender(); - MockSyslogServer mockServer; - String loggerName = this.getClass().getName(); - Logger logger = lc.getLogger(loggerName); - - @Before - public void setUp() throws Exception { - lc.setName("test"); - sa.setContext(lc); - } - - @After - public void tearDown() throws Exception { - } - - public void setMockServerAndConfigure(int expectedCount, String suffixPattern) - throws InterruptedException { - int port = RandomUtil.getRandomServerPort(); - - mockServer = new MockSyslogServer(expectedCount, port); - mockServer.start(); - // give MockSyslogServer head start - - Thread.sleep(100); - - sa.setSyslogHost("localhost"); - sa.setFacility("MAIL"); - sa.setPort(port); - sa.setSuffixPattern(suffixPattern); - sa.setStackTracePattern("[%thread] foo "+CoreConstants.TAB); - sa.start(); - assertTrue(sa.isStarted()); + private static final String SYSLOG_PREFIX_REGEX = "<\\d{2}>\\w{3} [\\d ]\\d \\d{2}(:\\d{2}){2} [\\w.-]* "; + LoggerContext lc = new LoggerContext(); + SyslogAppender sa = new SyslogAppender(); + MockSyslogServer mockServer; String loggerName = this.getClass().getName(); Logger logger = lc.getLogger(loggerName); - logger.addAppender(sa); - - } - - public void setMockServerAndConfigure(int expectedCount) - throws InterruptedException { - this.setMockServerAndConfigure(expectedCount, "[%thread] %logger %msg"); - } - - @Test - public void basic() throws InterruptedException { - - setMockServerAndConfigure(1); - String logMsg = "hello"; - logger.debug(logMsg); - - // wait max 2 seconds for mock server to finish. However, it should - // much sooner than that. - mockServer.join(8000); - - assertTrue(mockServer.isFinished()); - assertEquals(1, mockServer.getMessageList().size()); - String msg = new String(mockServer.getMessageList().get(0)); - - String threadName = Thread.currentThread().getName(); - - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; - assertTrue(msg.startsWith(expected)); - - checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " - + logMsg); - - } - - @Test - public void suffixPatternWithTag() throws InterruptedException { - setMockServerAndConfigure(1, "test/something [%thread] %logger %msg"); - String logMsg = "hello"; - logger.debug(logMsg); - - // wait max 2 seconds for mock server to finish. However, it should - // much sooner than that. - mockServer.join(8000); - - assertTrue(mockServer.isFinished()); - assertEquals(1, mockServer.getMessageList().size()); - String msg = new String(mockServer.getMessageList().get(0)); - - String threadName = Thread.currentThread().getName(); - - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; - assertTrue(msg.startsWith(expected)); - - checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "test/something \\[" + threadName + "\\] " + loggerName + " " - + logMsg); - - } - - @Test - public void tException() throws InterruptedException { - setMockServerAndConfigure(21); - - String logMsg = "hello"; - String exMsg = "just testing"; - Exception ex = new Exception(exMsg); - logger.debug(logMsg, ex); - StatusPrinter.print(lc); - - // wait max 2 seconds for mock server to finish. However, it should - // much sooner than that. - mockServer.join(8000); - assertTrue(mockServer.isFinished()); - - // message + 20 lines of stacktrace - assertEquals(21, mockServer.getMessageList().size()); - // int i = 0; - // for (String line: mockServer.msgList) { - // System.out.println(i++ + ": " + line); - // } - - String msg = new String(mockServer.getMessageList().get(0)); - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; - assertTrue(msg.startsWith(expected)); - - String threadName = Thread.currentThread().getName(); - String regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName - + " " + logMsg; - checkRegexMatch(msg, regex); - - msg = new String(mockServer.getMessageList().get(1)); - assertTrue(msg.contains(ex.getClass().getName())); - assertTrue(msg.contains(ex.getMessage())); - - msg = new String(mockServer.getMessageList().get(2)); - assertTrue(msg.startsWith(expected)); - regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + "foo "+CoreConstants.TAB + "at ch\\.qos.*"; - checkRegexMatch(msg, regex); - } - - private void checkRegexMatch(String s, String regex) { - assertTrue("The string [" + s + "] did not match regex [" + regex + "]", s - .matches(regex)); - } - - @Test - public void large() throws Exception { - setMockServerAndConfigure(2); - StringBuilder largeBuf = new StringBuilder(); - for (int i = 0; i < 2 * 1024 * 1024; i++) { - largeBuf.append('a'); + + @Before + public void setUp() throws Exception { + lc.setName("test"); + sa.setContext(lc); + } + + @After + public void tearDown() throws Exception { + } + + public void setMockServerAndConfigure(int expectedCount, String suffixPattern) throws InterruptedException { + int port = RandomUtil.getRandomServerPort(); + + mockServer = new MockSyslogServer(expectedCount, port); + mockServer.start(); + // give MockSyslogServer head start + + Thread.sleep(100); + + sa.setSyslogHost("localhost"); + sa.setFacility("MAIL"); + sa.setPort(port); + sa.setSuffixPattern(suffixPattern); + sa.setStackTracePattern("[%thread] foo " + CoreConstants.TAB); + sa.start(); + assertTrue(sa.isStarted()); + + String loggerName = this.getClass().getName(); + Logger logger = lc.getLogger(loggerName); + logger.addAppender(sa); + + } + + public void setMockServerAndConfigure(int expectedCount) throws InterruptedException { + this.setMockServerAndConfigure(expectedCount, "[%thread] %logger %msg"); + } + + @Test + public void basic() throws InterruptedException { + + setMockServerAndConfigure(1); + String logMsg = "hello"; + logger.debug(logMsg); + + // wait max 2 seconds for mock server to finish. However, it should + // much sooner than that. + mockServer.join(8000); + + assertTrue(mockServer.isFinished()); + assertEquals(1, mockServer.getMessageList().size()); + String msg = new String(mockServer.getMessageList().get(0)); + + String threadName = Thread.currentThread().getName(); + + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; + assertTrue(msg.startsWith(expected)); + + checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " + logMsg); + + } + + @Test + public void suffixPatternWithTag() throws InterruptedException { + setMockServerAndConfigure(1, "test/something [%thread] %logger %msg"); + String logMsg = "hello"; + logger.debug(logMsg); + + // wait max 2 seconds for mock server to finish. However, it should + // much sooner than that. + mockServer.join(8000); + + assertTrue(mockServer.isFinished()); + assertEquals(1, mockServer.getMessageList().size()); + String msg = new String(mockServer.getMessageList().get(0)); + + String threadName = Thread.currentThread().getName(); + + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; + assertTrue(msg.startsWith(expected)); + + checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "test/something \\[" + threadName + "\\] " + loggerName + " " + logMsg); + + } + + @Test + public void tException() throws InterruptedException { + setMockServerAndConfigure(21); + + String logMsg = "hello"; + String exMsg = "just testing"; + Exception ex = new Exception(exMsg); + logger.debug(logMsg, ex); + StatusPrinter.print(lc); + + // wait max 2 seconds for mock server to finish. However, it should + // much sooner than that. + mockServer.join(8000); + assertTrue(mockServer.isFinished()); + + // message + 20 lines of stacktrace + assertEquals(21, mockServer.getMessageList().size()); + // int i = 0; + // for (String line: mockServer.msgList) { + // System.out.println(i++ + ": " + line); + // } + + String msg = new String(mockServer.getMessageList().get(0)); + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; + assertTrue(msg.startsWith(expected)); + + String threadName = Thread.currentThread().getName(); + String regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " + logMsg; + checkRegexMatch(msg, regex); + + msg = new String(mockServer.getMessageList().get(1)); + assertTrue(msg.contains(ex.getClass().getName())); + assertTrue(msg.contains(ex.getMessage())); + + msg = new String(mockServer.getMessageList().get(2)); + assertTrue(msg.startsWith(expected)); + regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + "foo " + CoreConstants.TAB + "at ch\\.qos.*"; + checkRegexMatch(msg, regex); + } + + private void checkRegexMatch(String s, String regex) { + assertTrue("The string [" + s + "] did not match regex [" + regex + "]", s.matches(regex)); + } + + @Test + public void large() throws Exception { + setMockServerAndConfigure(2); + StringBuilder largeBuf = new StringBuilder(); + for (int i = 0; i < 2 * 1024 * 1024; i++) { + largeBuf.append('a'); + } + logger.debug(largeBuf.toString()); + + String logMsg = "hello"; + logger.debug(logMsg); + Thread.sleep(RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN + 10); + logger.debug(logMsg); + + mockServer.join(8000); + assertTrue(mockServer.isFinished()); + + // both messages received + assertEquals(2, mockServer.getMessageList().size()); + + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; + String threadName = Thread.currentThread().getName(); + + // large message is truncated + final int maxMessageSize = sa.getMaxMessageSize(); + String largeMsg = new String(mockServer.getMessageList().get(0)); + assertTrue(largeMsg.startsWith(expected)); + String largeRegex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " + "a{" + (maxMessageSize - 2000) + "," + maxMessageSize + "}"; + checkRegexMatch(largeMsg, largeRegex); + + String msg = new String(mockServer.getMessageList().get(1)); + assertTrue(msg.startsWith(expected)); + String regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " + logMsg; + checkRegexMatch(msg, regex); + } + + @Test + public void LBCLASSIC_50() throws JoranException { + + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "syslog_LBCLASSIC_50.xml"); + + org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("hello"); + } + + @Test + public void unknownHostShouldNotCauseStopToFail() { + // See LOGBACK-960 + sa.setSyslogHost("unknown.host"); + sa.setFacility("MAIL"); + sa.start(); + sa.stop(); + } + + @Test + public void nonAsciiMessageEncoding() throws Exception { + // See LOGBACK-732 + setMockServerAndConfigure(1); + + // Use a string that can be encoded in a somewhat odd encoding (ISO-8859-4) to minimize + // the probability of the encoding test to work by accident + String logMsg = "R\u0129ga"; // Riga spelled with the i having a tilda on top + + Charset ISO_8859_4 = Charset.forName("ISO-8859-4"); + sa.setCharset(ISO_8859_4); + logger.debug(logMsg); + + // wait max 8 seconds for mock server to finish. However, it should + // be done much sooner than that. + mockServer.join(8000); + + assertTrue(mockServer.isFinished()); + assertEquals(1, mockServer.getMessageList().size()); + String msg = new String(mockServer.getMessageList().get(0), ISO_8859_4); + String threadName = Thread.currentThread().getName(); + + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; + assertTrue(msg.startsWith(expected)); + + System.out.println(logMsg); + checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " + logMsg); + } - logger.debug(largeBuf.toString()); - - String logMsg = "hello"; - logger.debug(logMsg); - Thread.sleep(RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN+10); - logger.debug(logMsg); - - mockServer.join(8000); - assertTrue(mockServer.isFinished()); - - // both messages received - assertEquals(2, mockServer.getMessageList().size()); - - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; - String threadName = Thread.currentThread().getName(); - - // large message is truncated - final int maxMessageSize = sa.getMaxMessageSize(); - String largeMsg = new String(mockServer.getMessageList().get(0)); - assertTrue(largeMsg.startsWith(expected)); - String largeRegex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName - + " " + "a{" + (maxMessageSize - 2000) + "," + maxMessageSize + "}"; - checkRegexMatch(largeMsg, largeRegex); - - String msg = new String(mockServer.getMessageList().get(1)); - assertTrue(msg.startsWith(expected)); - String regex = SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName - + " " + logMsg; - checkRegexMatch(msg, regex); - } - - @Test - public void LBCLASSIC_50() throws JoranException { - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX - + "syslog_LBCLASSIC_50.xml"); - - org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("hello"); - } - - @Test - public void unknownHostShouldNotCauseStopToFail() { - // See LOGBACK-960 - sa.setSyslogHost("unknown.host"); - sa.setFacility("MAIL"); - sa.start(); - sa.stop(); - } - - @Test - public void nonAsciiMessageEncoding() throws Exception { - // See LOGBACK-732 - setMockServerAndConfigure(1); - - // Use a string that can be encoded in a somewhat odd encoding (ISO-8859-4) to minimize - // the probability of the encoding test to work by accident - String logMsg = "R\u0129ga"; // Riga spelled with the i having a tilda on top - - Charset ISO_8859_4 = Charset.forName("ISO-8859-4"); - sa.setCharset(ISO_8859_4); - logger.debug(logMsg); - - // wait max 8 seconds for mock server to finish. However, it should - // be done much sooner than that. - mockServer.join(8000); - - assertTrue(mockServer.isFinished()); - assertEquals(1, mockServer.getMessageList().size()); - String msg = new String(mockServer.getMessageList().get(0), ISO_8859_4); - String threadName = Thread.currentThread().getName(); - - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.DEBUG_SEVERITY) + ">"; - assertTrue(msg.startsWith(expected)); - - System.out.println(logMsg); - checkRegexMatch(msg, SYSLOG_PREFIX_REGEX + "\\[" + threadName + "\\] " + loggerName + " " - + logMsg); - - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockAppender.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockAppender.java index e781932fb6641e73e99f02863d65a3d6f2294352..842278fe66ea85963d13446a3cdec37e7930d65f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockAppender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockAppender.java @@ -30,29 +30,27 @@ import ch.qos.logback.core.AppenderBase; */ public class MockAppender extends AppenderBase { - private final Lock lock = new ReentrantLock(); - private final Condition appendCondition = lock.newCondition(); - private final BlockingQueue events = - new LinkedBlockingQueue(); - - @Override - protected void append(ILoggingEvent eventObject) { - lock.lock(); - try { - events.offer(eventObject); - appendCondition.signalAll(); + private final Lock lock = new ReentrantLock(); + private final Condition appendCondition = lock.newCondition(); + private final BlockingQueue events = new LinkedBlockingQueue(); + + @Override + protected void append(ILoggingEvent eventObject) { + lock.lock(); + try { + events.offer(eventObject); + appendCondition.signalAll(); + } finally { + lock.unlock(); + } + } + + public ILoggingEvent awaitAppend(long delay) throws InterruptedException { + return events.poll(delay, TimeUnit.MILLISECONDS); } - finally { - lock.unlock(); + + public ILoggingEvent getLastEvent() { + return events.peek(); } - } - - public ILoggingEvent awaitAppend(long delay) throws InterruptedException { - return events.poll(delay, TimeUnit.MILLISECONDS); - } - - public ILoggingEvent getLastEvent() { - return events.peek(); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockObjectMessage.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockObjectMessage.java index 3e2a35dc097708443279c537aa58a56317cfb080..7e27db0e3d2874eb28d0298e69b0e215a23b0e56 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockObjectMessage.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockObjectMessage.java @@ -22,239 +22,216 @@ import javax.jms.ObjectMessage; public class MockObjectMessage implements ObjectMessage { - Serializable object; - - public Serializable getObject() throws JMSException { - return object; - } - - public void setObject(Serializable object) throws JMSException { - this.object = object; - } - - public void acknowledge() throws JMSException { - - - } - - public void clearBody() throws JMSException { - - - } - - public void clearProperties() throws JMSException { - - - } - - public boolean getBooleanProperty(String arg0) throws JMSException { - - return false; - } - - public byte getByteProperty(String arg0) throws JMSException { - - return 0; - } - - public double getDoubleProperty(String arg0) throws JMSException { - - return 0; - } - - public float getFloatProperty(String arg0) throws JMSException { - - return 0; - } - - public int getIntProperty(String arg0) throws JMSException { - - return 0; - } - - public String getJMSCorrelationID() throws JMSException { - - return null; - } - - public byte[] getJMSCorrelationIDAsBytes() throws JMSException { - - return null; - } - - public int getJMSDeliveryMode() throws JMSException { - - return 0; - } - - public Destination getJMSDestination() throws JMSException { - - return null; - } - - public long getJMSExpiration() throws JMSException { - - return 0; - } - - public String getJMSMessageID() throws JMSException { - - return null; - } - - public int getJMSPriority() throws JMSException { - - return 0; - } - - public boolean getJMSRedelivered() throws JMSException { - - return false; - } - - public Destination getJMSReplyTo() throws JMSException { - - return null; - } - - public long getJMSTimestamp() throws JMSException { - - return 0; - } - - public String getJMSType() throws JMSException { - - return null; - } - - public long getLongProperty(String arg0) throws JMSException { - - return 0; - } - - public Object getObjectProperty(String arg0) throws JMSException { - - return null; - } - - public Enumeration getPropertyNames() throws JMSException { - - return null; - } - - public short getShortProperty(String arg0) throws JMSException { - - return 0; - } - - public String getStringProperty(String arg0) throws JMSException { - - return null; - } - - public boolean propertyExists(String arg0) throws JMSException { - - return false; - } - - public void setBooleanProperty(String arg0, boolean arg1) throws JMSException { - - - } - - public void setByteProperty(String arg0, byte arg1) throws JMSException { - - - } - - public void setDoubleProperty(String arg0, double arg1) throws JMSException { - - - } - - public void setFloatProperty(String arg0, float arg1) throws JMSException { - - - } - - public void setIntProperty(String arg0, int arg1) throws JMSException { - - - } - - public void setJMSCorrelationID(String arg0) throws JMSException { - - - } - - public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException { - - - } - - public void setJMSDeliveryMode(int arg0) throws JMSException { - - - } - - public void setJMSDestination(Destination arg0) throws JMSException { - - - } - - public void setJMSExpiration(long arg0) throws JMSException { - - - } - - public void setJMSMessageID(String arg0) throws JMSException { - - - } - - public void setJMSPriority(int arg0) throws JMSException { - - - } - - public void setJMSRedelivered(boolean arg0) throws JMSException { - - - } - - public void setJMSReplyTo(Destination arg0) throws JMSException { - - - } - - public void setJMSTimestamp(long arg0) throws JMSException { - - - } - - public void setJMSType(String arg0) throws JMSException { - - - } - - public void setLongProperty(String arg0, long arg1) throws JMSException { - - - } - - public void setObjectProperty(String arg0, Object arg1) throws JMSException { - - - } - - public void setShortProperty(String arg0, short arg1) throws JMSException { - - - } - - public void setStringProperty(String arg0, String arg1) throws JMSException { - - - } + Serializable object; + + public Serializable getObject() throws JMSException { + return object; + } + + public void setObject(Serializable object) throws JMSException { + this.object = object; + } + + public void acknowledge() throws JMSException { + + } + + public void clearBody() throws JMSException { + + } + + public void clearProperties() throws JMSException { + + } + + public boolean getBooleanProperty(String arg0) throws JMSException { + + return false; + } + + public byte getByteProperty(String arg0) throws JMSException { + + return 0; + } + + public double getDoubleProperty(String arg0) throws JMSException { + + return 0; + } + + public float getFloatProperty(String arg0) throws JMSException { + + return 0; + } + + public int getIntProperty(String arg0) throws JMSException { + + return 0; + } + + public String getJMSCorrelationID() throws JMSException { + + return null; + } + + public byte[] getJMSCorrelationIDAsBytes() throws JMSException { + + return null; + } + + public int getJMSDeliveryMode() throws JMSException { + + return 0; + } + + public Destination getJMSDestination() throws JMSException { + + return null; + } + + public long getJMSExpiration() throws JMSException { + + return 0; + } + + public String getJMSMessageID() throws JMSException { + + return null; + } + + public int getJMSPriority() throws JMSException { + + return 0; + } + + public boolean getJMSRedelivered() throws JMSException { + + return false; + } + + public Destination getJMSReplyTo() throws JMSException { + + return null; + } + + public long getJMSTimestamp() throws JMSException { + + return 0; + } + + public String getJMSType() throws JMSException { + + return null; + } + + public long getLongProperty(String arg0) throws JMSException { + + return 0; + } + + public Object getObjectProperty(String arg0) throws JMSException { + + return null; + } + + public Enumeration getPropertyNames() throws JMSException { + + return null; + } + + public short getShortProperty(String arg0) throws JMSException { + + return 0; + } + + public String getStringProperty(String arg0) throws JMSException { + + return null; + } + + public boolean propertyExists(String arg0) throws JMSException { + + return false; + } + + public void setBooleanProperty(String arg0, boolean arg1) throws JMSException { + + } + + public void setByteProperty(String arg0, byte arg1) throws JMSException { + + } + + public void setDoubleProperty(String arg0, double arg1) throws JMSException { + + } + + public void setFloatProperty(String arg0, float arg1) throws JMSException { + + } + + public void setIntProperty(String arg0, int arg1) throws JMSException { + + } + + public void setJMSCorrelationID(String arg0) throws JMSException { + + } + + public void setJMSCorrelationIDAsBytes(byte[] arg0) throws JMSException { + + } + + public void setJMSDeliveryMode(int arg0) throws JMSException { + + } + + public void setJMSDestination(Destination arg0) throws JMSException { + + } + + public void setJMSExpiration(long arg0) throws JMSException { + + } + + public void setJMSMessageID(String arg0) throws JMSException { + + } + + public void setJMSPriority(int arg0) throws JMSException { + + } + + public void setJMSRedelivered(boolean arg0) throws JMSException { + + } + + public void setJMSReplyTo(Destination arg0) throws JMSException { + + } + + public void setJMSTimestamp(long arg0) throws JMSException { + + } + + public void setJMSType(String arg0) throws JMSException { + + } + + public void setLongProperty(String arg0, long arg1) throws JMSException { + + } + + public void setObjectProperty(String arg0, Object arg1) throws JMSException { + + } + + public void setShortProperty(String arg0, short arg1) throws JMSException { + + } + + public void setStringProperty(String arg0, String arg1) throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueue.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueue.java index 1b4b672b2bb2abe080928d084675bc2c0120270f..9d4699ebda163a116659465b3ab832ceeee75a2a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueue.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueue.java @@ -18,14 +18,14 @@ import javax.jms.Queue; public class MockQueue implements Queue { - String name; - - public MockQueue(String name) { - this.name = name; - } - - public String getQueueName() throws JMSException { - return name; - } + String name; + + public MockQueue(String name) { + this.name = name; + } + + public String getQueueName() throws JMSException { + return name; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnection.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnection.java index 5e530e3d761b804fc7a03cdd3fa7c7ff0dc6dd0b..88474e2fff94de27ea330d6bc233202848470b80 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnection.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnection.java @@ -27,70 +27,65 @@ import javax.jms.Topic; public class MockQueueConnection implements QueueConnection { - MockQueueSession session = new MockQueueSession(); - - public QueueSession createQueueSession(boolean arg0, int arg1) throws JMSException { - return session; - } - - public ConnectionConsumer createConnectionConsumer(Queue arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { - - return null; - } - - public void close() throws JMSException { - - - } - - public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { - - return null; - } - - public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2, ServerSessionPool arg3, int arg4) throws JMSException { - - return null; - } - - public Session createSession(boolean arg0, int arg1) throws JMSException { - - return null; - } - - public String getClientID() throws JMSException { - - return null; - } - - public ExceptionListener getExceptionListener() throws JMSException { - - return null; - } - - public ConnectionMetaData getMetaData() throws JMSException { - - return null; - } - - public void setClientID(String arg0) throws JMSException { - - - } - - public void setExceptionListener(ExceptionListener arg0) throws JMSException { - - - } - - public void start() throws JMSException { - - - } - - public void stop() throws JMSException { - - - } + MockQueueSession session = new MockQueueSession(); + + public QueueSession createQueueSession(boolean arg0, int arg1) throws JMSException { + return session; + } + + public ConnectionConsumer createConnectionConsumer(Queue arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { + + return null; + } + + public void close() throws JMSException { + + } + + public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { + + return null; + } + + public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2, ServerSessionPool arg3, int arg4) throws JMSException { + + return null; + } + + public Session createSession(boolean arg0, int arg1) throws JMSException { + + return null; + } + + public String getClientID() throws JMSException { + + return null; + } + + public ExceptionListener getExceptionListener() throws JMSException { + + return null; + } + + public ConnectionMetaData getMetaData() throws JMSException { + + return null; + } + + public void setClientID(String arg0) throws JMSException { + + } + + public void setExceptionListener(ExceptionListener arg0) throws JMSException { + + } + + public void start() throws JMSException { + + } + + public void stop() throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnectionFactory.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnectionFactory.java index a516efca0956675b8eb91e87f1d5cbb6fc05cef7..d8cabd56ca247abb2389d82267d166ab054caa15 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnectionFactory.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueConnectionFactory.java @@ -20,23 +20,23 @@ import javax.jms.QueueConnectionFactory; public class MockQueueConnectionFactory implements QueueConnectionFactory { - MockQueueConnection cnx = new MockQueueConnection(); - - public QueueConnection createQueueConnection() throws JMSException { - return cnx; - } - - public QueueConnection createQueueConnection(String user, String pass) throws JMSException { - - return cnx; - } - - public Connection createConnection() throws JMSException { - return null; - } - - public Connection createConnection(String arg0, String arg1) throws JMSException { - return null; - } + MockQueueConnection cnx = new MockQueueConnection(); + + public QueueConnection createQueueConnection() throws JMSException { + return cnx; + } + + public QueueConnection createQueueConnection(String user, String pass) throws JMSException { + + return cnx; + } + + public Connection createConnection() throws JMSException { + return null; + } + + public Connection createConnection(String arg0, String arg1) throws JMSException { + return null; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSender.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSender.java index fe8ea434bdafa4908df5836d63ccb29072001ee0..fe95dcbb884da02d0e071dc30a30166b55e9b1cf 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSender.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSender.java @@ -24,111 +24,98 @@ import javax.jms.QueueSender; public class MockQueueSender implements QueueSender { - List messageList = new ArrayList(); - Queue queue; - - public MockQueueSender(Queue queue) { - this.queue = queue; - } - - public List getMessageList() { - return messageList; - } - - public Queue getQueue() throws JMSException { - return queue; - } + List messageList = new ArrayList(); + Queue queue; - public void send(Message message) throws JMSException { - messageList.add(message); - - } + public MockQueueSender(Queue queue) { + this.queue = queue; + } - public void send(Queue arg0, Message arg1) throws JMSException { + public List getMessageList() { + return messageList; + } - - } + public Queue getQueue() throws JMSException { + return queue; + } - public void send(Message arg0, int arg1, int arg2, long arg3) throws JMSException { + public void send(Message message) throws JMSException { + messageList.add(message); - - } + } - public void send(Queue arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { + public void send(Queue arg0, Message arg1) throws JMSException { - - } + } - public void close() throws JMSException { + public void send(Message arg0, int arg1, int arg2, long arg3) throws JMSException { - - } + } - public int getDeliveryMode() throws JMSException { + public void send(Queue arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { - return 0; - } + } - public Destination getDestination() throws JMSException { + public void close() throws JMSException { - return null; - } + } - public boolean getDisableMessageID() throws JMSException { + public int getDeliveryMode() throws JMSException { - return false; - } + return 0; + } - public boolean getDisableMessageTimestamp() throws JMSException { + public Destination getDestination() throws JMSException { - return false; - } + return null; + } - public int getPriority() throws JMSException { + public boolean getDisableMessageID() throws JMSException { - return 0; - } + return false; + } - public long getTimeToLive() throws JMSException { + public boolean getDisableMessageTimestamp() throws JMSException { - return 0; - } + return false; + } - public void send(Destination arg0, Message arg1) throws JMSException { + public int getPriority() throws JMSException { - - } + return 0; + } - public void send(Destination arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { + public long getTimeToLive() throws JMSException { - - } + return 0; + } - public void setDeliveryMode(int arg0) throws JMSException { + public void send(Destination arg0, Message arg1) throws JMSException { - - } + } - public void setDisableMessageID(boolean arg0) throws JMSException { + public void send(Destination arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { - - } + } - public void setDisableMessageTimestamp(boolean arg0) throws JMSException { + public void setDeliveryMode(int arg0) throws JMSException { - - } + } - public void setPriority(int arg0) throws JMSException { + public void setDisableMessageID(boolean arg0) throws JMSException { - - } + } - public void setTimeToLive(long arg0) throws JMSException { + public void setDisableMessageTimestamp(boolean arg0) throws JMSException { - - } - - + } + + public void setPriority(int arg0) throws JMSException { + + } + + public void setTimeToLive(long arg0) throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSession.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSession.java index e31fee6aaa4c4542b6019ead708a79adecd90071..392ece9dbba9f649c12d469f9e244d46b05fa575 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSession.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockQueueSession.java @@ -38,171 +38,163 @@ import javax.jms.TopicSubscriber; public class MockQueueSession implements QueueSession { - public ObjectMessage createObjectMessage() throws JMSException { - return new MockObjectMessage(); - } - - public QueueSender createSender(Queue queue) throws JMSException { - if (queue == null) { - return null; + public ObjectMessage createObjectMessage() throws JMSException { + return new MockObjectMessage(); } - return new MockQueueSender(queue); - } - public QueueBrowser createBrowser(Queue arg0) throws JMSException { + public QueueSender createSender(Queue queue) throws JMSException { + if (queue == null) { + return null; + } + return new MockQueueSender(queue); + } - return null; - } + public QueueBrowser createBrowser(Queue arg0) throws JMSException { - public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException { + return null; + } - return null; - } + public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException { - public Queue createQueue(String arg0) throws JMSException { + return null; + } - return null; - } + public Queue createQueue(String arg0) throws JMSException { - public QueueReceiver createReceiver(Queue arg0) throws JMSException { + return null; + } - return null; - } + public QueueReceiver createReceiver(Queue arg0) throws JMSException { - public QueueReceiver createReceiver(Queue arg0, String arg1) throws JMSException { + return null; + } - return null; - } + public QueueReceiver createReceiver(Queue arg0, String arg1) throws JMSException { - public TemporaryQueue createTemporaryQueue() throws JMSException { + return null; + } - return null; - } + public TemporaryQueue createTemporaryQueue() throws JMSException { - public void close() throws JMSException { + return null; + } - - } + public void close() throws JMSException { - public void commit() throws JMSException { + } - - } + public void commit() throws JMSException { - public BytesMessage createBytesMessage() throws JMSException { + } - return null; - } + public BytesMessage createBytesMessage() throws JMSException { - public MessageConsumer createConsumer(Destination arg0) throws JMSException { + return null; + } - return null; - } + public MessageConsumer createConsumer(Destination arg0) throws JMSException { - public MessageConsumer createConsumer(Destination arg0, String arg1) throws JMSException { + return null; + } - return null; - } + public MessageConsumer createConsumer(Destination arg0, String arg1) throws JMSException { - public MessageConsumer createConsumer(Destination arg0, String arg1, boolean arg2) throws JMSException { + return null; + } - return null; - } + public MessageConsumer createConsumer(Destination arg0, String arg1, boolean arg2) throws JMSException { - public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException { + return null; + } - return null; - } + public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException { - public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1, String arg2, boolean arg3) throws JMSException { + return null; + } - return null; - } + public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1, String arg2, boolean arg3) throws JMSException { - public MapMessage createMapMessage() throws JMSException { + return null; + } - return null; - } + public MapMessage createMapMessage() throws JMSException { - public Message createMessage() throws JMSException { + return null; + } - return null; - } + public Message createMessage() throws JMSException { - public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException { + return null; + } - return null; - } + public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException { - public MessageProducer createProducer(Destination arg0) throws JMSException { + return null; + } + + public MessageProducer createProducer(Destination arg0) throws JMSException { - return null; - } + return null; + } - public StreamMessage createStreamMessage() throws JMSException { + public StreamMessage createStreamMessage() throws JMSException { - return null; - } + return null; + } - public TemporaryTopic createTemporaryTopic() throws JMSException { + public TemporaryTopic createTemporaryTopic() throws JMSException { - return null; - } + return null; + } - public TextMessage createTextMessage() throws JMSException { + public TextMessage createTextMessage() throws JMSException { - return null; - } + return null; + } - public TextMessage createTextMessage(String arg0) throws JMSException { + public TextMessage createTextMessage(String arg0) throws JMSException { - return null; - } + return null; + } - public Topic createTopic(String arg0) throws JMSException { + public Topic createTopic(String arg0) throws JMSException { - return null; - } + return null; + } - public int getAcknowledgeMode() throws JMSException { + public int getAcknowledgeMode() throws JMSException { - return 0; - } + return 0; + } - public MessageListener getMessageListener() throws JMSException { + public MessageListener getMessageListener() throws JMSException { - return null; - } + return null; + } - public boolean getTransacted() throws JMSException { + public boolean getTransacted() throws JMSException { - return false; - } + return false; + } - public void recover() throws JMSException { + public void recover() throws JMSException { - - } + } - public void rollback() throws JMSException { + public void rollback() throws JMSException { - - } + } - public void run() { + public void run() { - - } + } - public void setMessageListener(MessageListener arg0) throws JMSException { + public void setMessageListener(MessageListener arg0) throws JMSException { - - } + } - public void unsubscribe(String arg0) throws JMSException { + public void unsubscribe(String arg0) throws JMSException { - - } - + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockSyslogServer.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockSyslogServer.java index 972999071316c9f6bae2644338fb2c99281aed3e..46ee016f7021ee0a44775408e6bd847af4a5ce46 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockSyslogServer.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockSyslogServer.java @@ -24,49 +24,52 @@ import java.util.List; */ public class MockSyslogServer extends Thread { - final int loopLen; - final int port; - - List msgList = new ArrayList(); - boolean finished = false; - - public MockSyslogServer(int loopLen, int port) { - super(); - this.loopLen = loopLen; - this.port = port; - } + final int loopLen; + final int port; - @Override - public void run() { - //System.out.println("MockSyslogServer listening on port "+port); - DatagramSocket socket = null; - try { - socket = new DatagramSocket(port); + List msgList = new ArrayList(); + boolean finished = false; - for (int i = 0; i < loopLen; i++) { - byte[] buf = new byte[65536]; - DatagramPacket packet = new DatagramPacket(buf, buf.length); - //System.out.println("Waiting for message"); - socket.receive(packet); - byte[] out = new byte[packet.getLength()]; - System.arraycopy(buf, 0, out, 0, out.length); - msgList.add(out); - } - } catch (Exception se) { - se.printStackTrace(); - } finally { - if(socket != null) { - try {socket.close();} catch(Exception e) {} - } + public MockSyslogServer(int loopLen, int port) { + super(); + this.loopLen = loopLen; + this.port = port; + } + + @Override + public void run() { + // System.out.println("MockSyslogServer listening on port "+port); + DatagramSocket socket = null; + try { + socket = new DatagramSocket(port); + + for (int i = 0; i < loopLen; i++) { + byte[] buf = new byte[65536]; + DatagramPacket packet = new DatagramPacket(buf, buf.length); + // System.out.println("Waiting for message"); + socket.receive(packet); + byte[] out = new byte[packet.getLength()]; + System.arraycopy(buf, 0, out, 0, out.length); + msgList.add(out); + } + } catch (Exception se) { + se.printStackTrace(); + } finally { + if (socket != null) { + try { + socket.close(); + } catch (Exception e) { + } + } + } + finished = true; + } + + public boolean isFinished() { + return finished; + } + + public List getMessageList() { + return msgList; } - finished = true; - } - - public boolean isFinished() { - return finished; - } - - public List getMessageList() { - return msgList; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopic.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopic.java index d596c14543fbe9b3865deeef5e5f1489efe90970..19b6841ec365d3e4bbbc0b6f612639943f80970e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopic.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopic.java @@ -18,14 +18,14 @@ import javax.jms.Topic; public class MockTopic implements Topic { - String name; - - public MockTopic(String name) { - this.name = name; - } - - public String getTopicName() throws JMSException { - return name; - } + String name; + + public MockTopic(String name) { + this.name = name; + } + + public String getTopicName() throws JMSException { + return name; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnection.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnection.java index 8a2217a530434302b13544d2cb0b891af517daf1..59fb25bdccabe7b91bd9988f69da3ba0834aca01 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnection.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnection.java @@ -26,70 +26,65 @@ import javax.jms.TopicSession; public class MockTopicConnection implements TopicConnection { - MockTopicSession session = new MockTopicSession(); - - public TopicSession createTopicSession(boolean arg0, int arg1) throws JMSException { - return session; - } - - public ConnectionConsumer createConnectionConsumer(Topic arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { - - return null; - } - - public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2, ServerSessionPool arg3, int arg4) throws JMSException { - - return null; - } - - public void close() throws JMSException { - - - } - - public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { - - return null; - } - - public Session createSession(boolean arg0, int arg1) throws JMSException { - - return null; - } - - public String getClientID() throws JMSException { - - return null; - } - - public ExceptionListener getExceptionListener() throws JMSException { - - return null; - } - - public ConnectionMetaData getMetaData() throws JMSException { - - return null; - } - - public void setClientID(String arg0) throws JMSException { - - - } - - public void setExceptionListener(ExceptionListener arg0) throws JMSException { - - - } - - public void start() throws JMSException { - - - } - - public void stop() throws JMSException { - - - } + MockTopicSession session = new MockTopicSession(); + + public TopicSession createTopicSession(boolean arg0, int arg1) throws JMSException { + return session; + } + + public ConnectionConsumer createConnectionConsumer(Topic arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { + + return null; + } + + public ConnectionConsumer createDurableConnectionConsumer(Topic arg0, String arg1, String arg2, ServerSessionPool arg3, int arg4) throws JMSException { + + return null; + } + + public void close() throws JMSException { + + } + + public ConnectionConsumer createConnectionConsumer(Destination arg0, String arg1, ServerSessionPool arg2, int arg3) throws JMSException { + + return null; + } + + public Session createSession(boolean arg0, int arg1) throws JMSException { + + return null; + } + + public String getClientID() throws JMSException { + + return null; + } + + public ExceptionListener getExceptionListener() throws JMSException { + + return null; + } + + public ConnectionMetaData getMetaData() throws JMSException { + + return null; + } + + public void setClientID(String arg0) throws JMSException { + + } + + public void setExceptionListener(ExceptionListener arg0) throws JMSException { + + } + + public void start() throws JMSException { + + } + + public void stop() throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnectionFactory.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnectionFactory.java index a54dbea422ce1c20ae4aab3d4dd97f8604b11ef0..d9a1cbb25830dd431ca8611068dfef472b53189c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnectionFactory.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicConnectionFactory.java @@ -20,23 +20,23 @@ import javax.jms.TopicConnectionFactory; public class MockTopicConnectionFactory implements TopicConnectionFactory { - MockTopicConnection cnx = new MockTopicConnection(); - - public TopicConnection createTopicConnection() throws JMSException { - return cnx; - } - - public TopicConnection createTopicConnection(String user, String pass) throws JMSException { - - return cnx; - } - - public Connection createConnection() throws JMSException { - return null; - } - - public Connection createConnection(String arg0, String arg1) throws JMSException { - return null; - } + MockTopicConnection cnx = new MockTopicConnection(); + + public TopicConnection createTopicConnection() throws JMSException { + return cnx; + } + + public TopicConnection createTopicConnection(String user, String pass) throws JMSException { + + return cnx; + } + + public Connection createConnection() throws JMSException { + return null; + } + + public Connection createConnection(String arg0, String arg1) throws JMSException { + return null; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicPublisher.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicPublisher.java index 5ab6d17ebc6fdac21626f507fbf056b30fb74c2b..57bec47426117d536856976377c88b2b19c2135e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicPublisher.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicPublisher.java @@ -24,117 +24,105 @@ import javax.jms.TopicPublisher; public class MockTopicPublisher implements TopicPublisher { - List messageList = new ArrayList(); - Topic topic; - - public MockTopicPublisher(Topic topic) { - this.topic = topic; - } - - public void publish(Message message) throws JMSException { - messageList.add(message); - } - - public List getMessageList() { - return messageList; - } - - public Topic getTopic() throws JMSException { - return topic; - } - - public void publish(Message arg0, int arg1, int arg2, long arg3) throws JMSException { - - } - - public void publish(Topic arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { - - - } - - public void publish(Topic arg0, Message arg1) throws JMSException { - - - } - - public void close() throws JMSException { - - - } - - public int getDeliveryMode() throws JMSException { - - return 0; - } - - public Destination getDestination() throws JMSException { - - return null; - } - - public boolean getDisableMessageID() throws JMSException { - - return false; - } - - public boolean getDisableMessageTimestamp() throws JMSException { - - return false; - } - - public int getPriority() throws JMSException { - - return 0; - } - - public long getTimeToLive() throws JMSException { - - return 0; - } - - public void send(Destination arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { - - - } - - public void send(Destination arg0, Message arg1) throws JMSException { - - - } - - public void send(Message arg0, int arg1, int arg2, long arg3) throws JMSException { - - - } - - public void send(Message arg0) throws JMSException { - - - } - - public void setDeliveryMode(int arg0) throws JMSException { - - - } - - public void setDisableMessageID(boolean arg0) throws JMSException { - - - } - - public void setDisableMessageTimestamp(boolean arg0) throws JMSException { - - - } - - public void setPriority(int arg0) throws JMSException { - - - } - - public void setTimeToLive(long arg0) throws JMSException { - - - } + List messageList = new ArrayList(); + Topic topic; + + public MockTopicPublisher(Topic topic) { + this.topic = topic; + } + + public void publish(Message message) throws JMSException { + messageList.add(message); + } + + public List getMessageList() { + return messageList; + } + + public Topic getTopic() throws JMSException { + return topic; + } + + public void publish(Message arg0, int arg1, int arg2, long arg3) throws JMSException { + + } + + public void publish(Topic arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { + + } + + public void publish(Topic arg0, Message arg1) throws JMSException { + + } + + public void close() throws JMSException { + + } + + public int getDeliveryMode() throws JMSException { + + return 0; + } + + public Destination getDestination() throws JMSException { + + return null; + } + + public boolean getDisableMessageID() throws JMSException { + + return false; + } + + public boolean getDisableMessageTimestamp() throws JMSException { + + return false; + } + + public int getPriority() throws JMSException { + + return 0; + } + + public long getTimeToLive() throws JMSException { + + return 0; + } + + public void send(Destination arg0, Message arg1, int arg2, int arg3, long arg4) throws JMSException { + + } + + public void send(Destination arg0, Message arg1) throws JMSException { + + } + + public void send(Message arg0, int arg1, int arg2, long arg3) throws JMSException { + + } + + public void send(Message arg0) throws JMSException { + + } + + public void setDeliveryMode(int arg0) throws JMSException { + + } + + public void setDisableMessageID(boolean arg0) throws JMSException { + + } + + public void setDisableMessageTimestamp(boolean arg0) throws JMSException { + + } + + public void setPriority(int arg0) throws JMSException { + + } + + public void setTimeToLive(long arg0) throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicSession.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicSession.java index ab261b14c4fb81808a7d5fbf60638f29a5217b9d..8ced38e690635e78668ebb6de90bbf18d9b3292a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicSession.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/mock/MockTopicSession.java @@ -37,162 +37,157 @@ import javax.jms.TopicSubscriber; public class MockTopicSession implements TopicSession { - public ObjectMessage createObjectMessage() throws JMSException { - return new MockObjectMessage(); - } - - public TopicPublisher createPublisher(Topic topic) throws JMSException { - if (topic == null) { - return null; - } - return new MockTopicPublisher(topic); - } - - - public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException { - return null; - } - - public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1, String arg2, boolean arg3) throws JMSException { - return null; - } - - public TopicSubscriber createSubscriber(Topic arg0) throws JMSException { - return null; - } - - public TopicSubscriber createSubscriber(Topic arg0, String arg1, boolean arg2) throws JMSException { - return null; - } - - public TemporaryTopic createTemporaryTopic() throws JMSException { - return null; - } - - public Topic createTopic(String arg0) throws JMSException { - return null; - } - - public void unsubscribe(String arg0) throws JMSException { - - } - - public void close() throws JMSException { - - } - - public void commit() throws JMSException { - - } - - public QueueBrowser createBrowser(Queue arg0) throws JMSException { - - return null; - } - - public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException { - - return null; - } - - public BytesMessage createBytesMessage() throws JMSException { - - return null; - } - - public MessageConsumer createConsumer(Destination arg0) throws JMSException { - - return null; - } - - public MessageConsumer createConsumer(Destination arg0, String arg1) throws JMSException { - - return null; - } - - public MessageConsumer createConsumer(Destination arg0, String arg1, boolean arg2) throws JMSException { - - return null; - } - - public MapMessage createMapMessage() throws JMSException { - - return null; - } - - public Message createMessage() throws JMSException { - - return null; - } - - public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException { - - return null; - } - - public MessageProducer createProducer(Destination arg0) throws JMSException { - - return null; - } - - public Queue createQueue(String arg0) throws JMSException { - - return null; - } - - public StreamMessage createStreamMessage() throws JMSException { - - return null; - } - - public TemporaryQueue createTemporaryQueue() throws JMSException { - - return null; - } - - public TextMessage createTextMessage() throws JMSException { - - return null; - } - - public TextMessage createTextMessage(String arg0) throws JMSException { - - return null; - } - - public int getAcknowledgeMode() throws JMSException { - - return 0; - } - - public MessageListener getMessageListener() throws JMSException { - - return null; - } - - public boolean getTransacted() throws JMSException { - - return false; - } - - public void recover() throws JMSException { - - - } - - public void rollback() throws JMSException { - - - } - - public void run() { - - - } - - public void setMessageListener(MessageListener arg0) throws JMSException { - - - } + public ObjectMessage createObjectMessage() throws JMSException { + return new MockObjectMessage(); + } + + public TopicPublisher createPublisher(Topic topic) throws JMSException { + if (topic == null) { + return null; + } + return new MockTopicPublisher(topic); + } + + public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1) throws JMSException { + return null; + } + + public TopicSubscriber createDurableSubscriber(Topic arg0, String arg1, String arg2, boolean arg3) throws JMSException { + return null; + } + + public TopicSubscriber createSubscriber(Topic arg0) throws JMSException { + return null; + } + + public TopicSubscriber createSubscriber(Topic arg0, String arg1, boolean arg2) throws JMSException { + return null; + } + + public TemporaryTopic createTemporaryTopic() throws JMSException { + return null; + } + + public Topic createTopic(String arg0) throws JMSException { + return null; + } + + public void unsubscribe(String arg0) throws JMSException { + + } + + public void close() throws JMSException { + + } + + public void commit() throws JMSException { + + } + + public QueueBrowser createBrowser(Queue arg0) throws JMSException { + + return null; + } + + public QueueBrowser createBrowser(Queue arg0, String arg1) throws JMSException { + + return null; + } + + public BytesMessage createBytesMessage() throws JMSException { + + return null; + } + + public MessageConsumer createConsumer(Destination arg0) throws JMSException { + + return null; + } + + public MessageConsumer createConsumer(Destination arg0, String arg1) throws JMSException { + + return null; + } + + public MessageConsumer createConsumer(Destination arg0, String arg1, boolean arg2) throws JMSException { + + return null; + } + + public MapMessage createMapMessage() throws JMSException { + + return null; + } + + public Message createMessage() throws JMSException { + + return null; + } + + public ObjectMessage createObjectMessage(Serializable arg0) throws JMSException { + + return null; + } + + public MessageProducer createProducer(Destination arg0) throws JMSException { + + return null; + } + + public Queue createQueue(String arg0) throws JMSException { + + return null; + } + + public StreamMessage createStreamMessage() throws JMSException { + + return null; + } + + public TemporaryQueue createTemporaryQueue() throws JMSException { + + return null; + } + + public TextMessage createTextMessage() throws JMSException { + + return null; + } + + public TextMessage createTextMessage(String arg0) throws JMSException { + + return null; + } + + public int getAcknowledgeMode() throws JMSException { + + return 0; + } + + public MessageListener getMessageListener() throws JMSException { + + return null; + } + + public boolean getTransacted() throws JMSException { + + return false; + } + + public void recover() throws JMSException { + + } + + public void rollback() throws JMSException { + + } + + public void run() { + + } + + public void setMessageListener(MessageListener arg0) throws JMSException { + + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/InstrumentedServerSocketReceiver.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/InstrumentedServerSocketReceiver.java index 5ec994f45202571812e84b55858843f81bc8771c..7487888549c6c0a1518e7191ce797f34372f541a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/InstrumentedServerSocketReceiver.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/InstrumentedServerSocketReceiver.java @@ -26,71 +26,63 @@ import ch.qos.logback.classic.net.server.ServerSocketReceiver; import ch.qos.logback.core.net.server.ServerListener; import ch.qos.logback.core.net.server.ServerRunner; - /** * A {@link ServerSocketReceiver} with instrumentation for unit testing. * * @author Carl Harris */ public class InstrumentedServerSocketReceiver extends ServerSocketReceiver { - - private final ServerSocket serverSocket; - private final ServerListener listener; - private final ServerRunner runner; - - private ServerListener lastListener; - - public InstrumentedServerSocketReceiver(ServerSocket serverSocket) { - this(serverSocket, new RemoteAppenderServerListener(serverSocket), null); - } - - public InstrumentedServerSocketReceiver(ServerSocket serverSocket, - ServerListener listener, - ServerRunner runner) { - this.serverSocket = serverSocket; - this.listener = listener; - this.runner = runner; - } - - @Override - protected ServerSocketFactory getServerSocketFactory() throws Exception { - return new ServerSocketFactory() { - - @Override - public ServerSocket createServerSocket(int port) throws IOException { - return serverSocket; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog) - throws IOException { - return serverSocket; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog, - InetAddress ifAddress) throws IOException { - return serverSocket; - } - }; - } - - @Override - protected ServerRunner createServerRunner( - ServerListener listener, - Executor executor) { - lastListener = listener; - return runner != null ? runner : super.createServerRunner(listener, executor); - } - - @Override - protected ServerListener createServerListener( - ServerSocket socket) { - return listener; - } - - public ServerListener getLastListener() { - return lastListener; - } + + private final ServerSocket serverSocket; + private final ServerListener listener; + private final ServerRunner runner; + + private ServerListener lastListener; + + public InstrumentedServerSocketReceiver(ServerSocket serverSocket) { + this(serverSocket, new RemoteAppenderServerListener(serverSocket), null); + } + + public InstrumentedServerSocketReceiver(ServerSocket serverSocket, ServerListener listener, ServerRunner runner) { + this.serverSocket = serverSocket; + this.listener = listener; + this.runner = runner; + } + + @Override + protected ServerSocketFactory getServerSocketFactory() throws Exception { + return new ServerSocketFactory() { + + @Override + public ServerSocket createServerSocket(int port) throws IOException { + return serverSocket; + } + + @Override + public ServerSocket createServerSocket(int port, int backlog) throws IOException { + return serverSocket; + } + + @Override + public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { + return serverSocket; + } + }; + } + + @Override + protected ServerRunner createServerRunner(ServerListener listener, Executor executor) { + lastListener = listener; + return runner != null ? runner : super.createServerRunner(listener, executor); + } + + @Override + protected ServerListener createServerListener(ServerSocket socket) { + return listener; + } + + public ServerListener getLastListener() { + return lastListener; + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLConfiguration.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLConfiguration.java index d0ecddb7915f4eae014442c727d4006e99bed297..1c21d035a30378180a67a56feeaf8f7487e8b529 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLConfiguration.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLConfiguration.java @@ -32,19 +32,17 @@ import ch.qos.logback.core.spi.ContextAware; */ class MockSSLConfiguration extends SSLConfiguration { - private boolean contextCreated; - - @Override - public SSLContext createContext(ContextAware context) - throws NoSuchProviderException, NoSuchAlgorithmException, - KeyManagementException, UnrecoverableKeyException, KeyStoreException, - CertificateException { - contextCreated = true; - return super.createContext(context); - } - - public boolean isContextCreated() { - return contextCreated; - } + private boolean contextCreated; + + @Override + public SSLContext createContext(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException, + UnrecoverableKeyException, KeyStoreException, CertificateException { + contextCreated = true; + return super.createContext(context); + } + + public boolean isContextCreated() { + return contextCreated; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLParametersConfiguration.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLParametersConfiguration.java index c0a3e9880761a674b218b1545fcb2fa3e8f55331..4d36e022cbf428ceee5ade73d1f580b3f784e2de 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLParametersConfiguration.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/MockSSLParametersConfiguration.java @@ -24,16 +24,16 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; */ class MockSSLParametersConfiguration extends SSLParametersConfiguration { - private boolean contextInjected; - - @Override - public void setContext(Context context) { - contextInjected = true; - super.setContext(context); - } + private boolean contextInjected; + + @Override + public void setContext(Context context) { + contextInjected = true; + super.setContext(context); + } + + public boolean isContextInjected() { + return contextInjected; + } - public boolean isContextInjected() { - return contextInjected; - } - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClientTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClientTest.java index 98c9696f6f9035e8e665e470e6a0f043bfb059ce..55cd864df7872e0bd7946cf6586d626093cf5ab9 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClientTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/RemoteAppenderStreamClientTest.java @@ -39,54 +39,53 @@ import ch.qos.logback.classic.spi.LoggingEventVO; */ public class RemoteAppenderStreamClientTest { - private MockAppender appender; - private Logger logger; - private LoggingEvent event; - private RemoteAppenderStreamClient client; - - @Before - public void setUp() throws Exception { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - appender = new MockAppender(); - appender.start(); - - logger = lc.getLogger(getClass()); - logger.addAppender(appender); - - event = new LoggingEvent(logger.getName(), logger, - Level.DEBUG, "test message", null, new Object[0]); - - LoggingEventVO eventVO = LoggingEventVO.build(event); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(bos); - oos.writeObject(eventVO); - oos.close(); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - client = new RemoteAppenderStreamClient("some client ID", bis); - client.setLoggerContext(lc); - } - - @Test - public void testWithEnabledLevel() throws Exception { - logger.setLevel(Level.DEBUG); - client.run(); - client.close(); - - ILoggingEvent rcvdEvent = appender.getLastEvent(); - assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); - assertEquals(event.getLevel(), rcvdEvent.getLevel()); - assertEquals(event.getMessage(), rcvdEvent.getMessage()); - } - - @Test - public void testWithDisabledLevel() throws Exception { - logger.setLevel(Level.INFO); - client.run(); - client.close(); - assertNull(appender.getLastEvent()); - } + private MockAppender appender; + private Logger logger; + private LoggingEvent event; + private RemoteAppenderStreamClient client; + + @Before + public void setUp() throws Exception { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + appender = new MockAppender(); + appender.start(); + + logger = lc.getLogger(getClass()); + logger.addAppender(appender); + + event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); + + LoggingEventVO eventVO = LoggingEventVO.build(event); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos); + oos.writeObject(eventVO); + oos.close(); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + client = new RemoteAppenderStreamClient("some client ID", bis); + client.setLoggerContext(lc); + } + + @Test + public void testWithEnabledLevel() throws Exception { + logger.setLevel(Level.DEBUG); + client.run(); + client.close(); + + ILoggingEvent rcvdEvent = appender.getLastEvent(); + assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); + assertEquals(event.getLevel(), rcvdEvent.getLevel()); + assertEquals(event.getMessage(), rcvdEvent.getMessage()); + } + + @Test + public void testWithDisabledLevel() throws Exception { + logger.setLevel(Level.INFO); + client.run(); + client.close(); + assertNull(appender.getLastEvent()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiverTest.java index 25adb2538f4a38afa05520bd51af56f5c434c6d6..2fd60a0c8ac0e2491138987702093af49ddad718 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/SSLServerSocketReceiverTest.java @@ -30,28 +30,27 @@ import ch.qos.logback.core.net.mock.MockContext; */ public class SSLServerSocketReceiverTest { - private MockContext context = new MockContext(); - - private MockSSLConfiguration ssl = new MockSSLConfiguration(); - - private MockSSLParametersConfiguration parameters = - new MockSSLParametersConfiguration(); - - private SSLServerSocketReceiver receiver = new SSLServerSocketReceiver(); - - @Before - public void setUp() throws Exception { - receiver.setContext(context); - receiver.setSsl(ssl); - ssl.setParameters(parameters); - } - - @Test - public void testGetServerSocketFactory() throws Exception { - ServerSocketFactory socketFactory = receiver.getServerSocketFactory(); - assertNotNull(socketFactory); - assertTrue(ssl.isContextCreated()); - assertTrue(parameters.isContextInjected()); - } + private MockContext context = new MockContext(); + + private MockSSLConfiguration ssl = new MockSSLConfiguration(); + + private MockSSLParametersConfiguration parameters = new MockSSLParametersConfiguration(); + + private SSLServerSocketReceiver receiver = new SSLServerSocketReceiver(); + + @Before + public void setUp() throws Exception { + receiver.setContext(context); + receiver.setSsl(ssl); + ssl.setParameters(parameters); + } + + @Test + public void testGetServerSocketFactory() throws Exception { + ServerSocketFactory socketFactory = receiver.getServerSocketFactory(); + assertNotNull(socketFactory); + assertTrue(ssl.isContextCreated()); + assertTrue(parameters.isContextInjected()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverFunctionalTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverFunctionalTest.java index 1a7007cf27bb1e67a91598a91ca1a38acde5fc2a..f0864dc89375996612e7102d07d6417b291574d5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverFunctionalTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverFunctionalTest.java @@ -46,69 +46,66 @@ import ch.qos.logback.core.net.server.ServerSocketUtil; */ public class ServerSocketReceiverFunctionalTest { - private static final int EVENT_COUNT = 10; - private static final int SHUTDOWN_DELAY = 10000; - - private MockAppender appender; - private Logger logger; - private ServerSocket serverSocket; - private InstrumentedServerSocketReceiver receiver; - private LoggerContext lc; - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - - appender = new MockAppender(); - appender.start(); - - logger = lc.getLogger(getClass()); - logger.addAppender(appender); - - serverSocket = ServerSocketUtil.createServerSocket(); - - receiver = new InstrumentedServerSocketReceiver(serverSocket); - - receiver.setContext(lc); - receiver.start(); - } - - @After - public void tearDown() throws Exception { - receiver.stop(); - ExecutorService executor = lc.getExecutorService(); - executor.shutdownNow(); - executor.awaitTermination(SHUTDOWN_DELAY, TimeUnit.MILLISECONDS); - assertTrue(executor.isTerminated()); - } - - @Test - public void testLogEventFromClient() throws Exception { - ILoggingEvent event = new LoggingEvent(logger.getName(), logger, - Level.DEBUG, "test message", null, new Object[0]); - Socket socket = new Socket(InetAddress.getLocalHost(), - serverSocket.getLocalPort()); - - try { - LoggingEventVO eventVO = LoggingEventVO.build(event); - - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - for (int i = 0; i < EVENT_COUNT; i++) { - oos.writeObject(eventVO); - } - - oos.writeObject(eventVO); - oos.flush(); + private static final int EVENT_COUNT = 10; + private static final int SHUTDOWN_DELAY = 10000; + + private MockAppender appender; + private Logger logger; + private ServerSocket serverSocket; + private InstrumentedServerSocketReceiver receiver; + private LoggerContext lc; + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + + appender = new MockAppender(); + appender.start(); + + logger = lc.getLogger(getClass()); + logger.addAppender(appender); + + serverSocket = ServerSocketUtil.createServerSocket(); + + receiver = new InstrumentedServerSocketReceiver(serverSocket); + + receiver.setContext(lc); + receiver.start(); } - finally { - socket.close(); + + @After + public void tearDown() throws Exception { + receiver.stop(); + ExecutorService executor = lc.getExecutorService(); + executor.shutdownNow(); + executor.awaitTermination(SHUTDOWN_DELAY, TimeUnit.MILLISECONDS); + assertTrue(executor.isTerminated()); + } + + @Test + public void testLogEventFromClient() throws Exception { + ILoggingEvent event = new LoggingEvent(logger.getName(), logger, Level.DEBUG, "test message", null, new Object[0]); + Socket socket = new Socket(InetAddress.getLocalHost(), serverSocket.getLocalPort()); + + try { + LoggingEventVO eventVO = LoggingEventVO.build(event); + + ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); + for (int i = 0; i < EVENT_COUNT; i++) { + oos.writeObject(eventVO); + } + + oos.writeObject(eventVO); + oos.flush(); + } finally { + socket.close(); + } + + ILoggingEvent rcvdEvent = appender.awaitAppend(SHUTDOWN_DELAY); + assertNotNull(rcvdEvent); + assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); + assertEquals(event.getLevel(), rcvdEvent.getLevel()); + assertEquals(event.getMessage(), rcvdEvent.getMessage()); } - - ILoggingEvent rcvdEvent = appender.awaitAppend(SHUTDOWN_DELAY); - assertNotNull(rcvdEvent); - assertEquals(event.getLoggerName(), rcvdEvent.getLoggerName()); - assertEquals(event.getLevel(), rcvdEvent.getLevel()); - assertEquals(event.getMessage(), rcvdEvent.getMessage()); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverTest.java index d38c1c3c914efb5a61c278db2a7f98021403dde7..a9f10a3936b13484bdc84bc3ab339577edc33e2a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/server/ServerSocketReceiverTest.java @@ -40,66 +40,64 @@ import ch.qos.logback.core.status.Status; */ public class ServerSocketReceiverTest { - private MockContext context = new MockContext(); - - private MockServerRunner runner = - new MockServerRunner(); - - private MockServerListener listener = - new MockServerListener(); - - private ServerSocket serverSocket; - private InstrumentedServerSocketReceiver receiver; - - @Before - public void setUp() throws Exception { - serverSocket = ServerSocketUtil.createServerSocket(); - receiver = new InstrumentedServerSocketReceiver(serverSocket, listener, runner); - receiver.setContext(context); - } - - @After - public void tearDown() throws Exception { - serverSocket.close(); - } - - @Test - public void testStartStop() throws Exception { - receiver.start(); - assertTrue(runner.isContextInjected()); - assertTrue(runner.isRunning()); - assertSame(listener, receiver.getLastListener()); - - receiver.stop(); - assertFalse(runner.isRunning()); - } - - @Test - public void testStartWhenAlreadyStarted() throws Exception { - receiver.start(); - receiver.start(); - assertEquals(1, runner.getStartCount()); - } - - @Test - public void testStopThrowsException() throws Exception { - receiver.start(); - assertTrue(receiver.isStarted()); - IOException ex = new IOException("test exception"); - runner.setStopException(ex); - receiver.stop(); - - Status status = context.getLastStatus(); - assertNotNull(status); - assertTrue(status instanceof ErrorStatus); - assertTrue(status.getMessage().contains(ex.getMessage())); - assertSame(ex, status.getThrowable()); - } - - @Test - public void testStopWhenNotStarted() throws Exception { - receiver.stop(); - assertEquals(0, runner.getStartCount()); - } + private MockContext context = new MockContext(); + + private MockServerRunner runner = new MockServerRunner(); + + private MockServerListener listener = new MockServerListener(); + + private ServerSocket serverSocket; + private InstrumentedServerSocketReceiver receiver; + + @Before + public void setUp() throws Exception { + serverSocket = ServerSocketUtil.createServerSocket(); + receiver = new InstrumentedServerSocketReceiver(serverSocket, listener, runner); + receiver.setContext(context); + } + + @After + public void tearDown() throws Exception { + serverSocket.close(); + } + + @Test + public void testStartStop() throws Exception { + receiver.start(); + assertTrue(runner.isContextInjected()); + assertTrue(runner.isRunning()); + assertSame(listener, receiver.getLastListener()); + + receiver.stop(); + assertFalse(runner.isRunning()); + } + + @Test + public void testStartWhenAlreadyStarted() throws Exception { + receiver.start(); + receiver.start(); + assertEquals(1, runner.getStartCount()); + } + + @Test + public void testStopThrowsException() throws Exception { + receiver.start(); + assertTrue(receiver.isStarted()); + IOException ex = new IOException("test exception"); + runner.setStopException(ex); + receiver.stop(); + + Status status = context.getLastStatus(); + assertNotNull(status); + assertTrue(status instanceof ErrorStatus); + assertTrue(status.getMessage().contains(ex.getMessage())); + assertSame(ex, status.getThrowable()); + } + + @Test + public void testStopWhenNotStarted() throws Exception { + receiver.stop(); + assertEquals(0, runner.getStartCount()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/Builder.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/Builder.java index 4c70916ce80316d4ee8384e72d2e38ab363d9337..d2b02b2b797fa122c5f94afc686d165290d561b7 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/Builder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/Builder.java @@ -15,10 +15,10 @@ package ch.qos.logback.classic.net.testObjectBuilders; public interface Builder { - // 45 characters message - String MSG_PREFIX = "aaaaabbbbbcccccdddddaaaaabbbbbcccccdddddaaaa"; + // 45 characters message + String MSG_PREFIX = "aaaaabbbbbcccccdddddaaaaabbbbbcccccdddddaaaa"; - // final String MSG_PREFIX = "a"; + // final String MSG_PREFIX = "a"; - E build(int i); + E build(int i); } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventBuilderInContext.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventBuilderInContext.java index cab42c80849dfd3bebaa6f3a606a697d22e348e4..59faf055dfb3607056268c80b353c8d7908ae670 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventBuilderInContext.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventBuilderInContext.java @@ -21,21 +21,19 @@ import ch.qos.logback.classic.spi.LoggingEvent; public class LoggingEventBuilderInContext implements Builder { + LoggerContext loggerContext; + Logger logger; + String fqcn; - LoggerContext loggerContext; - Logger logger; - String fqcn; - public LoggingEventBuilderInContext(LoggerContext loggerContext, String loggerName, String fqcn) { - this.loggerContext = loggerContext; - logger = loggerContext.getLogger(loggerName); - this.fqcn = fqcn; - } + public LoggingEventBuilderInContext(LoggerContext loggerContext, String loggerName, String fqcn) { + this.loggerContext = loggerContext; + logger = loggerContext.getLogger(loggerName); + this.fqcn = fqcn; + } - - public ILoggingEvent build(int i) { - LoggingEvent le = new LoggingEvent(fqcn, logger, Level.DEBUG, "hello " + i, - null, null); - return le; - } + public ILoggingEvent build(int i) { + LoggingEvent le = new LoggingEvent(fqcn, logger, Level.DEBUG, "hello " + i, null, null); + return le; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventWithParametersBuilder.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventWithParametersBuilder.java index 02295ecc67f11e78c6f470e7e5b6f8ebbe13842c..8e271334862547d334d3f3efee89cb1ccfaaf68a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventWithParametersBuilder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/LoggingEventWithParametersBuilder.java @@ -20,30 +20,30 @@ import ch.qos.logback.classic.spi.LoggingEvent; public class LoggingEventWithParametersBuilder implements Builder { - final String MSG = "aaaaabbbbbcccc {} cdddddaaaaabbbbbcccccdddddaaaa {}"; + final String MSG = "aaaaabbbbbcccc {} cdddddaaaaabbbbbcccccdddddaaaa {}"; - LoggerContext loggerContext = new LoggerContext(); - private Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + LoggerContext loggerContext = new LoggerContext(); + private Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - public LoggingEvent build(int i) { + public LoggingEvent build(int i) { - LoggingEvent le = new LoggingEvent(); - le.setTimeStamp(System.currentTimeMillis()); + LoggingEvent le = new LoggingEvent(); + le.setTimeStamp(System.currentTimeMillis()); - Object[] aa = new Object[] { i, "HELLO WORLD [========== ]" + i }; + Object[] aa = new Object[] { i, "HELLO WORLD [========== ]" + i }; - le.setArgumentArray(aa); - String msg = MSG + i; - le.setMessage(msg); + le.setArgumentArray(aa); + String msg = MSG + i; + le.setMessage(msg); - // compute formatted message - // this forces le.formmatedMessage to be set (this is the whole point of the - // exercise) - le.getFormattedMessage(); - le.setLevel(Level.DEBUG); - le.setLoggerName(logger.getName()); - le.setLoggerContextRemoteView(loggerContext.getLoggerContextRemoteView()); - le.setThreadName("threadName"); - return le; - } + // compute formatted message + // this forces le.formmatedMessage to be set (this is the whole point of the + // exercise) + le.getFormattedMessage(); + le.setLevel(Level.DEBUG); + le.setLoggerName(logger.getName()); + le.setLoggerContextRemoteView(loggerContext.getLoggerContextRemoteView()); + le.setThreadName("threadName"); + return le; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/MinimalSerBuilder.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/MinimalSerBuilder.java index 628575ce9fa011f50f60d77edb709e32a1abb031..acd9e941f5bf1bd14aad90eaf36a9854f70a2a1d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/MinimalSerBuilder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/MinimalSerBuilder.java @@ -15,22 +15,21 @@ package ch.qos.logback.classic.net.testObjectBuilders; import java.io.Serializable; +public class MinimalSerBuilder implements Builder { -public class MinimalSerBuilder implements Builder{ - - public Object build(int i) { - return new MinimalSer(i); - } + public Object build(int i) { + return new MinimalSer(i); + } } class MinimalSer implements Serializable { - private static final long serialVersionUID = 2807646397580899815L; + private static final long serialVersionUID = 2807646397580899815L; - String message; + String message; - public MinimalSer(int i) { - message = Builder.MSG_PREFIX; - } + public MinimalSer(int i) { + message = Builder.MSG_PREFIX; + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventBuilder.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventBuilder.java index 51fd9892a6dfeb64e61914a58911f9d3b1ed289f..c054a1dad840dd2e56b9cb3fb28c58ded01b7c3c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventBuilder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventBuilder.java @@ -20,18 +20,18 @@ import ch.qos.logback.classic.spi.LoggingEvent; public class TrivialLoggingEventBuilder implements Builder { - LoggerContext loggerContext = new LoggerContext(); + LoggerContext loggerContext = new LoggerContext(); - private Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + private Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - public Object build(int i) { - LoggingEvent le = new LoggingEvent(); - le.setTimeStamp(System.currentTimeMillis()); - le.setLevel(Level.DEBUG); - le.setLoggerName(logger.getName()); - le.setLoggerContextRemoteView(loggerContext.getLoggerContextRemoteView()); - le.setMessage(MSG_PREFIX); - le.setThreadName("threadName"); - return le; - } + public Object build(int i) { + LoggingEvent le = new LoggingEvent(); + le.setTimeStamp(System.currentTimeMillis()); + le.setLevel(Level.DEBUG); + le.setLoggerName(logger.getName()); + le.setLoggerContextRemoteView(loggerContext.getLoggerContextRemoteView()); + le.setMessage(MSG_PREFIX); + le.setThreadName("threadName"); + return le; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventVOBuilder.java b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventVOBuilder.java index a3614a58bbdc0f6d26b332fdb947347f4a609704..9f94bfdc5a6df06af20c79a73c1b5ee6628a1230 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventVOBuilder.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/net/testObjectBuilders/TrivialLoggingEventVOBuilder.java @@ -21,11 +21,11 @@ import ch.qos.logback.classic.spi.LoggingEventVO; */ public class TrivialLoggingEventVOBuilder implements Builder { - public Object build(int i) { - TrivialLoggingEventBuilder loggingEventBuilder = new TrivialLoggingEventBuilder(); - LoggingEvent event = (LoggingEvent) loggingEventBuilder.build(i); + public Object build(int i) { + TrivialLoggingEventBuilder loggingEventBuilder = new TrivialLoggingEventBuilder(); + LoggingEvent event = (LoggingEvent) loggingEventBuilder.build(i); - return LoggingEventVO.build(event); - } + return LoggingEventVO.build(event); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ConverterTest.java index 0e7afaf10bb85914ebda2c7854045be308917490..027dbcba54ac8248fb312101cb8ac4c691a5b3f6 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ConverterTest.java @@ -38,364 +38,361 @@ import static org.hamcrest.CoreMatchers.*; public class ConverterTest { - LoggerContext lc = new LoggerContext(); - Logger logger = lc.getLogger(ConverterTest.class); - LoggingEvent le; - List optionList = new ArrayList(); - - // The LoggingEvent is massaged with an FCQN of FormattingConverter. This - // forces the returned caller information to match the caller stack for this - // this particular test. - LoggingEvent makeLoggingEvent(Exception ex) { - return new LoggingEvent( - ch.qos.logback.core.pattern.FormattingConverter.class.getName(), - logger, Level.INFO, "Some message", ex, null); - } - - Exception getException(String msg, Exception cause) { - return new Exception(msg, cause); - } - - @Before - public void setUp() throws Exception { - Exception rootEx = getException("Innermost", null); - Exception nestedEx = getException("Nested", rootEx); - - Exception ex = new Exception("Bogus exception", nestedEx); - - le = makeLoggingEvent(ex); - } - - @Test - public void testLineOfCaller() { - { - DynamicConverter converter = new LineOfCallerConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - // the number below should be the line number of the previous line - assertEquals("74", buf.toString()); + LoggerContext lc = new LoggerContext(); + Logger logger = lc.getLogger(ConverterTest.class); + LoggingEvent le; + List optionList = new ArrayList(); + + // The LoggingEvent is massaged with an FCQN of FormattingConverter. This + // forces the returned caller information to match the caller stack for this + // this particular test. + LoggingEvent makeLoggingEvent(Exception ex) { + return new LoggingEvent(ch.qos.logback.core.pattern.FormattingConverter.class.getName(), logger, Level.INFO, "Some message", ex, null); } - } - - @Test - public void testLevel() { - { - DynamicConverter converter = new LevelConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("INFO", buf.toString()); + + Exception getException(String msg, Exception cause) { + return new Exception(msg, cause); + } + + @Before + public void setUp() throws Exception { + Exception rootEx = getException("Innermost", null); + Exception nestedEx = getException("Nested", rootEx); + + Exception ex = new Exception("Bogus exception", nestedEx); + + le = makeLoggingEvent(ex); + } + + @Test + public void testLineOfCaller() { + { + DynamicConverter converter = new LineOfCallerConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + // the number below should be the line number of the previous line + assertEquals("72", buf.toString()); + } + } + + @Test + public void testLevel() { + { + DynamicConverter converter = new LevelConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("INFO", buf.toString()); + } + { + DynamicConverter converter = new LevelConverter(); + converter.setFormattingInfo(new FormatInfo(1, 1, true, false)); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("I", buf.toString()); + } } - { - DynamicConverter converter = new LevelConverter(); - converter.setFormattingInfo(new FormatInfo(1, 1, true, false)); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("I", buf.toString()); + + @Test + public void testThread() { + DynamicConverter converter = new ThreadConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + System.out.println(buf.toString()); + String regex = ClassicTestConstants.NAKED_MAIN_REGEX; + assertTrue(buf.toString().matches(regex)); + } + + @Test + public void testMessage() { + DynamicConverter converter = new MessageConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("Some message", buf.toString()); } - } - - @Test - public void testThread() { - DynamicConverter converter = new ThreadConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - System.out.println(buf.toString()); - String regex = ClassicTestConstants.NAKED_MAIN_REGEX; - assertTrue(buf.toString().matches(regex)); - } - - @Test - public void testMessage() { - DynamicConverter converter = new MessageConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("Some message", buf.toString()); - } - - @Test - public void testLineSeparator() { - DynamicConverter converter = new LineSeparatorConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals(CoreConstants.LINE_SEPARATOR, buf.toString()); - } - - @Test - public void testException() { - { - DynamicConverter converter = new ThrowableProxyConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); + + @Test + public void testLineSeparator() { + DynamicConverter converter = new LineSeparatorConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals(CoreConstants.LINE_SEPARATOR, buf.toString()); } - { - DynamicConverter converter = new ThrowableProxyConverter(); - this.optionList.add("3"); - converter.setOptionList(this.optionList); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); + @Test + public void testException() { + { + DynamicConverter converter = new ThrowableProxyConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + } + + { + DynamicConverter converter = new ThrowableProxyConverter(); + this.optionList.add("3"); + converter.setOptionList(this.optionList); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + } } - } - - @Test - public void testLogger() { - { - ClassicConverter converter = new LoggerConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals(this.getClass().getName(), buf.toString()); + + @Test + public void testLogger() { + { + ClassicConverter converter = new LoggerConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals(this.getClass().getName(), buf.toString()); + } + + { + ClassicConverter converter = new LoggerConverter(); + this.optionList.add("20"); + converter.setOptionList(this.optionList); + converter.start(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("c.q.l.c.p.ConverterTest", buf.toString()); + } + + { + DynamicConverter converter = new LoggerConverter(); + this.optionList.clear(); + this.optionList.add("0"); + converter.setOptionList(this.optionList); + converter.start(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("ConverterTest", buf.toString()); + } } - { - ClassicConverter converter = new LoggerConverter(); - this.optionList.add("20"); - converter.setOptionList(this.optionList); - converter.start(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("c.q.l.c.p.ConverterTest", buf.toString()); + @Test + public void testVeryLongLoggerName() { + ClassicConverter converter = new LoggerConverter(); + this.optionList.add("5"); + converter.setOptionList(this.optionList); + converter.start(); + StringBuilder buf = new StringBuilder(); + + char c = 'a'; + int extraParts = 3; + int totalParts = ClassicConstants.MAX_DOTS + extraParts; + StringBuilder loggerNameBuf = new StringBuilder(); + StringBuilder witness = new StringBuilder(); + + for (int i = 0; i < totalParts; i++) { + loggerNameBuf.append(c).append(c).append(c); + if (i < ClassicConstants.MAX_DOTS) { + witness.append(c); + } else { + witness.append(c).append(c).append(c); + } + loggerNameBuf.append('.'); + witness.append('.'); + } + loggerNameBuf.append("zzzzzz"); + witness.append("zzzzzz"); + + le.setLoggerName(loggerNameBuf.toString()); + converter.write(buf, le); + assertEquals(witness.toString(), buf.toString()); } - { - DynamicConverter converter = new LoggerConverter(); - this.optionList.clear(); - this.optionList.add("0"); - converter.setOptionList(this.optionList); - converter.start(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("ConverterTest", buf.toString()); + @Test + public void testClass() { + DynamicConverter converter = new ClassOfCallerConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals(this.getClass().getName(), buf.toString()); } - } - - @Test - public void testVeryLongLoggerName() { - ClassicConverter converter = new LoggerConverter(); - this.optionList.add("5"); - converter.setOptionList(this.optionList); - converter.start(); - StringBuilder buf = new StringBuilder(); - - char c = 'a'; - int extraParts = 3; - int totalParts = ClassicConstants.MAX_DOTS + extraParts; - StringBuilder loggerNameBuf = new StringBuilder(); - StringBuilder witness = new StringBuilder(); - - for(int i = 0; i < totalParts ; i++) { - loggerNameBuf.append(c).append(c).append(c); - if(i < ClassicConstants.MAX_DOTS) { - witness.append(c); - } else { - witness.append(c).append(c).append(c); - } - loggerNameBuf.append('.'); - witness.append('.'); + + @Test + public void testMethodOfCaller() { + DynamicConverter converter = new MethodOfCallerConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("testMethodOfCaller", buf.toString()); } - loggerNameBuf.append("zzzzzz"); - witness.append("zzzzzz"); - - le.setLoggerName(loggerNameBuf.toString()); - converter.write(buf, le); - assertEquals(witness.toString(), buf.toString()); - } - - @Test - public void testClass() { - DynamicConverter converter = new ClassOfCallerConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals(this.getClass().getName(), buf.toString()); - } - - @Test - public void testMethodOfCaller() { - DynamicConverter converter = new MethodOfCallerConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("testMethodOfCaller", buf.toString()); - } - - @Test - public void testFileOfCaller() { - DynamicConverter converter = new FileOfCallerConverter(); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertEquals("ConverterTest.java", buf.toString()); - } - - @Test - public void testCallerData() { - { - DynamicConverter converter = new CallerDataConverter(); - converter.start(); - - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - if (buf.length() < 10) { - fail("buf is too short"); - } + + @Test + public void testFileOfCaller() { + DynamicConverter converter = new FileOfCallerConverter(); + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertEquals("ConverterTest.java", buf.toString()); } - { - DynamicConverter converter = new CallerDataConverter(); - this.optionList.add("2"); - this.optionList.add("XXX"); - converter.setOptionList(this.optionList); - converter.start(); - - StringBuilder buf = new StringBuilder(); - LoggingEvent event = makeLoggingEvent(null); - event.setMarker(MarkerFactory.getMarker("XXX")); - converter.write(buf, event); - if (buf.length() < 10) { - fail("buf is too short"); - } + @Test + public void testCallerData() { + { + DynamicConverter converter = new CallerDataConverter(); + converter.start(); + + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + if (buf.length() < 10) { + fail("buf is too short"); + } + } + + { + DynamicConverter converter = new CallerDataConverter(); + this.optionList.add("2"); + this.optionList.add("XXX"); + converter.setOptionList(this.optionList); + converter.start(); + + StringBuilder buf = new StringBuilder(); + LoggingEvent event = makeLoggingEvent(null); + event.setMarker(MarkerFactory.getMarker("XXX")); + converter.write(buf, event); + if (buf.length() < 10) { + fail("buf is too short"); + } + } + + { + DynamicConverter converter = new CallerDataConverter(); + this.optionList.clear(); + this.optionList.add("2"); + this.optionList.add("XXX"); + this.optionList.add("*"); + converter.setOptionList(this.optionList); + converter.start(); + + StringBuilder buf = new StringBuilder(); + LoggingEvent event = makeLoggingEvent(null); + event.setMarker(MarkerFactory.getMarker("YYY")); + converter.write(buf, event); + if (buf.length() < 10) { + fail("buf is too short"); + } + } + { + DynamicConverter converter = new CallerDataConverter(); + this.optionList.clear(); + this.optionList.add("2"); + this.optionList.add("XXX"); + this.optionList.add("+"); + converter.setOptionList(this.optionList); + converter.start(); + + StringBuilder buf = new StringBuilder(); + LoggingEvent event = makeLoggingEvent(null); + event.setMarker(MarkerFactory.getMarker("YYY")); + converter.write(buf, event); + if (buf.length() < 10) { + fail("buf is too short"); + } + } + + { + DynamicConverter converter = new CallerDataConverter(); + this.optionList.clear(); + this.optionList.add("2"); + this.optionList.add("XXX"); + this.optionList.add("*"); + converter.setOptionList(this.optionList); + converter.start(); + + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + if (buf.length() < 10) { + fail("buf is too short"); + } + // System.out.println(buf); + } + + { + DynamicConverter converter = new CallerDataConverter(); + this.optionList.clear(); + this.optionList.add("4..5"); + converter.setOptionList(this.optionList); + converter.start(); + + StringBuilder buf = new StringBuilder(); + converter.write(buf, le); + assertTrue("buf is too short", buf.length() >= 10); + + String expected = "Caller+4\t at java.lang.reflect.Method.invoke("; + String actual = buf.toString().substring(0, expected.length()); + assertThat(actual, is(expected)); + } } - { - DynamicConverter converter = new CallerDataConverter(); - this.optionList.clear(); - this.optionList.add("2"); - this.optionList.add("XXX"); - this.optionList.add("*"); - converter.setOptionList(this.optionList); - converter.start(); - - StringBuilder buf = new StringBuilder(); - LoggingEvent event = makeLoggingEvent(null); - event.setMarker(MarkerFactory.getMarker("YYY")); - converter.write(buf, event); - if (buf.length() < 10) { - fail("buf is too short"); - } + @Test + public void testRelativeTime() throws Exception { + DynamicConverter converter = new RelativeTimeConverter(); + StringBuilder buf0 = new StringBuilder(); + StringBuilder buf1 = new StringBuilder(); + ILoggingEvent e0 = makeLoggingEvent(null); + ILoggingEvent e1 = makeLoggingEvent(null); + converter.write(buf0, e0); + converter.write(buf1, e1); + assertEquals(buf0.toString(), buf1.toString()); } - { - DynamicConverter converter = new CallerDataConverter(); - this.optionList.clear(); - this.optionList.add("2"); - this.optionList.add("XXX"); - this.optionList.add("+"); - converter.setOptionList(this.optionList); - converter.start(); - - StringBuilder buf = new StringBuilder(); - LoggingEvent event = makeLoggingEvent(null); - event.setMarker(MarkerFactory.getMarker("YYY")); - converter.write(buf, event); - if (buf.length() < 10) { - fail("buf is too short"); - } + + @Test + public void testSyslogStart() throws Exception { + DynamicConverter converter = new SyslogStartConverter(); + this.optionList.clear(); + this.optionList.add("MAIL"); + converter.setOptionList(this.optionList); + converter.start(); + + ILoggingEvent event = makeLoggingEvent(null); + + StringBuilder buf = new StringBuilder(); + converter.write(buf, event); + + String expected = "<" + (SyslogConstants.LOG_MAIL + SyslogConstants.INFO_SEVERITY) + ">"; + assertTrue(buf.toString().startsWith(expected)); } - { - DynamicConverter converter = new CallerDataConverter(); - this.optionList.clear(); - this.optionList.add("2"); - this.optionList.add("XXX"); - this.optionList.add("*"); - converter.setOptionList(this.optionList); - converter.start(); - - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - if (buf.length() < 10) { - fail("buf is too short"); - } - // System.out.println(buf); + @Test + public void testMDCConverter() throws Exception { + MDC.clear(); + MDC.put("someKey", "someValue"); + MDCConverter converter = new MDCConverter(); + this.optionList.clear(); + this.optionList.add("someKey"); + converter.setOptionList(optionList); + converter.start(); + + ILoggingEvent event = makeLoggingEvent(null); + + String result = converter.convert(event); + assertEquals("someValue", result); } - { - DynamicConverter converter = new CallerDataConverter(); - this.optionList.clear(); - this.optionList.add("4..5"); - converter.setOptionList(this.optionList); - converter.start(); + @Test + public void contextNameConverter() { + ClassicConverter converter = new ContextNameConverter(); + // see http://jira.qos.ch/browse/LBCLASSIC-149 + LoggerContext lcOther = new LoggerContext(); + lcOther.setName("another"); + converter.setContext(lcOther); + + lc.setName("aValue"); + ILoggingEvent event = makeLoggingEvent(null); - StringBuilder buf = new StringBuilder(); - converter.write(buf, le); - assertTrue("buf is too short", buf.length() >= 10); + String result = converter.convert(event); + assertEquals("aValue", result); + } - String expected = "Caller+4\t at java.lang.reflect.Method.invoke("; - String actual = buf.toString().substring(0, expected.length()); - assertThat(actual, is(expected)); + @Test + public void contextProperty() { + PropertyConverter converter = new PropertyConverter(); + converter.setContext(lc); + List ol = new ArrayList(); + ol.add("k"); + converter.setOptionList(ol); + converter.start(); + lc.setName("aValue"); + lc.putProperty("k", "v"); + ILoggingEvent event = makeLoggingEvent(null); + + String result = converter.convert(event); + assertEquals("v", result); } - } - - @Test - public void testRelativeTime() throws Exception { - DynamicConverter converter = new RelativeTimeConverter(); - StringBuilder buf0 = new StringBuilder(); - StringBuilder buf1 = new StringBuilder(); - ILoggingEvent e0 = makeLoggingEvent(null); - ILoggingEvent e1 = makeLoggingEvent(null); - converter.write(buf0, e0); - converter.write(buf1, e1); - assertEquals(buf0.toString(), buf1.toString()); - } - - @Test - public void testSyslogStart() throws Exception { - DynamicConverter converter = new SyslogStartConverter(); - this.optionList.clear(); - this.optionList.add("MAIL"); - converter.setOptionList(this.optionList); - converter.start(); - - ILoggingEvent event = makeLoggingEvent(null); - - StringBuilder buf = new StringBuilder(); - converter.write(buf, event); - - String expected = "<" - + (SyslogConstants.LOG_MAIL + SyslogConstants.INFO_SEVERITY) + ">"; - assertTrue(buf.toString().startsWith(expected)); - } - - @Test - public void testMDCConverter() throws Exception { - MDC.clear(); - MDC.put("someKey", "someValue"); - MDCConverter converter = new MDCConverter(); - this.optionList.clear(); - this.optionList.add("someKey"); - converter.setOptionList(optionList); - converter.start(); - - ILoggingEvent event = makeLoggingEvent(null); - - String result = converter.convert(event); - assertEquals("someValue", result); - } - - @Test - public void contextNameConverter() { - ClassicConverter converter = new ContextNameConverter(); - // see http://jira.qos.ch/browse/LBCLASSIC-149 - LoggerContext lcOther = new LoggerContext(); - lcOther.setName("another"); - converter.setContext(lcOther); - - lc.setName("aValue"); - ILoggingEvent event = makeLoggingEvent(null); - - String result = converter.convert(event); - assertEquals("aValue", result); - } - - @Test - public void contextProperty() { - PropertyConverter converter = new PropertyConverter(); - converter.setContext(lc); - List ol = new ArrayList(); - ol.add("k"); - converter.setOptionList(ol); - converter.start(); - lc.setName("aValue"); - lc.putProperty("k", "v"); - ILoggingEvent event = makeLoggingEvent(null); - - String result = converter.convert(event); - assertEquals("v", result); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverterTest.java index 0a370f20414dd93dcc98852edd1cd1ef603cdd8c..3dedc7e5c3eaedfb9ca5f675d2112c0d6e102238 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ExtendedThrowableProxyConverterTest.java @@ -34,74 +34,72 @@ import ch.qos.logback.classic.spi.LoggingEvent; public class ExtendedThrowableProxyConverterTest { - LoggerContext lc = new LoggerContext(); - ExtendedThrowableProxyConverter etpc = new ExtendedThrowableProxyConverter(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - - @Before - public void setUp() throws Exception { - lc.setPackagingDataEnabled(true); - etpc.setContext(lc); - etpc.start(); - } - - @After - public void tearDown() throws Exception { - } - - private ILoggingEvent createLoggingEvent(Throwable t) { - return new LoggingEvent(this.getClass().getName(), lc - .getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, - null); - } - - @Test - public void integration() { - PatternLayout pl = new PatternLayout(); - pl.setContext(lc); - pl.setPattern("%m%n%xEx"); - pl.start(); - ILoggingEvent e = createLoggingEvent(new Exception("x")); - String res = pl.doLayout(e); - - // make sure that at least some package data was output - Pattern p = Pattern.compile("\\s*at .*?\\[.*?\\]"); - Matcher m = p.matcher(res); - int i = 0; - while(m.find()) { - i++; + LoggerContext lc = new LoggerContext(); + ExtendedThrowableProxyConverter etpc = new ExtendedThrowableProxyConverter(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + + @Before + public void setUp() throws Exception { + lc.setPackagingDataEnabled(true); + etpc.setContext(lc); + etpc.start(); } - assertThat(i).isGreaterThan(5); - } - - @Test - public void smoke() { - Exception t = new Exception("smoke"); - verify(t); - } - - @Test - public void nested() { - Throwable t = makeNestedException(1); - verify(t); - } - - void verify(Throwable t) { - t.printStackTrace(pw); - - ILoggingEvent le = createLoggingEvent(t); - String result = etpc.convert(le); - result = result.replace("common frames omitted", "more"); - result = result.replaceAll(" ~?\\[.*\\]", ""); - assertEquals(sw.toString(), result); - } - - Throwable makeNestedException(int level) { - if (level == 0) { - return new Exception("nesting level=" + level); + + @After + public void tearDown() throws Exception { + } + + private ILoggingEvent createLoggingEvent(Throwable t) { + return new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, null); + } + + @Test + public void integration() { + PatternLayout pl = new PatternLayout(); + pl.setContext(lc); + pl.setPattern("%m%n%xEx"); + pl.start(); + ILoggingEvent e = createLoggingEvent(new Exception("x")); + String res = pl.doLayout(e); + + // make sure that at least some package data was output + Pattern p = Pattern.compile("\\s*at .*?\\[.*?\\]"); + Matcher m = p.matcher(res); + int i = 0; + while (m.find()) { + i++; + } + assertThat(i).isGreaterThan(5); + } + + @Test + public void smoke() { + Exception t = new Exception("smoke"); + verify(t); + } + + @Test + public void nested() { + Throwable t = makeNestedException(1); + verify(t); + } + + void verify(Throwable t) { + t.printStackTrace(pw); + + ILoggingEvent le = createLoggingEvent(t); + String result = etpc.convert(le); + result = result.replace("common frames omitted", "more"); + result = result.replaceAll(" ~?\\[.*\\]", ""); + assertEquals(sw.toString(), result); + } + + Throwable makeNestedException(int level) { + if (level == 0) { + return new Exception("nesting level=" + level); + } + Throwable cause = makeNestedException(level - 1); + return new Exception("nesting level =" + level, cause); } - Throwable cause = makeNestedException(level - 1); - return new Exception("nesting level =" + level, cause); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MDCConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MDCConverterTest.java index 1b888d2be3f77e07d5d59e368981447447eae84a..3ce1efc83ef679a6c2aff45a6dd23ce8f7c772ab 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MDCConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MDCConverterTest.java @@ -31,50 +31,48 @@ import ch.qos.logback.core.util.SystemInfo; public class MDCConverterTest { - LoggerContext lc; - MDCConverter converter; - int diff = RandomUtil.getPositiveInt(); + LoggerContext lc; + MDCConverter converter; + int diff = RandomUtil.getPositiveInt(); - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - converter = new MDCConverter(); - converter.start(); - MDC.clear(); - } + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + converter = new MDCConverter(); + converter.start(); + MDC.clear(); + } - @After - public void tearDown() throws Exception { - lc = null; - converter.stop(); - converter = null; - MDC.clear(); - } + @After + public void tearDown() throws Exception { + lc = null; + converter.stop(); + converter = null; + MDC.clear(); + } - @Test - public void testConvertWithOneEntry() { - String k = "MDCConverterTest_k"+diff; - String v = "MDCConverterTest_v"+diff; + @Test + public void testConvertWithOneEntry() { + String k = "MDCConverterTest_k" + diff; + String v = "MDCConverterTest_v" + diff; - MDC.put(k, v); - ILoggingEvent le = createLoggingEvent(); - String result = converter.convert(le); - assertEquals(k+"="+v, result); - } + MDC.put(k, v); + ILoggingEvent le = createLoggingEvent(); + String result = converter.convert(le); + assertEquals(k + "=" + v, result); + } - @Test - public void testConvertWithMultipleEntries() { - MDC.put("testKey", "testValue"); - MDC.put("testKey2", "testValue2"); - ILoggingEvent le = createLoggingEvent(); - String result = converter.convert(le); - boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?"); - assertTrue(result + " is not conform", isConform); - } + @Test + public void testConvertWithMultipleEntries() { + MDC.put("testKey", "testValue"); + MDC.put("testKey2", "testValue2"); + ILoggingEvent le = createLoggingEvent(); + String result = converter.convert(le); + boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?"); + assertTrue(result + " is not conform", isConform); + } - private ILoggingEvent createLoggingEvent() { - return new LoggingEvent(this.getClass().getName(), lc - .getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, - null); - } + private ILoggingEvent createLoggingEvent() { + return new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, null); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MarkerConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MarkerConverterTest.java index 146bdd3f8d9b6216d24ab3615e0d57def5056fc4..3b8ff80b30f4390a1064cfcea2ec4644dac327b5 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MarkerConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/MarkerConverterTest.java @@ -29,66 +29,65 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.LoggingEvent; public class MarkerConverterTest { - - LoggerContext lc; - MarkerConverter converter; - // use a different facotry for each test so that they are independent - IMarkerFactory markerFactory = new BasicMarkerFactory(); - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - converter = new MarkerConverter(); - converter.start(); - } - - @After - public void tearDown() throws Exception { - lc = null; - converter.stop(); - converter = null; - } - - @Test - public void testWithNullMarker() { - String result = converter.convert(createLoggingEvent(null)); - assertEquals("", result); - } - - @Test - public void testWithMarker() { - String name = "test"; - Marker marker = markerFactory.getMarker(name); - String result = converter.convert(createLoggingEvent(marker)); - assertEquals(name, result); - } - - @Test - public void testWithOneChildMarker() { - Marker marker = markerFactory.getMarker("test"); - marker.add(markerFactory.getMarker("child")); - - String result = converter.convert(createLoggingEvent(marker)); - - assertEquals("test [ child ]", result); - } - - @Test - public void testWithSeveralChildMarker() { - Marker marker = markerFactory.getMarker("testParent"); - marker.add(markerFactory.getMarker("child1")); - marker.add(markerFactory.getMarker("child2")); - marker.add(markerFactory.getMarker("child3")); - - String result = converter.convert(createLoggingEvent(marker)); - - assertEquals("testParent [ child1, child2, child3 ]", result); - } - - private ILoggingEvent createLoggingEvent(Marker marker) { - LoggingEvent le = new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), - Level.DEBUG, "test message", null, null); - le.setMarker(marker); - return le; - } + + LoggerContext lc; + MarkerConverter converter; + // use a different facotry for each test so that they are independent + IMarkerFactory markerFactory = new BasicMarkerFactory(); + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + converter = new MarkerConverter(); + converter.start(); + } + + @After + public void tearDown() throws Exception { + lc = null; + converter.stop(); + converter = null; + } + + @Test + public void testWithNullMarker() { + String result = converter.convert(createLoggingEvent(null)); + assertEquals("", result); + } + + @Test + public void testWithMarker() { + String name = "test"; + Marker marker = markerFactory.getMarker(name); + String result = converter.convert(createLoggingEvent(marker)); + assertEquals(name, result); + } + + @Test + public void testWithOneChildMarker() { + Marker marker = markerFactory.getMarker("test"); + marker.add(markerFactory.getMarker("child")); + + String result = converter.convert(createLoggingEvent(marker)); + + assertEquals("test [ child ]", result); + } + + @Test + public void testWithSeveralChildMarker() { + Marker marker = markerFactory.getMarker("testParent"); + marker.add(markerFactory.getMarker("child1")); + marker.add(markerFactory.getMarker("child2")); + marker.add(markerFactory.getMarker("child3")); + + String result = converter.convert(createLoggingEvent(marker)); + + assertEquals("testParent [ child1, child2, child3 ]", result); + } + + private ILoggingEvent createLoggingEvent(Marker marker) { + LoggingEvent le = new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, null); + le.setMarker(marker); + return le; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/PackageTest.java index f83cbb7cfeaa0ccf2cdbc82a4bd77b0d583a85af..90547f2b9182240cb0484977e9e2988dc96c1d60 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/PackageTest.java @@ -18,11 +18,8 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ConverterTest.class, - TargetLengthBasedClassNameAbbreviatorTest.class, MDCConverterTest.class, - MarkerConverterTest.class, ExtendedThrowableProxyConverterTest.class, - ThrowableProxyConverterTest.class, - RootCauseFirstThrowableProxyConverterTest.class}) +@SuiteClasses({ ConverterTest.class, TargetLengthBasedClassNameAbbreviatorTest.class, MDCConverterTest.class, MarkerConverterTest.class, + ExtendedThrowableProxyConverterTest.class, ThrowableProxyConverterTest.class, RootCauseFirstThrowableProxyConverterTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverterTest.java index 9b4f952df3dc37445297303ff00769e295be6cc6..f0d0e3fc1bc4f9196b4e81897f88f695c3073dca 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/RootCauseFirstThrowableProxyConverterTest.java @@ -38,81 +38,75 @@ import static org.fest.assertions.Assertions.assertThat; */ public class RootCauseFirstThrowableProxyConverterTest { - private LoggerContext context = new LoggerContext(); - private ThrowableProxyConverter converter = new RootCauseFirstThrowableProxyConverter(); - private StringWriter stringWriter = new StringWriter(); - private PrintWriter printWriter = new PrintWriter(stringWriter); - - @Before - public void setUp() throws Exception { - converter.setContext(context); - converter.start(); - } - - private ILoggingEvent createLoggingEvent(Throwable t) { - return new LoggingEvent(this.getClass().getName(), context - .getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, - null); - } - - @Test - public void integration() { - //given - context.setPackagingDataEnabled(true); - PatternLayout pl = new PatternLayout(); - pl.setContext(context); - pl.setPattern("%m%rEx%n"); - pl.start(); - - //when - ILoggingEvent e = createLoggingEvent(new Exception("x")); - String result = pl.doLayout(e); - - //then - // make sure that at least some package data was output - Pattern p = Pattern.compile("\\s*at .*?\\[.*?\\]"); - Matcher m = p.matcher(result); - int i = 0; - while(m.find()) { - i++; + private LoggerContext context = new LoggerContext(); + private ThrowableProxyConverter converter = new RootCauseFirstThrowableProxyConverter(); + private StringWriter stringWriter = new StringWriter(); + private PrintWriter printWriter = new PrintWriter(stringWriter); + + @Before + public void setUp() throws Exception { + converter.setContext(context); + converter.start(); + } + + private ILoggingEvent createLoggingEvent(Throwable t) { + return new LoggingEvent(this.getClass().getName(), context.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, null); + } + + @Test + public void integration() { + // given + context.setPackagingDataEnabled(true); + PatternLayout pl = new PatternLayout(); + pl.setContext(context); + pl.setPattern("%m%rEx%n"); + pl.start(); + + // when + ILoggingEvent e = createLoggingEvent(new Exception("x")); + String result = pl.doLayout(e); + + // then + // make sure that at least some package data was output + Pattern p = Pattern.compile("\\s*at .*?\\[.*?\\]"); + Matcher m = p.matcher(result); + int i = 0; + while (m.find()) { + i++; + } + assertThat(i).isGreaterThan(5); + } + + @Test + public void smoke() { + // given + Exception exception = new Exception("smoke"); + exception.printStackTrace(printWriter); + + // when + ILoggingEvent le = createLoggingEvent(exception); + String result = converter.convert(le); + + // then + result = result.replace("common frames omitted", "more"); + result = result.replaceAll(" ~?\\[.*\\]", ""); + assertThat(result).isEqualTo(stringWriter.toString()); + } + + @Test + public void nested() { + // given + Throwable nestedException = makeNestedException(2); + nestedException.printStackTrace(printWriter); + + // when + ILoggingEvent le = createLoggingEvent(nestedException); + String result = converter.convert(le); + + // then + assertThat(result).startsWith("java.lang.Exception: nesting level=0"); + assertThat(positionOf("nesting level=0").in(result)).isLessThan(positionOf("nesting level =1").in(result)); + assertThat(positionOf("nesting level =1").in(result)).isLessThan(positionOf("nesting level =2").in(result)); } - assertThat(i).isGreaterThan(5); - } - - @Test - public void smoke() { - //given - Exception exception = new Exception("smoke"); - exception.printStackTrace(printWriter); - - //when - ILoggingEvent le = createLoggingEvent(exception); - String result = converter.convert(le); - - //then - result = result.replace("common frames omitted", "more"); - result = result.replaceAll(" ~?\\[.*\\]", ""); - assertThat(result).isEqualTo(stringWriter.toString()); - } - - @Test - public void nested() { - //given - Throwable nestedException = makeNestedException(2); - nestedException.printStackTrace(printWriter); - - //when - ILoggingEvent le = createLoggingEvent(nestedException); - String result = converter.convert(le); - - //then - assertThat(result).startsWith("java.lang.Exception: nesting level=0"); - assertThat( - positionOf("nesting level=0").in(result)).isLessThan( - positionOf("nesting level =1").in(result)); - assertThat( - positionOf("nesting level =1").in(result)).isLessThan( - positionOf("nesting level =2").in(result)); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/SyslogStartConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/SyslogStartConverterTest.java index ceabc71b271b402e3ca9c43549a790404fb36d2c..7ca926d5b4ac00bf64c44e8df3e8dcadf08b2936 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/SyslogStartConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/SyslogStartConverterTest.java @@ -32,104 +32,102 @@ import static org.junit.Assert.assertEquals; public class SyslogStartConverterTest { - private LoggerContext lc; - private SyslogStartConverter converter; - private final String HOSTNAME = findHostname(); - private final Calendar calendar = Calendar.getInstance(Locale.US); - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - converter = new SyslogStartConverter(); - converter.setOptionList(Arrays.asList("local7")); - converter.start(); - } - - @After - public void tearDown() throws Exception { - lc = null; - converter.stop(); - converter = null; - } - - @Test - public void datesLessThanTen() { - // RFC 3164, section 4.1.2: - // If the day of the month is less than 10, then it MUST be represented as - // a space and then the number. For example, the 7th day of August would be - // represented as "Aug 7", with two spaces between the "g" and the "7". - LoggingEvent le = createLoggingEvent(); - calendar.set(2012, Calendar.AUGUST, 7, 13, 15, 0); - le.setTimeStamp(calendar.getTimeInMillis()); - assertEquals("<191>Aug 7 13:15:00 " + HOSTNAME + " ", converter.convert(le)); - } - - @Test - public void datesGreaterThanTen() { - LoggingEvent le = createLoggingEvent(); - calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); - le.setTimeStamp(calendar.getTimeInMillis()); - assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); - } - - @Test - public void multipleConversions() { - LoggingEvent le = createLoggingEvent(); - calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); - le.setTimeStamp(calendar.getTimeInMillis()); - assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); - assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); - - calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 16); - le.setTimeStamp(calendar.getTimeInMillis()); - assertEquals("<191>Oct 11 22:14:16 " + HOSTNAME + " ", converter.convert(le)); - } - - @Test - public void ignoreDefaultLocale() { - Locale originalDefaultLocale = Locale.getDefault(); - Locale.setDefault(Locale.TRADITIONAL_CHINESE); - - try { - converter.start(); - - LoggingEvent le = createLoggingEvent(); - calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); - le.setTimeStamp(calendar.getTimeInMillis()); - String result = converter.convert(le); - assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", result); - } finally { - Locale.setDefault(originalDefaultLocale); + private LoggerContext lc; + private SyslogStartConverter converter; + private final String HOSTNAME = findHostname(); + private final Calendar calendar = Calendar.getInstance(Locale.US); + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + converter = new SyslogStartConverter(); + converter.setOptionList(Arrays.asList("local7")); + converter.start(); } - } - - @Test - @Ignore - public void hostnameShouldNotIncludeDomain() throws Exception { - // RFC 3164, section 4.1.2: - // The Domain Name MUST NOT be included in the HOSTNAME field. - String host = HOSTNAME; - final int firstPeriod = host.indexOf("."); - if (firstPeriod != -1) { - host = host.substring(0, firstPeriod); + + @After + public void tearDown() throws Exception { + lc = null; + converter.stop(); + converter = null; + } + + @Test + public void datesLessThanTen() { + // RFC 3164, section 4.1.2: + // If the day of the month is less than 10, then it MUST be represented as + // a space and then the number. For example, the 7th day of August would be + // represented as "Aug 7", with two spaces between the "g" and the "7". + LoggingEvent le = createLoggingEvent(); + calendar.set(2012, Calendar.AUGUST, 7, 13, 15, 0); + le.setTimeStamp(calendar.getTimeInMillis()); + assertEquals("<191>Aug 7 13:15:00 " + HOSTNAME + " ", converter.convert(le)); + } + + @Test + public void datesGreaterThanTen() { + LoggingEvent le = createLoggingEvent(); + calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); + le.setTimeStamp(calendar.getTimeInMillis()); + assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); + } + + @Test + public void multipleConversions() { + LoggingEvent le = createLoggingEvent(); + calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); + le.setTimeStamp(calendar.getTimeInMillis()); + assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); + assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", converter.convert(le)); + + calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 16); + le.setTimeStamp(calendar.getTimeInMillis()); + assertEquals("<191>Oct 11 22:14:16 " + HOSTNAME + " ", converter.convert(le)); } - LoggingEvent le = createLoggingEvent(); - calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); - le.setTimeStamp(calendar.getTimeInMillis()); - assertEquals("<191>Oct 11 22:14:15 " + host + " ", converter.convert(le)); - } - - private LoggingEvent createLoggingEvent() { - return new LoggingEvent(this.getClass().getName(), lc - .getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, - null); - } - - private static String findHostname() { - try { - return InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - return "UNKNOWN_LOCALHOST"; + + @Test + public void ignoreDefaultLocale() { + Locale originalDefaultLocale = Locale.getDefault(); + Locale.setDefault(Locale.TRADITIONAL_CHINESE); + + try { + converter.start(); + + LoggingEvent le = createLoggingEvent(); + calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); + le.setTimeStamp(calendar.getTimeInMillis()); + String result = converter.convert(le); + assertEquals("<191>Oct 11 22:14:15 " + HOSTNAME + " ", result); + } finally { + Locale.setDefault(originalDefaultLocale); + } + } + + @Test + @Ignore + public void hostnameShouldNotIncludeDomain() throws Exception { + // RFC 3164, section 4.1.2: + // The Domain Name MUST NOT be included in the HOSTNAME field. + String host = HOSTNAME; + final int firstPeriod = host.indexOf("."); + if (firstPeriod != -1) { + host = host.substring(0, firstPeriod); + } + LoggingEvent le = createLoggingEvent(); + calendar.set(2012, Calendar.OCTOBER, 11, 22, 14, 15); + le.setTimeStamp(calendar.getTimeInMillis()); + assertEquals("<191>Oct 11 22:14:15 " + host + " ", converter.convert(le)); + } + + private LoggingEvent createLoggingEvent() { + return new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", null, null); + } + + private static String findHostname() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + return "UNKNOWN_LOCALHOST"; + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviatorTest.java index 184b60bb764a4467d66a6f2441ac6458a51a5b21..c1a30334f5404abedafe298384088b8bc3920c9d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/TargetLengthBasedClassNameAbbreviatorTest.java @@ -19,131 +19,131 @@ import org.junit.Test; import ch.qos.logback.classic.pattern.TargetLengthBasedClassNameAbbreviator; -public class TargetLengthBasedClassNameAbbreviatorTest { +public class TargetLengthBasedClassNameAbbreviatorTest { - - @Test - public void testShortName() { - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(100); - String name = "hello"; - assertEquals(name, abbreviator.abbreviate(name)); - } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(100); - String name = "hello.world"; - assertEquals(name, abbreviator.abbreviate(name)); - } - } - - @Test - public void testNoDot() { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "hello"; - assertEquals(name, abbreviator.abbreviate(name)); - } - - @Test - public void testOneDot() { - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "hello.world"; - assertEquals("h.world", abbreviator.abbreviate(name)); + @Test + public void testShortName() { + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(100); + String name = "hello"; + assertEquals(name, abbreviator.abbreviate(name)); + } + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(100); + String name = "hello.world"; + assertEquals(name, abbreviator.abbreviate(name)); + } } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "h.world"; - assertEquals("h.world", abbreviator.abbreviate(name)); + @Test + public void testNoDot() { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "hello"; + assertEquals(name, abbreviator.abbreviate(name)); } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = ".world"; - assertEquals(".world", abbreviator.abbreviate(name)); - } - } - - @Test - public void testTwoDot() { - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "com.logback.Foobar"; - assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); - } + @Test + public void testOneDot() { + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "hello.world"; + assertEquals("h.world", abbreviator.abbreviate(name)); + } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "c.logback.Foobar"; - assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); - } + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "h.world"; + assertEquals("h.world", abbreviator.abbreviate(name)); + } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "c..Foobar"; - assertEquals("c..Foobar", abbreviator.abbreviate(name)); - } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "..Foobar"; - assertEquals("..Foobar", abbreviator.abbreviate(name)); - } - } - - @Test - public void test3Dot() { - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "com.logback.xyz.Foobar"; - assertEquals("c.l.x.Foobar", abbreviator.abbreviate(name)); - } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(13); - String name = "com.logback.xyz.Foobar"; - assertEquals("c.l.x.Foobar", abbreviator.abbreviate(name)); - } - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(14); - String name = "com.logback.xyz.Foobar"; - assertEquals("c.l.xyz.Foobar", abbreviator.abbreviate(name)); - } - - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(15); - String name = "com.logback.alligator.Foobar"; - assertEquals("c.l.a.Foobar", abbreviator.abbreviate(name)); - } - } - @Test - public void testXDot() { - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(21); - String name = "com.logback.wombat.alligator.Foobar"; - assertEquals("c.l.w.a.Foobar", abbreviator.abbreviate(name)); + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = ".world"; + assertEquals(".world", abbreviator.abbreviate(name)); + } } - - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(22); - String name = "com.logback.wombat.alligator.Foobar"; - assertEquals("c.l.w.alligator.Foobar", abbreviator.abbreviate(name)); - } - - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); - String name = "com.logback.wombat.alligator.tomato.Foobar"; - assertEquals("c.l.w.a.t.Foobar", abbreviator.abbreviate(name)); + + @Test + public void testTwoDot() { + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "com.logback.Foobar"; + assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "c.logback.Foobar"; + assertEquals("c.l.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "c..Foobar"; + assertEquals("c..Foobar", abbreviator.abbreviate(name)); + } + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "..Foobar"; + assertEquals("..Foobar", abbreviator.abbreviate(name)); + } } - - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(21); - String name = "com.logback.wombat.alligator.tomato.Foobar"; - assertEquals("c.l.w.a.tomato.Foobar", abbreviator.abbreviate(name)); + + @Test + public void test3Dot() { + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "com.logback.xyz.Foobar"; + assertEquals("c.l.x.Foobar", abbreviator.abbreviate(name)); + } + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(13); + String name = "com.logback.xyz.Foobar"; + assertEquals("c.l.x.Foobar", abbreviator.abbreviate(name)); + } + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(14); + String name = "com.logback.xyz.Foobar"; + assertEquals("c.l.xyz.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(15); + String name = "com.logback.alligator.Foobar"; + assertEquals("c.l.a.Foobar", abbreviator.abbreviate(name)); + } } - - { - TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(29); - String name = "com.logback.wombat.alligator.tomato.Foobar"; - assertEquals("c.l.w.alligator.tomato.Foobar", abbreviator.abbreviate(name)); + + @Test + public void testXDot() { + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(21); + String name = "com.logback.wombat.alligator.Foobar"; + assertEquals("c.l.w.a.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(22); + String name = "com.logback.wombat.alligator.Foobar"; + assertEquals("c.l.w.alligator.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(1); + String name = "com.logback.wombat.alligator.tomato.Foobar"; + assertEquals("c.l.w.a.t.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(21); + String name = "com.logback.wombat.alligator.tomato.Foobar"; + assertEquals("c.l.w.a.tomato.Foobar", abbreviator.abbreviate(name)); + } + + { + TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(29); + String name = "com.logback.wombat.alligator.tomato.Foobar"; + assertEquals("c.l.w.alligator.tomato.Foobar", abbreviator.abbreviate(name)); + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ThrowableProxyConverterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ThrowableProxyConverterTest.java index 2bfdc62f3365dfdd6821d70c331205cca6c2b6a1..ee15d2e692b0d7db0abb5d89ba59f05a5e0c09ea 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ThrowableProxyConverterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/pattern/ThrowableProxyConverterTest.java @@ -40,188 +40,184 @@ import static org.junit.Assume.assumeTrue; public class ThrowableProxyConverterTest { - LoggerContext lc = new LoggerContext(); - ThrowableProxyConverter tpc = new ThrowableProxyConverter(); - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - - @Before - public void setUp() throws Exception { - tpc.setContext(lc); - tpc.start(); - } - - @After - public void tearDown() throws Exception { - } - - private ILoggingEvent createLoggingEvent(Throwable t) { - return new LoggingEvent(this.getClass().getName(), lc - .getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, - null); - } - - @Test - public void suppressed() throws InvocationTargetException, IllegalAccessException - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(e, fooException); - addSuppressed(e, barException); - ex = e; + LoggerContext lc = new LoggerContext(); + ThrowableProxyConverter tpc = new ThrowableProxyConverter(); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + + @Before + public void setUp() throws Exception { + tpc.setContext(lc); + tpc.start(); } - verify(ex); - } - - @Test - public void suppressedWithCause() throws InvocationTargetException, IllegalAccessException - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - ex=new Exception("Wrapper", e); - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(ex, fooException); - addSuppressed(e, barException); + + @After + public void tearDown() throws Exception { + } + + private ILoggingEvent createLoggingEvent(Throwable t) { + return new LoggingEvent(this.getClass().getName(), lc.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG, "test message", t, null); + } + + @Test + public void suppressed() throws InvocationTargetException, IllegalAccessException { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(e, fooException); + addSuppressed(e, barException); + ex = e; + } + verify(ex); } - verify(ex); - } - - @Test - public void suppressedWithSuppressed() throws Exception - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - ex=new Exception("Wrapper", e); - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(barException, fooException); - addSuppressed(e, barException); + + @Test + public void suppressedWithCause() throws InvocationTargetException, IllegalAccessException { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + ex = new Exception("Wrapper", e); + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(ex, fooException); + addSuppressed(e, barException); + } + verify(ex); + } + + @Test + public void suppressedWithSuppressed() throws Exception { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + ex = new Exception("Wrapper", e); + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(barException, fooException); + addSuppressed(e, barException); + } + verify(ex); + } + + @Test + public void smoke() { + Exception t = new Exception("smoke"); + verify(t); + } + + @Test + public void nested() { + Throwable t = TestHelper.makeNestedException(1); + verify(t); + } + + @Test + public void withArgumentOfOne() throws Exception { + final Throwable t = TestHelper.makeNestedException(0); + t.printStackTrace(pw); + final ILoggingEvent le = createLoggingEvent(t); + + final List optionList = Arrays.asList("1"); + tpc.setOptionList(optionList); + tpc.start(); + + final String result = tpc.convert(le); + + final BufferedReader reader = new BufferedReader(new StringReader(result)); + assertTrue(reader.readLine().contains(t.getMessage())); + assertNotNull(reader.readLine()); + assertNull("Unexpected line in stack trace", reader.readLine()); + } + + @Test + public void withShortArgument() throws Exception { + final Throwable t = TestHelper.makeNestedException(0); + t.printStackTrace(pw); + final ILoggingEvent le = createLoggingEvent(t); + + final List options = Arrays.asList("short"); + tpc.setOptionList(options); + tpc.start(); + + final String result = tpc.convert(le); + + final BufferedReader reader = new BufferedReader(new StringReader(result)); + assertTrue(reader.readLine().contains(t.getMessage())); + assertNotNull(reader.readLine()); + assertNull("Unexpected line in stack trace", reader.readLine()); + } + + @Test + public void skipSelectedLine() throws Exception { + // given + final Throwable t = TestHelper.makeNestedException(0); + t.printStackTrace(pw); + final ILoggingEvent le = createLoggingEvent(t); + tpc.setOptionList(Arrays.asList("full", "skipSelectedLines")); + tpc.start(); + + // when + final String result = tpc.convert(le); + + // then + assertThat(result).excludes("skipSelectedLines"); + } + + @Test + public void skipMultipleLines() throws Exception { + // given + final Throwable t = TestHelper.makeNestedException(0); + t.printStackTrace(pw); + final ILoggingEvent le = createLoggingEvent(t); + tpc.setOptionList(Arrays.asList("full", "skipMultipleLines", "junit")); + tpc.start(); + + // when + final String result = tpc.convert(le); + + // then + assertThat(result).excludes("skipSelectedLines").excludes("junit"); + } + + @Test + public void shouldLimitTotalLinesExcludingSkipped() throws Exception { + // given + final Throwable t = TestHelper.makeNestedException(0); + t.printStackTrace(pw); + final ILoggingEvent le = createLoggingEvent(t); + tpc.setOptionList(Arrays.asList("3", "shouldLimitTotalLinesExcludingSkipped")); + tpc.start(); + + // when + final String result = tpc.convert(le); + + // then + String[] lines = result.split(CoreConstants.LINE_SEPARATOR); + assertThat(lines).hasSize(3 + 1); + } + + void someMethod() throws Exception { + throw new Exception("someMethod"); + } + + void verify(Throwable t) { + t.printStackTrace(pw); + + ILoggingEvent le = createLoggingEvent(t); + String result = tpc.convert(le); + System.out.println(result); + result = result.replace("common frames omitted", "more"); + assertEquals(sw.toString(), result); } - verify(ex); - } - - @Test - public void smoke() { - Exception t = new Exception("smoke"); - verify(t); - } - - @Test - public void nested() { - Throwable t = TestHelper.makeNestedException(1); - verify(t); - } - - @Test - public void withArgumentOfOne() throws Exception { - final Throwable t = TestHelper.makeNestedException(0); - t.printStackTrace(pw); - final ILoggingEvent le = createLoggingEvent(t); - - final List optionList = Arrays.asList("1"); - tpc.setOptionList(optionList); - tpc.start(); - - final String result = tpc.convert(le); - - final BufferedReader reader = new BufferedReader(new StringReader(result)); - assertTrue(reader.readLine().contains(t.getMessage())); - assertNotNull(reader.readLine()); - assertNull("Unexpected line in stack trace", reader.readLine()); - } - - @Test - public void withShortArgument() throws Exception { - final Throwable t = TestHelper.makeNestedException(0); - t.printStackTrace(pw); - final ILoggingEvent le = createLoggingEvent(t); - - final List options = Arrays.asList("short"); - tpc.setOptionList(options); - tpc.start(); - - final String result = tpc.convert(le); - - final BufferedReader reader = new BufferedReader(new StringReader(result)); - assertTrue(reader.readLine().contains(t.getMessage())); - assertNotNull(reader.readLine()); - assertNull("Unexpected line in stack trace", reader.readLine()); - } - - @Test - public void skipSelectedLine() throws Exception { - //given - final Throwable t = TestHelper.makeNestedException(0); - t.printStackTrace(pw); - final ILoggingEvent le = createLoggingEvent(t); - tpc.setOptionList(Arrays.asList("full", "skipSelectedLines")); - tpc.start(); - - //when - final String result = tpc.convert(le); - - //then - assertThat(result).excludes("skipSelectedLines"); - } - - @Test - public void skipMultipleLines() throws Exception { - //given - final Throwable t = TestHelper.makeNestedException(0); - t.printStackTrace(pw); - final ILoggingEvent le = createLoggingEvent(t); - tpc.setOptionList(Arrays.asList("full", "skipMultipleLines", "junit")); - tpc.start(); - - //when - final String result = tpc.convert(le); - - //then - assertThat(result) - .excludes("skipSelectedLines") - .excludes("junit"); - } - - @Test - public void shouldLimitTotalLinesExcludingSkipped() throws Exception { - //given - final Throwable t = TestHelper.makeNestedException(0); - t.printStackTrace(pw); - final ILoggingEvent le = createLoggingEvent(t); - tpc.setOptionList(Arrays.asList("3", "shouldLimitTotalLinesExcludingSkipped")); - tpc.start(); - - //when - final String result = tpc.convert(le); - - //then - String[] lines = result.split(CoreConstants.LINE_SEPARATOR); - assertThat(lines).hasSize(3 + 1); - } - - void someMethod() throws Exception { - throw new Exception("someMethod"); - } - - void verify(Throwable t) { - t.printStackTrace(pw); - - ILoggingEvent le = createLoggingEvent(t); - String result = tpc.convert(le); - System.out.println(result); - result = result.replace("common frames omitted", "more"); - assertEquals(sw.toString(), result); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/PackageTest.java index 8fa6f69d3b98d3c297a315784b4dbbba1ee98433..041106b1175a33347af2d2a196197e0dbddf306c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { UniqueFileTest.class, TimeBasedRollingWithConfigFileTest.class }) +@SuiteClasses({ UniqueFileTest.class, TimeBasedRollingWithConfigFileTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/TimeBasedRollingWithConfigFileTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/TimeBasedRollingWithConfigFileTest.java index 6cb94d259434314e39be68795d05eb85e1e288ae..b84f263447878d107f0c020125efd7b5f7bff3b4 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/TimeBasedRollingWithConfigFileTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/TimeBasedRollingWithConfigFileTest.java @@ -135,7 +135,6 @@ public class TimeBasedRollingWithConfigFileTest extends ScaffoldingForRollingTes eCount >= 4 && eCount > expectedFilenameList.size() / 2); } - @Test public void timeAndSizeWithoutIntegerToken() throws Exception { String testId = "timeAndSizeWithoutIntegerToken"; @@ -144,12 +143,12 @@ public class TimeBasedRollingWithConfigFileTest extends ScaffoldingForRollingTes expectedFilenameList.add(randomOutputDir + "z" + testId); RollingFileAppender rfa = (RollingFileAppender) root.getAppender("ROLLING"); StatusPrinter.print(lc); - + statusChecker.assertContainsMatch("Missing integer token"); assertFalse(rfa.isStarted()); - + } - + void addExpectedFileNamedIfItsTime(String testId, String msg, boolean gzExtension) { fileSize += msg.getBytes().length; diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/UniqueFileTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/UniqueFileTest.java index 3522c754e089c9c06d6c33994ca20ab42903293e..4378af2294d015e4b5cca13096cb1b72b5ef9050 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/rolling/UniqueFileTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/rolling/UniqueFileTest.java @@ -37,23 +37,23 @@ import ch.qos.logback.core.util.CoreTestConstants; */ public class UniqueFileTest { static String UNIK_DIFF = "UNIK_DIFF"; - + LoggerContext lc = new LoggerContext(); StatusChecker sc = new StatusChecker(lc); Logger logger = lc.getLogger(this.getClass()); - int diff = RandomUtil.getPositiveInt()%1000; + int diff = RandomUtil.getPositiveInt() % 1000; String diffAsStr = Integer.toString(diff); - - + @Before public void setUp() { System.setProperty(UNIK_DIFF, diffAsStr); } + @After public void tearDown() { System.clearProperty(UNIK_DIFF); } - + void loadConfig(String confifFile) throws JoranException { JoranConfigurator jc = new JoranConfigurator(); jc.setContext(lc); diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextDetachingSCLTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextDetachingSCLTest.java index fac3b510642cc2cb238c8023e291d499de83c6b5..d51b9b970e56064083487f55e13d1927921f6127 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextDetachingSCLTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextDetachingSCLTest.java @@ -28,62 +28,61 @@ import ch.qos.logback.classic.util.MockInitialContextFactory; import org.slf4j.LoggerFactoryFriend; import org.slf4j.impl.StaticLoggerBinderFriend; -public class ContextDetachingSCLTest { - - static String INITIAL_CONTEXT_KEY = "java.naming.factory.initial"; - - ContextDetachingSCL contextDetachingSCL; - - @Before - public void setUp() throws Exception { - - System.setProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR, "JNDI"); - - contextDetachingSCL = new ContextDetachingSCL(); - - MockInitialContextFactory.initialize(); - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "toto"); - - //The property must be set after we setup the Mock - System.setProperty(INITIAL_CONTEXT_KEY, MockInitialContextFactory.class.getName()); - - // reinitialize the LoggerFactory, These reset methods are reserved for internal use - StaticLoggerBinderFriend.reset(); - LoggerFactoryFriend.reset(); - - //this call will create the context "toto" - LoggerFactory.getLogger(ContextDetachingSCLTest.class); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(INITIAL_CONTEXT_KEY); - // reinitialize the LoggerFactory, These resets method are reserved for internal use - StaticLoggerBinderFriend.reset(); - LoggerFactoryFriend.reset(); - } - - @Test - public void testDetach() { - ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); - contextDetachingSCL.contextDestroyed(null); - assertEquals(0, selector.getCount()); - } - - - @Test - public void testDetachWithMissingContext() { - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); - ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); - assertEquals("tata", selector.getLoggerContext().getName()); - - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "titi"); - assertEquals("titi", selector.getLoggerContext().getName()); - contextDetachingSCL.contextDestroyed(null); - - assertEquals(2, selector.getCount()); - } - +public class ContextDetachingSCLTest { + + static String INITIAL_CONTEXT_KEY = "java.naming.factory.initial"; + + ContextDetachingSCL contextDetachingSCL; + + @Before + public void setUp() throws Exception { + + System.setProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR, "JNDI"); + + contextDetachingSCL = new ContextDetachingSCL(); + + MockInitialContextFactory.initialize(); + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "toto"); + + // The property must be set after we setup the Mock + System.setProperty(INITIAL_CONTEXT_KEY, MockInitialContextFactory.class.getName()); + + // reinitialize the LoggerFactory, These reset methods are reserved for internal use + StaticLoggerBinderFriend.reset(); + LoggerFactoryFriend.reset(); + + // this call will create the context "toto" + LoggerFactory.getLogger(ContextDetachingSCLTest.class); + } + + @After + public void tearDown() throws Exception { + System.clearProperty(INITIAL_CONTEXT_KEY); + // reinitialize the LoggerFactory, These resets method are reserved for internal use + StaticLoggerBinderFriend.reset(); + LoggerFactoryFriend.reset(); + } + + @Test + public void testDetach() { + ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); + contextDetachingSCL.contextDestroyed(null); + assertEquals(0, selector.getCount()); + } + + @Test + public void testDetachWithMissingContext() { + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); + ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); + assertEquals("tata", selector.getLoggerContext().getName()); + + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "titi"); + assertEquals("titi", selector.getLoggerContext().getName()); + contextDetachingSCL.contextDestroyed(null); + + assertEquals(2, selector.getCount()); + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextJNDISelectorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextJNDISelectorTest.java index 1bd8fc5b7a612a521af0b6d490d02a73b953133a..bdfc49d14ae565e1658ef0027f7f86939b9c272c 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextJNDISelectorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/selector/ContextJNDISelectorTest.java @@ -27,62 +27,62 @@ import ch.qos.logback.classic.util.MockInitialContext; import ch.qos.logback.classic.util.MockInitialContextFactory; import ch.qos.logback.core.Context; -public class ContextJNDISelectorTest { - - static String INITIAL_CONTEXT_KEY = "java.naming.factory.initial"; - - @Before - public void setUp() throws Exception { - - System.setProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR, "JNDI"); - StaticLoggerBinderFriend.reset(); - - MockInitialContextFactory.initialize(); - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "toto"); - - //The property must be set after we setup the Mock - System.setProperty(INITIAL_CONTEXT_KEY, MockInitialContextFactory.class.getName()); - - //this call will create the context "toto" - LoggerFactory.getLogger(ContextDetachingSCLTest.class); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(INITIAL_CONTEXT_KEY); - } - - @Test - public void testGetExistingContext() { - ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); - Context context = selector.getLoggerContext(); - assertEquals("toto", context.getName()); - } - - @Test - public void testCreateContext() { - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); - - LoggerFactory.getLogger(ContextDetachingSCLTest.class); - - ContextJNDISelector selector = (ContextJNDISelector)ContextSelectorStaticBinder.getSingleton().getContextSelector(); - Context context = selector.getLoggerContext(); - assertEquals("tata", context.getName()); - System.out.println(selector.getContextNames()); - assertEquals(2, selector.getCount()); - } - - @Test - public void defaultContext() { - MockInitialContext mic = MockInitialContextFactory.getContext(); - mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, null); - - ContextJNDISelector selector = (ContextJNDISelector)ContextSelectorStaticBinder.getSingleton().getContextSelector(); - Context context = selector.getLoggerContext(); - - assertEquals("default", context.getName()); - } - +public class ContextJNDISelectorTest { + + static String INITIAL_CONTEXT_KEY = "java.naming.factory.initial"; + + @Before + public void setUp() throws Exception { + + System.setProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR, "JNDI"); + StaticLoggerBinderFriend.reset(); + + MockInitialContextFactory.initialize(); + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "toto"); + + // The property must be set after we setup the Mock + System.setProperty(INITIAL_CONTEXT_KEY, MockInitialContextFactory.class.getName()); + + // this call will create the context "toto" + LoggerFactory.getLogger(ContextDetachingSCLTest.class); + } + + @After + public void tearDown() throws Exception { + System.clearProperty(INITIAL_CONTEXT_KEY); + } + + @Test + public void testGetExistingContext() { + ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector(); + Context context = selector.getLoggerContext(); + assertEquals("toto", context.getName()); + } + + @Test + public void testCreateContext() { + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, "tata"); + + LoggerFactory.getLogger(ContextDetachingSCLTest.class); + + ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); + Context context = selector.getLoggerContext(); + assertEquals("tata", context.getName()); + System.out.println(selector.getContextNames()); + assertEquals(2, selector.getCount()); + } + + @Test + public void defaultContext() { + MockInitialContext mic = MockInitialContextFactory.getContext(); + mic.map.put(ClassicConstants.JNDI_CONTEXT_NAME, null); + + ContextJNDISelector selector = (ContextJNDISelector) ContextSelectorStaticBinder.getSingleton().getContextSelector(); + Context context = selector.getLoggerContext(); + + assertEquals("default", context.getName()); + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/selector/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/selector/PackageTest.java index 8e8aa6d8c5325872e102aef96c1476d4d8f7e25e..30571484ee2ecf3aa5d19c79c441de6885d99a1e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/selector/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/selector/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ContextJNDISelectorTest.class, ContextDetachingSCLTest.class}) -public class PackageTest { +@SuiteClasses({ ContextJNDISelectorTest.class, ContextDetachingSCLTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/sift/MDCBasedDiscriminatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/sift/MDCBasedDiscriminatorTest.java index 989878e6b194305632716ba19c3f3674223a1485..3e2db5111b50a746c033dec4e92231fcb5b6bb36 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/sift/MDCBasedDiscriminatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/sift/MDCBasedDiscriminatorTest.java @@ -35,46 +35,46 @@ import static org.junit.Assert.assertTrue; */ public class MDCBasedDiscriminatorTest { - static String DEFAULT_VAL = "DEFAULT_VAL"; + static String DEFAULT_VAL = "DEFAULT_VAL"; - MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator(); - LoggerContext context = new LoggerContext(); - Logger logger = context.getLogger(this.getClass()); + MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator(); + LoggerContext context = new LoggerContext(); + Logger logger = context.getLogger(this.getClass()); - int diff = RandomUtil.getPositiveInt(); - String key = "MDCBasedDiscriminatorTest_key" + diff; - String value = "MDCBasedDiscriminatorTest_val" + diff; - LoggingEvent event; + int diff = RandomUtil.getPositiveInt(); + String key = "MDCBasedDiscriminatorTest_key" + diff; + String value = "MDCBasedDiscriminatorTest_val" + diff; + LoggingEvent event; - @Before - public void setUp() { - MDC.clear(); - discriminator.setContext(context); - discriminator.setKey(key); - discriminator.setDefaultValue(DEFAULT_VAL); - discriminator.start(); - assertTrue(discriminator.isStarted()); - } + @Before + public void setUp() { + MDC.clear(); + discriminator.setContext(context); + discriminator.setKey(key); + discriminator.setDefaultValue(DEFAULT_VAL); + discriminator.start(); + assertTrue(discriminator.isStarted()); + } - @After - public void teaDown() { - MDC.clear(); - } + @After + public void teaDown() { + MDC.clear(); + } - @Test - public void smoke() { - MDC.put(key, value); - event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null); + @Test + public void smoke() { + MDC.put(key, value); + event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null); - String discriminatorValue = discriminator.getDiscriminatingValue(event); - assertEquals(value, discriminatorValue); - } + String discriminatorValue = discriminator.getDiscriminatingValue(event); + assertEquals(value, discriminatorValue); + } - @Test - public void nullMDC() { - event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null); - assertEquals(new HashMap(), event.getMDCPropertyMap()); - String discriminatorValue = discriminator.getDiscriminatingValue(event); - assertEquals(DEFAULT_VAL, discriminatorValue); - } + @Test + public void nullMDC() { + event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null); + assertEquals(new HashMap(), event.getMDCPropertyMap()); + String discriminatorValue = discriminator.getDiscriminatingValue(event); + assertEquals(DEFAULT_VAL, discriminatorValue); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/sift/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/sift/PackageTest.java index a854681f4eb24535c2c7d785020701a488215080..b8cd386757c1d63817bcd495c3bd4488af2bba55 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/sift/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/sift/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({MDCBasedDiscriminatorTest.class, SiftingAppenderTest.class}) -public class PackageTest { +@SuiteClasses({ MDCBasedDiscriminatorTest.class, SiftingAppenderTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/sift/SiftingAppenderTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/sift/SiftingAppenderTest.java index 867fa518ccfb19f13296eb99de424e3e8bca55ce..ae601107fe84b4dc3ac109f6cf2bb9dcb156a502 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/sift/SiftingAppenderTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/sift/SiftingAppenderTest.java @@ -49,244 +49,237 @@ import ch.qos.logback.core.util.StatusPrinter; public class SiftingAppenderTest { - static String SIFT_FOLDER_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX + "sift/"; - - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(this.getClass().getName()); - Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - StatusChecker statusChecker = new StatusChecker(loggerContext); - int diff = RandomUtil.getPositiveInt(); - int now = 0; - - protected void configure(String file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(file); - } - - @Before - public void setUp() { - MDC.clear(); - } - - @After - public void tearDown() { - MDC.clear(); - } - - @Test - public void unsetDefaultValueProperty() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "unsetDefaultValueProperty.xml"); - logger.debug("hello"); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - assertFalse(sa.isStarted()); - } - - @Test - public void smoke() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "smoke.xml"); - logger.debug("smoke"); - Appender appender = getAppenderTracker().find("smokeDefault"); - assertNotNull(appender); - ListAppender listAppender = (ListAppender) appender; - List eventList = listAppender.list; - assertEquals(1, listAppender.list.size()); - assertEquals("smoke", eventList.get(0).getMessage()); - } - - private AppenderTracker getAppenderTracker() { - SiftingAppender ha = (SiftingAppender) root.getAppender("SIFT"); - return ha.getAppenderTracker(); - } - - @Test - public void zeroNesting() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "zeroNesting.xml"); - logger.debug("hello"); - logger.debug("hello"); - logger.debug("hello"); - logger.debug("hello"); - logger.debug("hello"); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - - Appender appender = getAppenderTracker().find("zeroDefault"); - assertNotNull(appender); - NOPAppender nopa = (NOPAppender) appender; - StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); - - statusChecker.assertContainsMatch(ErrorStatus.ERROR, "No nested appenders found"); - } - - @Test - public void multipleNesting() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "multipleNesting.xml"); - logger.debug("hello"); - logger.debug("hello"); - logger.debug("hello"); - - Appender listAppender = getAppenderTracker().find("multipleDefault"); - StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); - - assertNotNull(listAppender); - statusChecker.assertContainsMatch(ErrorStatus.ERROR, - "Only and only one appender can be nested"); - } - - @Test - public void defaultLayoutRule() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "defaultLayoutRule.xml"); - logger.debug("hello"); - SiftingAppender ha = (SiftingAppender) root.getAppender("SIFT"); - StringListAppender listAppender = (StringListAppender) ha - .getAppenderTracker().find("default"); - - assertNotNull(listAppender); - List strList = listAppender.strList; - assertEquals(1, strList.size()); - assertEquals("DEBUG hello", strList.get(0)); - } - - @Test - public void testWholeCycle() throws JoranException { - String mdcKey = "cycle"; - configure(SIFT_FOLDER_PREFIX + "completeCycle.xml"); - MDC.put(mdcKey, "a"); - logger.debug("smoke"); - long timestamp = System.currentTimeMillis(); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - ListAppender listAppender = (ListAppender) - sa.getAppenderTracker().find("a"); - assertNotNull(listAppender); - List eventList = listAppender.list; - assertEquals(1, listAppender.list.size()); - assertEquals("smoke", eventList.get(0).getMessage()); - - MDC.remove(mdcKey); - LoggingEvent le = new LoggingEvent("x", logger, Level.INFO, "hello", null, - null); - le.setTimeStamp(timestamp + ComponentTracker.DEFAULT_TIMEOUT + 1); - sa.doAppend(le); - assertFalse(listAppender.isStarted()); - assertEquals(1, sa.getAppenderTracker().allKeys().size()); - assertTrue(sa.getAppenderTracker().allKeys().contains("cycleDefault")); - } - - @Test - public void sessionFinalizationShouldCauseLingering() throws JoranException { - String mdcKey = "linger"; - String mdcVal = "session" + diff; - configure(SIFT_FOLDER_PREFIX + "lingering.xml"); - MDC.put(mdcKey, mdcVal); - logger.debug("linger 1"); - logger.debug(ClassicConstants.FINALIZE_SESSION_MARKER, "linger 2"); - long now = System.currentTimeMillis(); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - AppenderTracker tracker = sa.getAppenderTracker(); - - assertEquals(1, tracker.allKeys().size()); - Appender appender = tracker.find(mdcVal); - assertTrue(appender.isStarted()); - - tracker.removeStaleComponents(now + AppenderTracker.LINGERING_TIMEOUT + 1); - // previously lingering appenders should be closed upon timeout - assertFalse(appender.isStarted()); - // and they should be gone - assertEquals(0, tracker.allKeys().size()); - } - - @Test - public void localPropertiesShouldBeVisible() throws JoranException { - String mdcKey = "localProperty"; - String mdcVal = "" + diff; - String msg = "localPropertiesShouldBeVisible"; - String prefix = "Y"; - configure(SIFT_FOLDER_PREFIX + "propertyPropagation.xml"); - MDC.put(mdcKey, mdcVal); - logger.debug(msg); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - StringListAppender listAppender = (StringListAppender) sa - .getAppenderTracker().find(mdcVal); - assertNotNull(listAppender); - List strList = listAppender.strList; - assertEquals(1, listAppender.strList.size()); - assertEquals(prefix + msg, strList.get(0)); - } - - @Test - public void propertyDefinedWithinSiftElementShouldBeVisible() throws JoranException { - String mdcKey = "propertyDefinedWithinSift"; - String mdcVal = "" + diff; - String msg = "propertyDefinedWithinSiftElementShouldBeVisible"; - String prefix = "Y"; - configure(SIFT_FOLDER_PREFIX + "propertyDefinedInSiftElement.xml"); - MDC.put(mdcKey, mdcVal); - logger.debug(msg); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - StringListAppender listAppender = (StringListAppender) sa - .getAppenderTracker().find(mdcVal); - assertNotNull(listAppender); - List strList = listAppender.strList; - assertEquals(1, listAppender.strList.size()); - assertEquals(prefix + msg, strList.get(0)); - } - - @Test - public void compositePropertyShouldCombineWithinAndWithoutSiftElement() throws JoranException { - String mdcKey = "compositeProperty"; - String mdcVal = "" + diff; - String msg = "compositePropertyShouldCombineWithinAndWithoutSiftElement"; - String prefix = "composite"; - configure(SIFT_FOLDER_PREFIX + "compositeProperty.xml"); - MDC.put(mdcKey, mdcVal); - logger.debug(msg); - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - StringListAppender listAppender = (StringListAppender) sa - .getAppenderTracker().find(mdcVal); - assertNotNull(listAppender); - List strList = listAppender.strList; - assertEquals(1, listAppender.strList.size()); - assertEquals(prefix + msg, strList.get(0)); - } - - @Test - public void maxAppendersCountPropertyShouldBeHonored() throws JoranException { - configure(SIFT_FOLDER_PREFIX + "maxAppenderCount.xml"); - int max = 5; - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); - String mdcKey = "max"; - for(int i = 0; i <= max; i++) { - MDC.put(mdcKey, "" + (diff + i)); - LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "max"+i, null, null); - event.setTimeStamp(now); - sa.doAppend(event); - now += AbstractComponentTracker.WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS; + static String SIFT_FOLDER_PREFIX = ClassicTestConstants.JORAN_INPUT_PREFIX + "sift/"; + + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(this.getClass().getName()); + Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + StatusChecker statusChecker = new StatusChecker(loggerContext); + int diff = RandomUtil.getPositiveInt(); + int now = 0; + + protected void configure(String file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(file); } - AppenderTracker tracker = sa.getAppenderTracker(); - assertEquals(max, tracker.allKeys().size()); - assertNull(tracker.find("" + (diff + 0))); - for(int i = 1; i <= max; i++) { - assertNotNull(tracker.find("" + (diff + i))); + + @Before + public void setUp() { + MDC.clear(); + } + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void unsetDefaultValueProperty() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "unsetDefaultValueProperty.xml"); + logger.debug("hello"); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + assertFalse(sa.isStarted()); + } + + @Test + public void smoke() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "smoke.xml"); + logger.debug("smoke"); + Appender appender = getAppenderTracker().find("smokeDefault"); + assertNotNull(appender); + ListAppender listAppender = (ListAppender) appender; + List eventList = listAppender.list; + assertEquals(1, listAppender.list.size()); + assertEquals("smoke", eventList.get(0).getMessage()); + } + + private AppenderTracker getAppenderTracker() { + SiftingAppender ha = (SiftingAppender) root.getAppender("SIFT"); + return ha.getAppenderTracker(); + } + + @Test + public void zeroNesting() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "zeroNesting.xml"); + logger.debug("hello"); + logger.debug("hello"); + logger.debug("hello"); + logger.debug("hello"); + logger.debug("hello"); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + + Appender appender = getAppenderTracker().find("zeroDefault"); + assertNotNull(appender); + NOPAppender nopa = (NOPAppender) appender; + StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); + + statusChecker.assertContainsMatch(ErrorStatus.ERROR, "No nested appenders found"); + } + + @Test + public void multipleNesting() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "multipleNesting.xml"); + logger.debug("hello"); + logger.debug("hello"); + logger.debug("hello"); + + Appender listAppender = getAppenderTracker().find("multipleDefault"); + StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); + + assertNotNull(listAppender); + statusChecker.assertContainsMatch(ErrorStatus.ERROR, "Only and only one appender can be nested"); } - } - @Test - public void timeoutPropertyShouldBeHonored() throws JoranException, InterruptedException { - configure(SIFT_FOLDER_PREFIX + "timeout.xml"); - long timeout = 30*1000; - SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + @Test + public void defaultLayoutRule() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "defaultLayoutRule.xml"); + logger.debug("hello"); + SiftingAppender ha = (SiftingAppender) root.getAppender("SIFT"); + StringListAppender listAppender = (StringListAppender) ha.getAppenderTracker().find("default"); + + assertNotNull(listAppender); + List strList = listAppender.strList; + assertEquals(1, strList.size()); + assertEquals("DEBUG hello", strList.get(0)); + } + + @Test + public void testWholeCycle() throws JoranException { + String mdcKey = "cycle"; + configure(SIFT_FOLDER_PREFIX + "completeCycle.xml"); + MDC.put(mdcKey, "a"); + logger.debug("smoke"); + long timestamp = System.currentTimeMillis(); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + ListAppender listAppender = (ListAppender) sa.getAppenderTracker().find("a"); + assertNotNull(listAppender); + List eventList = listAppender.list; + assertEquals(1, listAppender.list.size()); + assertEquals("smoke", eventList.get(0).getMessage()); + + MDC.remove(mdcKey); + LoggingEvent le = new LoggingEvent("x", logger, Level.INFO, "hello", null, null); + le.setTimeStamp(timestamp + ComponentTracker.DEFAULT_TIMEOUT + 1); + sa.doAppend(le); + assertFalse(listAppender.isStarted()); + assertEquals(1, sa.getAppenderTracker().allKeys().size()); + assertTrue(sa.getAppenderTracker().allKeys().contains("cycleDefault")); + } + + @Test + public void sessionFinalizationShouldCauseLingering() throws JoranException { + String mdcKey = "linger"; + String mdcVal = "session" + diff; + configure(SIFT_FOLDER_PREFIX + "lingering.xml"); + MDC.put(mdcKey, mdcVal); + logger.debug("linger 1"); + logger.debug(ClassicConstants.FINALIZE_SESSION_MARKER, "linger 2"); + long now = System.currentTimeMillis(); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + AppenderTracker tracker = sa.getAppenderTracker(); + + assertEquals(1, tracker.allKeys().size()); + Appender appender = tracker.find(mdcVal); + assertTrue(appender.isStarted()); + + tracker.removeStaleComponents(now + AppenderTracker.LINGERING_TIMEOUT + 1); + // previously lingering appenders should be closed upon timeout + assertFalse(appender.isStarted()); + // and they should be gone + assertEquals(0, tracker.allKeys().size()); + } - LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "timeout", null, null); - event.setTimeStamp(now); - sa.doAppend(event); + @Test + public void localPropertiesShouldBeVisible() throws JoranException { + String mdcKey = "localProperty"; + String mdcVal = "" + diff; + String msg = "localPropertiesShouldBeVisible"; + String prefix = "Y"; + configure(SIFT_FOLDER_PREFIX + "propertyPropagation.xml"); + MDC.put(mdcKey, mdcVal); + logger.debug(msg); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + StringListAppender listAppender = (StringListAppender) sa.getAppenderTracker().find(mdcVal); + assertNotNull(listAppender); + List strList = listAppender.strList; + assertEquals(1, listAppender.strList.size()); + assertEquals(prefix + msg, strList.get(0)); + } - AppenderTracker tracker = sa.getAppenderTracker(); + @Test + public void propertyDefinedWithinSiftElementShouldBeVisible() throws JoranException { + String mdcKey = "propertyDefinedWithinSift"; + String mdcVal = "" + diff; + String msg = "propertyDefinedWithinSiftElementShouldBeVisible"; + String prefix = "Y"; + configure(SIFT_FOLDER_PREFIX + "propertyDefinedInSiftElement.xml"); + MDC.put(mdcKey, mdcVal); + logger.debug(msg); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + StringListAppender listAppender = (StringListAppender) sa.getAppenderTracker().find(mdcVal); + assertNotNull(listAppender); + List strList = listAppender.strList; + assertEquals(1, listAppender.strList.size()); + assertEquals(prefix + msg, strList.get(0)); + } - assertEquals(1, tracker.getComponentCount()); + @Test + public void compositePropertyShouldCombineWithinAndWithoutSiftElement() throws JoranException { + String mdcKey = "compositeProperty"; + String mdcVal = "" + diff; + String msg = "compositePropertyShouldCombineWithinAndWithoutSiftElement"; + String prefix = "composite"; + configure(SIFT_FOLDER_PREFIX + "compositeProperty.xml"); + MDC.put(mdcKey, mdcVal); + logger.debug(msg); + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + StringListAppender listAppender = (StringListAppender) sa.getAppenderTracker().find(mdcVal); + assertNotNull(listAppender); + List strList = listAppender.strList; + assertEquals(1, listAppender.strList.size()); + assertEquals(prefix + msg, strList.get(0)); + } - now += timeout+1; - tracker.removeStaleComponents(now); - assertEquals(0, tracker.getComponentCount()); - statusChecker.assertIsErrorFree(); - } + @Test + public void maxAppendersCountPropertyShouldBeHonored() throws JoranException { + configure(SIFT_FOLDER_PREFIX + "maxAppenderCount.xml"); + int max = 5; + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + String mdcKey = "max"; + for (int i = 0; i <= max; i++) { + MDC.put(mdcKey, "" + (diff + i)); + LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "max" + i, null, null); + event.setTimeStamp(now); + sa.doAppend(event); + now += AbstractComponentTracker.WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS; + } + AppenderTracker tracker = sa.getAppenderTracker(); + assertEquals(max, tracker.allKeys().size()); + assertNull(tracker.find("" + (diff + 0))); + for (int i = 1; i <= max; i++) { + assertNotNull(tracker.find("" + (diff + i))); + } + } + + @Test + public void timeoutPropertyShouldBeHonored() throws JoranException, InterruptedException { + configure(SIFT_FOLDER_PREFIX + "timeout.xml"); + long timeout = 30 * 1000; + SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); + + LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "timeout", null, null); + event.setTimeStamp(now); + sa.doAppend(event); + + AppenderTracker tracker = sa.getAppenderTracker(); + + assertEquals(1, tracker.getComponentCount()); + + now += timeout + 1; + tracker.removeStaleComponents(now); + assertEquals(0, tracker.getComponentCount()); + statusChecker.assertIsErrorFree(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/BasicContextListener.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/BasicContextListener.java index bfaa209320b548221699ca1d857287ff2b7974b3..4146a47a65c8f945efc9e7c7644ad377f347bd0a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/BasicContextListener.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/BasicContextListener.java @@ -19,42 +19,47 @@ import ch.qos.logback.classic.LoggerContext; public class BasicContextListener implements LoggerContextListener { - enum UpdateType { NONE, START, RESET, STOP , LEVEL_CHANGE}; - - UpdateType updateType = UpdateType.NONE; - LoggerContext context; - Logger logger; - Level level; - - boolean resetResistant; - - public void setResetResistant(boolean resetResistant) { - this.resetResistant = resetResistant; - } - - public void onReset(LoggerContext context) { - updateType = UpdateType.RESET; - this.context = context; - - } - public void onStart(LoggerContext context) { - updateType = UpdateType.START;; - this.context = context; - } - - public void onStop(LoggerContext context) { - updateType = UpdateType.STOP;; - this.context = context; - } - - public boolean isResetResistant() { - return resetResistant; - } - - public void onLevelChange(Logger logger, Level level) { - updateType = UpdateType.LEVEL_CHANGE; - this.logger = logger; - this.level = level; - } - + enum UpdateType { + NONE, START, RESET, STOP, LEVEL_CHANGE + }; + + UpdateType updateType = UpdateType.NONE; + LoggerContext context; + Logger logger; + Level level; + + boolean resetResistant; + + public void setResetResistant(boolean resetResistant) { + this.resetResistant = resetResistant; + } + + public void onReset(LoggerContext context) { + updateType = UpdateType.RESET; + this.context = context; + + } + + public void onStart(LoggerContext context) { + updateType = UpdateType.START; + ; + this.context = context; + } + + public void onStop(LoggerContext context) { + updateType = UpdateType.STOP; + ; + this.context = context; + } + + public boolean isResetResistant() { + return resetResistant; + } + + public void onLevelChange(Logger logger, Level level) { + updateType = UpdateType.LEVEL_CHANGE; + this.logger = logger; + this.level = level; + } + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/BogusClassLoader.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/BogusClassLoader.java index 98a5f278ba4fe7832d1c560037b858fe905c2b02..8131c94b67748cada955992b2f71385e7ea92049 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/BogusClassLoader.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/BogusClassLoader.java @@ -24,29 +24,28 @@ import java.net.URLClassLoader; */ public class BogusClassLoader extends URLClassLoader { - public BogusClassLoader(URL[] urls) { - super(urls); - } - - public BogusClassLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - } - - public Class loadClass(String name) throws ClassNotFoundException { - return loadClass(name, false); - } - - /** - * Throw NoClassDefFoundError if the requested class contains the string - * "Bogus". Otherwise, delegate to super-class. - */ - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { - - if (name.contains("Bogus")) { - throw new NoClassDefFoundError(); + public BogusClassLoader(URL[] urls) { + super(urls); } - return super.loadClass(name, resolve); - } + public BogusClassLoader(URL[] urls, ClassLoader parent) { + super(urls, parent); + } + + public Class loadClass(String name) throws ClassNotFoundException { + return loadClass(name, false); + } + + /** + * Throw NoClassDefFoundError if the requested class contains the string + * "Bogus". Otherwise, delegate to super-class. + */ + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + + if (name.contains("Bogus")) { + throw new NoClassDefFoundError(); + } + + return super.loadClass(name, resolve); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/CPDCSpecial.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/CPDCSpecial.java index 084f3a61bbb69758e78f2fd0badc1f113a0cbc8c..2ec9397ab7912376302015dfd812e901b6413d6d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/CPDCSpecial.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/CPDCSpecial.java @@ -15,10 +15,10 @@ package ch.qos.logback.classic.spi; public interface CPDCSpecial { - void doTest(); + void doTest(); - Throwable getThrowable(); + Throwable getThrowable(); - IThrowableProxy getThrowableProxy(); + IThrowableProxy getThrowableProxy(); } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/CallerDataTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/CallerDataTest.java index c174e2d98f24a0c7ce9d89fe71b5cea15068c366..b6f26c373f2ee614d308c633a71a57823fc75b97 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/CallerDataTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/CallerDataTest.java @@ -19,30 +19,29 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; -public class CallerDataTest { +public class CallerDataTest { + @Test + public void testBasic() { + Throwable t = new Throwable(); + StackTraceElement[] steArray = t.getStackTrace(); + + StackTraceElement[] cda = CallerData.extract(t, CallerDataTest.class.getName(), 50, null); + assertNotNull(cda); + assertTrue(cda.length > 0); + assertEquals(steArray.length - 1, cda.length); + } + + /** + * This test verifies that in case caller data cannot be + * extracted, CallerData.extract does not throw an exception + * + */ + @Test + public void testDeferredProcessing() { + StackTraceElement[] cda = CallerData.extract(new Throwable(), "com.inexistent.foo", 10, null); + assertNotNull(cda); + assertEquals(0, cda.length); + } - @Test - public void testBasic() { - Throwable t = new Throwable(); - StackTraceElement[] steArray = t.getStackTrace(); - - StackTraceElement[] cda = CallerData.extract(t, CallerDataTest.class.getName(), 50, null); - assertNotNull(cda); - assertTrue(cda.length > 0); - assertEquals(steArray.length - 1, cda.length); - } - - /** - * This test verifies that in case caller data cannot be - * extracted, CallerData.extract does not throw an exception - * - */ - @Test - public void testDeferredProcessing() { - StackTraceElement[] cda = CallerData.extract(new Throwable(), "com.inexistent.foo", 10, null); - assertNotNull(cda); - assertEquals(0, cda.length); - } - } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/ContextListenerTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/ContextListenerTest.java index 2ac14c7c4ed0ea0698bd5b1f1bfd3185b2cfd1c2..ed40c4ad7015c0a3d78960710298c82f91366741 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/ContextListenerTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/ContextListenerTest.java @@ -25,59 +25,59 @@ import ch.qos.logback.classic.spi.BasicContextListener.UpdateType; public class ContextListenerTest { - LoggerContext context; - BasicContextListener listener; + LoggerContext context; + BasicContextListener listener; - @Before - public void setUp() throws Exception { - context = new LoggerContext(); - listener = new BasicContextListener(); - context.addListener(listener); - } + @Before + public void setUp() throws Exception { + context = new LoggerContext(); + listener = new BasicContextListener(); + context.addListener(listener); + } - @Test - public void testNotifyOnReset() { - context.reset(); - assertEquals(UpdateType.RESET, listener.updateType); - assertEquals(listener.context, context); - } + @Test + public void testNotifyOnReset() { + context.reset(); + assertEquals(UpdateType.RESET, listener.updateType); + assertEquals(listener.context, context); + } - @Test - public void testNotifyOnStopResistant() { - listener.setResetResistant(true); - context.stop(); - assertEquals(UpdateType.STOP, listener.updateType); - assertEquals(listener.context, context); - } + @Test + public void testNotifyOnStopResistant() { + listener.setResetResistant(true); + context.stop(); + assertEquals(UpdateType.STOP, listener.updateType); + assertEquals(listener.context, context); + } - @Test - public void testNotifyOnStopNotResistant() { - context.stop(); - assertEquals(UpdateType.RESET, listener.updateType); - assertEquals(listener.context, context); - } + @Test + public void testNotifyOnStopNotResistant() { + context.stop(); + assertEquals(UpdateType.RESET, listener.updateType); + assertEquals(listener.context, context); + } - @Test - public void testNotifyOnStart() { - context.start(); - assertEquals(UpdateType.START, listener.updateType); - assertEquals(listener.context, context); - } + @Test + public void testNotifyOnStart() { + context.start(); + assertEquals(UpdateType.START, listener.updateType); + assertEquals(listener.context, context); + } - void checkLevelChange(String loggerName, Level level) { - Logger logger = context.getLogger(loggerName); - logger.setLevel(level); + void checkLevelChange(String loggerName, Level level) { + Logger logger = context.getLogger(loggerName); + logger.setLevel(level); - assertEquals(UpdateType.LEVEL_CHANGE, listener.updateType); - assertEquals(listener.logger, logger); - assertEquals(listener.level, level); + assertEquals(UpdateType.LEVEL_CHANGE, listener.updateType); + assertEquals(listener.logger, logger); + assertEquals(listener.level, level); - } + } - @Test - public void testLevelChange() { - checkLevelChange("a", Level.INFO); - checkLevelChange("a.b", Level.ERROR); - checkLevelChange("a.b.c", Level.DEBUG); - } + @Test + public void testLevelChange() { + checkLevelChange("a", Level.INFO); + checkLevelChange("a.b", Level.ERROR); + checkLevelChange("a.b.c", Level.DEBUG); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/DummyThrowableProxy.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/DummyThrowableProxy.java index 908811eec34289d841610b71bc4c44aaa4b788fc..8a416f65241cc9b970798fce86be82d64e21c32d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/DummyThrowableProxy.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/DummyThrowableProxy.java @@ -14,52 +14,59 @@ package ch.qos.logback.classic.spi; public class DummyThrowableProxy implements IThrowableProxy { - - private String className; - private String message; - private int commonFramesCount; - private StackTraceElementProxy[] stackTraceElementProxyArray; - private IThrowableProxy cause; - private IThrowableProxy[] suppressed; - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - public int getCommonFrames() { - return commonFramesCount; - } - public void setCommonFramesCount(int commonFramesCount) { - this.commonFramesCount = commonFramesCount; - } + private String className; + private String message; + private int commonFramesCount; + private StackTraceElementProxy[] stackTraceElementProxyArray; + private IThrowableProxy cause; + private IThrowableProxy[] suppressed; - public StackTraceElementProxy[] getStackTraceElementProxyArray() { - return stackTraceElementProxyArray; - } - public void setStackTraceElementProxyArray( - StackTraceElementProxy[] stackTraceElementProxyArray) { - this.stackTraceElementProxyArray = stackTraceElementProxyArray; - } - public IThrowableProxy getCause() { - return cause; - } - public void setCause(IThrowableProxy cause) { - this.cause = cause; - } + public String getClassName() { + return className; + } - public IThrowableProxy[] getSuppressed() { - return suppressed; - } + public void setClassName(String className) { + this.className = className; + } - public void setSuppressed(IThrowableProxy[] suppressed) { - this.suppressed = suppressed; - } + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public int getCommonFrames() { + return commonFramesCount; + } + + public void setCommonFramesCount(int commonFramesCount) { + this.commonFramesCount = commonFramesCount; + } + + public StackTraceElementProxy[] getStackTraceElementProxyArray() { + return stackTraceElementProxyArray; + } + + public void setStackTraceElementProxyArray(StackTraceElementProxy[] stackTraceElementProxyArray) { + this.stackTraceElementProxyArray = stackTraceElementProxyArray; + } + + public IThrowableProxy getCause() { + return cause; + } + + public void setCause(IThrowableProxy cause) { + this.cause = cause; + } + + public IThrowableProxy[] getSuppressed() { + return suppressed; + } + + public void setSuppressed(IThrowableProxy[] suppressed) { + this.suppressed = suppressed; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LocalFirstClassLoader.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LocalFirstClassLoader.java index 6406c15bc2a3370fce4f6f2aedd77a6e9266207e..140c5c338f83415a890b4f7854d24d852b8ef5a4 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LocalFirstClassLoader.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LocalFirstClassLoader.java @@ -24,56 +24,55 @@ import java.net.URLClassLoader; */ public class LocalFirstClassLoader extends URLClassLoader { - public LocalFirstClassLoader(URL[] urls) { - super(urls); - } + public LocalFirstClassLoader(URL[] urls) { + super(urls); + } + + public LocalFirstClassLoader(URL[] urls, ClassLoader parent) { + super(urls, parent); + } - public LocalFirstClassLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - } + public void addURL(URL url) { + super.addURL(url); + } - public void addURL(URL url) { - super.addURL(url); - } + public Class loadClass(String name) throws ClassNotFoundException { + return loadClass(name, false); + } - public Class loadClass(String name) throws ClassNotFoundException { - return loadClass(name, false); - } + /** + * We override the parent-first behavior established by java.lang.Classloader. + * + * The implementation is surprisingly straightforward. + */ + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - /** - * We override the parent-first behavior established by java.lang.Classloader. - * - * The implementation is surprisingly straightforward. - */ - protected Class loadClass(String name, boolean resolve) - throws ClassNotFoundException { + // First, check if the class has already been loaded + Class c = findLoadedClass(name); - // First, check if the class has already been loaded - Class c = findLoadedClass(name); + // if not loaded, search the local (child) resources + if (c == null) { + try { + c = findClass(name); + } catch (ClassNotFoundException cnfe) { + // ignore + } + } - // if not loaded, search the local (child) resources - if (c == null) { - try { - c = findClass(name); - } catch (ClassNotFoundException cnfe) { - // ignore - } - } + // if we could not find it, delegate to parent + // Note that we don't attempt to catch any ClassNotFoundException + if (c == null) { + if (getParent() != null) { + c = getParent().loadClass(name); + } else { + c = getSystemClassLoader().loadClass(name); + } + } - // if we could not find it, delegate to parent - // Note that we don't attempt to catch any ClassNotFoundException - if (c == null) { - if (getParent() != null) { - c = getParent().loadClass(name); - } else { - c = getSystemClassLoader().loadClass(name); - } - } + if (resolve) { + resolveClass(c); + } - if (resolve) { - resolveClass(c); + return c; } - - return c; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggerComparatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggerComparatorTest.java index 5d34617d1d70a96397f3b44666b5a7acb4b9f467..7472ed5b792d403d0a8d857f6bffc368b6b504dd 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggerComparatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggerComparatorTest.java @@ -20,32 +20,29 @@ import static org.junit.Assert.*; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; - public class LoggerComparatorTest { - LoggerComparator comparator = new LoggerComparator(); - LoggerContext lc = new LoggerContext(); - - Logger root = lc.getLogger("root"); - - Logger a = lc.getLogger("a"); - Logger b = lc.getLogger("b"); - - @Before - public void setUp() throws Exception { - - } - - - - @Test - public void testSmoke() { - assertEquals(0, comparator.compare(a, a)); - assertEquals(-1, comparator.compare(a, b)); - assertEquals(1, comparator.compare(b, a)); - assertEquals(-1, comparator.compare(root, a)); - // following two tests failed before bug #127 was fixed - assertEquals(1, comparator.compare(a, root)); - assertEquals(0, comparator.compare(root, root)); - } + LoggerComparator comparator = new LoggerComparator(); + LoggerContext lc = new LoggerContext(); + + Logger root = lc.getLogger("root"); + + Logger a = lc.getLogger("a"); + Logger b = lc.getLogger("b"); + + @Before + public void setUp() throws Exception { + + } + + @Test + public void testSmoke() { + assertEquals(0, comparator.compare(a, a)); + assertEquals(-1, comparator.compare(a, b)); + assertEquals(1, comparator.compare(b, a)); + assertEquals(-1, comparator.compare(root, a)); + // following two tests failed before bug #127 was fixed + assertEquals(1, comparator.compare(a, root)); + assertEquals(0, comparator.compare(root, root)); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationPerfTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationPerfTest.java index 2c204bee413f6e5dcd20c9150b1259ad6bc9e9c0..64a419b0f42ef4c5ea6454c4d6dc2625b75151ff 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationPerfTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationPerfTest.java @@ -47,95 +47,90 @@ import ch.qos.logback.core.CoreConstants; public class LoggingEventSerializationPerfTest { - static int LOOP_LEN = 10 * 1000; - - NOPOutputStream noos = new NOPOutputStream(); - ObjectOutputStream oos; - - @Before - public void setUp() throws Exception { - MDC.clear(); - oos = new ObjectOutputStream(noos); - } - - @After - public void tearDown() throws Exception { - } - - double doLoop(Builder builder, int loopLen) { - long start = System.nanoTime(); - int resetCounter = 0; - for (int i = 0; i < loopLen; i++) { - try { - ILoggingEvent le = (ILoggingEvent) builder.build(i); - oos.writeObject(LoggingEventVO.build(le)); - - oos.flush(); - if (++resetCounter >= CoreConstants.OOS_RESET_FREQUENCY) { - oos.reset(); - resetCounter = 0; - } + static int LOOP_LEN = 10 * 1000; - } catch (IOException ex) { - fail(ex.getMessage()); - } - } - long end = System.nanoTime(); - return (end - start) / (1.0d * loopLen); - } - - @Test - public void testPerformance() { - if (EnvUtilForTests.isLinux()) { - return; + NOPOutputStream noos = new NOPOutputStream(); + ObjectOutputStream oos; + + @Before + public void setUp() throws Exception { + MDC.clear(); + oos = new ObjectOutputStream(noos); } - TrivialLoggingEventBuilder builder = new TrivialLoggingEventBuilder(); - for (int i = 0; i < 3; i++) { - doLoop(builder, LOOP_LEN); - noos.reset(); + @After + public void tearDown() throws Exception { } - double rt = doLoop(builder, LOOP_LEN); - System.out - .println("average time per logging event " + rt + " nanoseconds"); - - long averageSize = (long) (noos.size() / (LOOP_LEN)); - System.out.println("noos size " + noos.size() + " average size=" - + averageSize); - double averageSizeLimit = 62.1; - - assertTrue("average size " + averageSize + " should be less than " - + averageSizeLimit, averageSizeLimit > averageSize); - - // the reference was computed on Orion (Ceki's computer) - long referencePerf = 5000; - BogoPerf.assertDuration(rt, referencePerf, CoreConstants.REFERENCE_BIPS); - } - - @Test - public void testPerformanceWithParameters() { - if (EnvUtilForTests.isLinux()) { - return; + + double doLoop(Builder builder, int loopLen) { + long start = System.nanoTime(); + int resetCounter = 0; + for (int i = 0; i < loopLen; i++) { + try { + ILoggingEvent le = (ILoggingEvent) builder.build(i); + oos.writeObject(LoggingEventVO.build(le)); + + oos.flush(); + if (++resetCounter >= CoreConstants.OOS_RESET_FREQUENCY) { + oos.reset(); + resetCounter = 0; + } + + } catch (IOException ex) { + fail(ex.getMessage()); + } + } + long end = System.nanoTime(); + return (end - start) / (1.0d * loopLen); } - LoggingEventWithParametersBuilder builder = new LoggingEventWithParametersBuilder(); - // warm up - for (int i = 0; i < 3; i++) { - doLoop(builder, LOOP_LEN); - noos.reset(); + @Test + public void testPerformance() { + if (EnvUtilForTests.isLinux()) { + return; + } + TrivialLoggingEventBuilder builder = new TrivialLoggingEventBuilder(); + + for (int i = 0; i < 3; i++) { + doLoop(builder, LOOP_LEN); + noos.reset(); + } + double rt = doLoop(builder, LOOP_LEN); + System.out.println("average time per logging event " + rt + " nanoseconds"); + + long averageSize = (long) (noos.size() / (LOOP_LEN)); + System.out.println("noos size " + noos.size() + " average size=" + averageSize); + double averageSizeLimit = 62.1; + + assertTrue("average size " + averageSize + " should be less than " + averageSizeLimit, averageSizeLimit > averageSize); + + // the reference was computed on Orion (Ceki's computer) + long referencePerf = 5000; + BogoPerf.assertDuration(rt, referencePerf, CoreConstants.REFERENCE_BIPS); } - double rt = doLoop(builder, LOOP_LEN); - long averageSize = (long) (noos.size() / (LOOP_LEN)); - System.out.println("noos size " + noos.size() + " average size=" - + averageSize); + @Test + public void testPerformanceWithParameters() { + if (EnvUtilForTests.isLinux()) { + return; + } + LoggingEventWithParametersBuilder builder = new LoggingEventWithParametersBuilder(); + + // warm up + for (int i = 0; i < 3; i++) { + doLoop(builder, LOOP_LEN); + noos.reset(); + } + double rt = doLoop(builder, LOOP_LEN); + long averageSize = (long) (noos.size() / (LOOP_LEN)); + + System.out.println("noos size " + noos.size() + " average size=" + averageSize); - double averageSizeLimit = 160; - assertTrue("averageSize " + averageSize + " should be less than " - + averageSizeLimit, averageSizeLimit > averageSize); + double averageSizeLimit = 160; + assertTrue("averageSize " + averageSize + " should be less than " + averageSizeLimit, averageSizeLimit > averageSize); - // the reference was computed on Orion (Ceki's computer) - long referencePerf = 7000; - BogoPerf.assertDuration(rt, referencePerf, CoreConstants.REFERENCE_BIPS); - } + // the reference was computed on Orion (Ceki's computer) + long referencePerf = 7000; + BogoPerf.assertDuration(rt, referencePerf, CoreConstants.REFERENCE_BIPS); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationTest.java index b3c0d090523ca865b2ee141c6be15ca8d9343790..17a317ca7a7df02aef01030d112d83a23203e5b8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventSerializationTest.java @@ -38,179 +38,174 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; public class LoggingEventSerializationTest { - LoggerContext lc; - Logger logger; - - ByteArrayOutputStream bos; - ObjectOutputStream oos; - ObjectInputStream inputStream; - PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); - - @Before - public void setUp() throws Exception { - lc = new LoggerContext(); - lc.setName("testContext"); - logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); - // create the byte output stream - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - } - - @After - public void tearDown() throws Exception { - lc = null; - logger = null; - oos.close(); - } - - @Test - public void smoke() throws Exception { - ILoggingEvent event = createLoggingEvent(); - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - } - - @Test - public void context() throws Exception { - lc.putProperty("testKey", "testValue"); - ILoggingEvent event = createLoggingEvent(); - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - - assertNotNull(remoteEvent.getLoggerName()); - assertEquals(Logger.ROOT_LOGGER_NAME, remoteEvent.getLoggerName()); - - LoggerContextVO loggerContextRemoteView = remoteEvent.getLoggerContextVO(); - assertNotNull(loggerContextRemoteView); - assertEquals("testContext", loggerContextRemoteView.getName()); - Map props = loggerContextRemoteView.getPropertyMap(); - assertNotNull(props); - assertEquals("testValue", props.get("testKey")); - } - - @Test - public void MDC() throws Exception { - MDC.put("key", "testValue"); - ILoggingEvent event = createLoggingEvent(); - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - Map MDCPropertyMap = remoteEvent.getMDCPropertyMap(); - assertEquals("testValue", MDCPropertyMap.get("key")); - } - - @Test - public void updatedMDC() throws Exception { - MDC.put("key", "testValue"); - ILoggingEvent event1 = createLoggingEvent(); - Serializable s1 = pst.transform(event1); - oos.writeObject(s1); - - MDC.put("key", "updatedTestValue"); - ILoggingEvent event2 = createLoggingEvent(); - Serializable s2 = pst.transform(event2); - oos.writeObject(s2); - - // create the input stream based on the ouput stream - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - inputStream = new ObjectInputStream(bis); - - // skip over one object - inputStream.readObject(); - ILoggingEvent remoteEvent2 = (ILoggingEvent) inputStream.readObject(); - - // We observe the second logging event. It should provide us with - // the updated MDC property. - Map MDCPropertyMap = remoteEvent2.getMDCPropertyMap(); - assertEquals("updatedTestValue", MDCPropertyMap.get("key")); - } - - @Test - public void nonSerializableParameters() throws Exception { - LoggingEvent event = createLoggingEvent(); - LuckyCharms lucky0 = new LuckyCharms(0); - event.setArgumentArray(new Object[] { lucky0, null }); - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - - Object[] aa = remoteEvent.getArgumentArray(); - assertNotNull(aa); - assertEquals(2, aa.length); - assertEquals("LC(0)", aa[0]); - assertNull(aa[1]); - } - - @Test - public void _Throwable() throws Exception { - LoggingEvent event = createLoggingEvent(); - Throwable throwable = new Throwable("just testing"); - ThrowableProxy tp = new ThrowableProxy(throwable); - event.setThrowableProxy(tp); - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - } - - @Test - public void extendendeThrowable() throws Exception { - LoggingEvent event = createLoggingEvent(); - Throwable throwable = new Throwable("just testing"); - ThrowableProxy tp = new ThrowableProxy(throwable); - event.setThrowableProxy(tp); - tp.calculatePackagingData(); - - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - } - - @Test - public void serializeLargeArgs() throws Exception { - - StringBuilder buffer = new StringBuilder(); - for (int i = 0; i < 100000; i++) { - buffer.append("X"); + LoggerContext lc; + Logger logger; + + ByteArrayOutputStream bos; + ObjectOutputStream oos; + ObjectInputStream inputStream; + PreSerializationTransformer pst = new LoggingEventPreSerializationTransformer(); + + @Before + public void setUp() throws Exception { + lc = new LoggerContext(); + lc.setName("testContext"); + logger = lc.getLogger(Logger.ROOT_LOGGER_NAME); + // create the byte output stream + bos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bos); + } + + @After + public void tearDown() throws Exception { + lc = null; + logger = null; + oos.close(); + } + + @Test + public void smoke() throws Exception { + ILoggingEvent event = createLoggingEvent(); + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + } + + @Test + public void context() throws Exception { + lc.putProperty("testKey", "testValue"); + ILoggingEvent event = createLoggingEvent(); + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + + assertNotNull(remoteEvent.getLoggerName()); + assertEquals(Logger.ROOT_LOGGER_NAME, remoteEvent.getLoggerName()); + + LoggerContextVO loggerContextRemoteView = remoteEvent.getLoggerContextVO(); + assertNotNull(loggerContextRemoteView); + assertEquals("testContext", loggerContextRemoteView.getName()); + Map props = loggerContextRemoteView.getPropertyMap(); + assertNotNull(props); + assertEquals("testValue", props.get("testKey")); + } + + @Test + public void MDC() throws Exception { + MDC.put("key", "testValue"); + ILoggingEvent event = createLoggingEvent(); + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + Map MDCPropertyMap = remoteEvent.getMDCPropertyMap(); + assertEquals("testValue", MDCPropertyMap.get("key")); + } + + @Test + public void updatedMDC() throws Exception { + MDC.put("key", "testValue"); + ILoggingEvent event1 = createLoggingEvent(); + Serializable s1 = pst.transform(event1); + oos.writeObject(s1); + + MDC.put("key", "updatedTestValue"); + ILoggingEvent event2 = createLoggingEvent(); + Serializable s2 = pst.transform(event2); + oos.writeObject(s2); + + // create the input stream based on the ouput stream + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + inputStream = new ObjectInputStream(bis); + + // skip over one object + inputStream.readObject(); + ILoggingEvent remoteEvent2 = (ILoggingEvent) inputStream.readObject(); + + // We observe the second logging event. It should provide us with + // the updated MDC property. + Map MDCPropertyMap = remoteEvent2.getMDCPropertyMap(); + assertEquals("updatedTestValue", MDCPropertyMap.get("key")); + } + + @Test + public void nonSerializableParameters() throws Exception { + LoggingEvent event = createLoggingEvent(); + LuckyCharms lucky0 = new LuckyCharms(0); + event.setArgumentArray(new Object[] { lucky0, null }); + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + + Object[] aa = remoteEvent.getArgumentArray(); + assertNotNull(aa); + assertEquals(2, aa.length); + assertEquals("LC(0)", aa[0]); + assertNull(aa[1]); + } + + @Test + public void _Throwable() throws Exception { + LoggingEvent event = createLoggingEvent(); + Throwable throwable = new Throwable("just testing"); + ThrowableProxy tp = new ThrowableProxy(throwable); + event.setThrowableProxy(tp); + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + } + + @Test + public void extendendeThrowable() throws Exception { + LoggingEvent event = createLoggingEvent(); + Throwable throwable = new Throwable("just testing"); + ThrowableProxy tp = new ThrowableProxy(throwable); + event.setThrowableProxy(tp); + tp.calculatePackagingData(); + + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + } + + @Test + public void serializeLargeArgs() throws Exception { + + StringBuilder buffer = new StringBuilder(); + for (int i = 0; i < 100000; i++) { + buffer.append("X"); + } + String largeString = buffer.toString(); + Object[] argArray = new Object[] { new LuckyCharms(2), largeString }; + + LoggingEvent event = createLoggingEvent(); + event.setArgumentArray(argArray); + + ILoggingEvent remoteEvent = writeAndRead(event); + checkForEquality(event, remoteEvent); + Object[] aa = remoteEvent.getArgumentArray(); + assertNotNull(aa); + assertEquals(2, aa.length); + String stringBack = (String) aa[1]; + assertEquals(largeString, stringBack); + } + + private LoggingEvent createLoggingEvent() { + return new LoggingEvent(this.getClass().getName(), logger, Level.DEBUG, "test message", null, null); + } + + private void checkForEquality(ILoggingEvent original, ILoggingEvent afterSerialization) { + assertEquals(original.getLevel(), afterSerialization.getLevel()); + assertEquals(original.getFormattedMessage(), afterSerialization.getFormattedMessage()); + assertEquals(original.getMessage(), afterSerialization.getMessage()); + + System.out.println(); + + ThrowableProxyVO witness = ThrowableProxyVO.build(original.getThrowableProxy()); + assertEquals(witness, afterSerialization.getThrowableProxy()); + + } + + private ILoggingEvent writeAndRead(ILoggingEvent event) throws IOException, ClassNotFoundException { + Serializable ser = pst.transform(event); + oos.writeObject(ser); + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + inputStream = new ObjectInputStream(bis); + + return (ILoggingEvent) inputStream.readObject(); } - String largeString = buffer.toString(); - Object[] argArray = new Object[] { new LuckyCharms(2), largeString }; - - LoggingEvent event = createLoggingEvent(); - event.setArgumentArray(argArray); - - ILoggingEvent remoteEvent = writeAndRead(event); - checkForEquality(event, remoteEvent); - Object[] aa = remoteEvent.getArgumentArray(); - assertNotNull(aa); - assertEquals(2, aa.length); - String stringBack = (String) aa[1]; - assertEquals(largeString, stringBack); - } - - private LoggingEvent createLoggingEvent() { - return new LoggingEvent(this.getClass().getName(), logger, - Level.DEBUG, "test message", null, null); - } - - private void checkForEquality(ILoggingEvent original, - ILoggingEvent afterSerialization) { - assertEquals(original.getLevel(), afterSerialization.getLevel()); - assertEquals(original.getFormattedMessage(), afterSerialization - .getFormattedMessage()); - assertEquals(original.getMessage(), afterSerialization.getMessage()); - - System.out.println(); - - ThrowableProxyVO witness = ThrowableProxyVO.build(original - .getThrowableProxy()); - assertEquals(witness, afterSerialization.getThrowableProxy()); - - } - - private ILoggingEvent writeAndRead(ILoggingEvent event) throws IOException, - ClassNotFoundException { - Serializable ser = pst.transform(event); - oos.writeObject(ser); - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - inputStream = new ObjectInputStream(bis); - - return (ILoggingEvent) inputStream.readObject(); - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventTest.java index 985b26ce24c9eb0d5f34f2d5e24f6bf845340b2d..e4ad6ec86b90a92879569fe4f68d6ac5196710a4 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LoggingEventTest.java @@ -24,55 +24,52 @@ import static org.junit.Assert.assertEquals; public class LoggingEventTest { - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - @Before - public void setUp() { - } + @Before + public void setUp() { + } + @Test + public void testFormattingOneArg() { + String message = "x={}"; + Throwable throwable = null; + Object[] argArray = new Object[] { 12 }; - @Test - public void testFormattingOneArg() { - String message = "x={}"; - Throwable throwable = null; - Object[] argArray = new Object[] {12}; + LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); + assertNull(event.formattedMessage); + assertEquals("x=12", event.getFormattedMessage()); + } - LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); - assertNull(event.formattedMessage); - assertEquals("x=12", event.getFormattedMessage()); - } + @Test + public void testFormattingTwoArg() { + String message = "{}-{}"; + Throwable throwable = null; + Object[] argArray = new Object[] { 12, 13 }; + LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); + assertNull(event.formattedMessage); + assertEquals("12-13", event.getFormattedMessage()); + } - @Test - public void testFormattingTwoArg() { - String message = "{}-{}"; - Throwable throwable = null; - Object[] argArray = new Object[] {12, 13}; - LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); + @Test + public void testNoFormattingWithArgs() { + String message = "testNoFormatting"; + Throwable throwable = null; + Object[] argArray = new Object[] { 12, 13 }; + LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); + assertNull(event.formattedMessage); + assertEquals(message, event.getFormattedMessage()); + } - assertNull(event.formattedMessage); - assertEquals("12-13", event.getFormattedMessage()); - } - - - @Test - public void testNoFormattingWithArgs() { - String message = "testNoFormatting"; - Throwable throwable = null; - Object[] argArray = new Object[] {12, 13}; - LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); - assertNull(event.formattedMessage); - assertEquals(message, event.getFormattedMessage()); - } - - @Test - public void testNoFormattingWithoutArgs() { - String message = "testNoFormatting"; - Throwable throwable = null; - Object[] argArray = null; - LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); - assertNull(event.formattedMessage); - assertEquals(message, event.getFormattedMessage()); - } + @Test + public void testNoFormattingWithoutArgs() { + String message = "testNoFormatting"; + Throwable throwable = null; + Object[] argArray = null; + LoggingEvent event = new LoggingEvent("", logger, Level.INFO, message, throwable, argArray); + assertNull(event.formattedMessage); + assertEquals(message, event.getFormattedMessage()); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LuckyCharms.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LuckyCharms.java index 8c23f4f2b4e5be6206f2a5bb9153787ab7746e56..8e70339ac8c74682c5169d2506c0a0ac494a8fbf 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/LuckyCharms.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/LuckyCharms.java @@ -15,14 +15,14 @@ package ch.qos.logback.classic.spi; // non serializable object public class LuckyCharms { - int id; - - LuckyCharms(int id) { - this.id= id; - } - - @Override - public String toString() { - return "LC("+id+")"; - } + int id; + + LuckyCharms(int id) { + this.id = id; + } + + @Override + public String toString() { + return "LC(" + id + ")"; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackageTest.java index bc9a4c235722647a381e8a99915a84203e5c54b3..e19c6de3adda09122eaaa2522637b64536f070c9 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackageTest.java @@ -18,9 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { ContextListenerTest.class, CallerDataTest.class, - LoggerComparatorTest.class, LoggingEventTest.class, LoggingEventSerializationTest.class, - LoggingEventSerializationPerfTest.class, ThrowableProxyTest.class, - PackagingDataCalculatorTest.class }) -public class PackageTest { +@SuiteClasses({ ContextListenerTest.class, CallerDataTest.class, LoggerComparatorTest.class, LoggingEventTest.class, LoggingEventSerializationTest.class, + LoggingEventSerializationPerfTest.class, ThrowableProxyTest.class, PackagingDataCalculatorTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackagingDataCalculatorTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackagingDataCalculatorTest.java index f567e2f50def89bc209bedaf625bce731ae96a7c..0cb8d38a61475cc1b75f27f1382f5266d4c4d6bf 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackagingDataCalculatorTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PackagingDataCalculatorTest.java @@ -27,100 +27,94 @@ import ch.qos.logback.core.util.SystemInfo; public class PackagingDataCalculatorTest { - public void verify(ThrowableProxy tp) { - for (StackTraceElementProxy step : tp.getStackTraceElementProxyArray()) { - if (step != null) { - assertNotNull(step.getClassPackagingData()); - } + public void verify(ThrowableProxy tp) { + for (StackTraceElementProxy step : tp.getStackTraceElementProxyArray()) { + if (step != null) { + assertNotNull(step.getClassPackagingData()); + } + } } - } - - @Test - public void smoke() throws Exception { - Throwable t = new Throwable("x"); - ThrowableProxy tp = new ThrowableProxy(t); - PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); - pdc.calculate(tp); - verify(tp); - tp.fullDump(); - } - - @Test - public void nested() throws Exception { - Throwable t = TestHelper.makeNestedException(3); - ThrowableProxy tp = new ThrowableProxy(t); - PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); - pdc.calculate(tp); - verify(tp); - } - - public void doCalculateClassPackagingData( - boolean withClassPackagingCalculation) { - try { - throw new Exception("testing"); - } catch (Throwable e) { - ThrowableProxy tp = new ThrowableProxy(e); - if (withClassPackagingCalculation) { + + @Test + public void smoke() throws Exception { + Throwable t = new Throwable("x"); + ThrowableProxy tp = new ThrowableProxy(t); + PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); + pdc.calculate(tp); + verify(tp); + tp.fullDump(); + } + + @Test + public void nested() throws Exception { + Throwable t = TestHelper.makeNestedException(3); + ThrowableProxy tp = new ThrowableProxy(t); PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); pdc.calculate(tp); - } + verify(tp); + } + + public void doCalculateClassPackagingData(boolean withClassPackagingCalculation) { + try { + throw new Exception("testing"); + } catch (Throwable e) { + ThrowableProxy tp = new ThrowableProxy(e); + if (withClassPackagingCalculation) { + PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); + pdc.calculate(tp); + } + } } - } - double loop(int len, boolean withClassPackagingCalculation) { - long start = System.nanoTime(); - for (int i = 0; i < len; i++) { - doCalculateClassPackagingData(withClassPackagingCalculation); + double loop(int len, boolean withClassPackagingCalculation) { + long start = System.nanoTime(); + for (int i = 0; i < len; i++) { + doCalculateClassPackagingData(withClassPackagingCalculation); + } + return (1.0 * System.nanoTime() - start) / len / 1000; } - return (1.0 * System.nanoTime() - start) / len / 1000; - } - @Test - public void perfTest() { - int len = 1000; - loop(len, false); - loop(len, true); + @Test + public void perfTest() { + int len = 1000; + loop(len, false); + loop(len, true); + + double d0 = loop(len, false); + System.out.println("without packaging info " + d0 + " microseconds"); - double d0 = loop(len, false); - System.out.println("without packaging info " + d0 + " microseconds"); + double d1 = loop(len, true); + System.out.println("with packaging info " + d1 + " microseconds"); - double d1 = loop(len, true); - System.out.println("with packaging info " + d1 + " microseconds"); + int slackFactor = 8; + if (!SystemInfo.getJavaVendor().contains("Sun")) { + // be more lenient with other JDKs + slackFactor = 15; + } + assertTrue("computing class packaging data (" + d1 + ") should have been less than " + slackFactor + + " times the time it takes to process an exception " + (d0 * slackFactor), d0 * slackFactor > d1); + + } + + private ClassLoader makeBogusClassLoader() throws MalformedURLException { + ClassLoader currentClassLoader = this.getClass().getClassLoader(); + return new BogusClassLoader(new URL[] {}, currentClassLoader); + } + + @Test + // Test http://jira.qos.ch/browse/LBCLASSIC-125 + public void noClassDefFoundError_LBCLASSIC_125Test() throws MalformedURLException { + ClassLoader cl = (URLClassLoader) makeBogusClassLoader(); + Thread.currentThread().setContextClassLoader(cl); + Throwable t = new Throwable("x"); + ThrowableProxy tp = new ThrowableProxy(t); + StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); + StackTraceElement bogusSTE = new StackTraceElement("com.Bogus", "myMethod", "myFile", 12); + stepArray[0] = new StackTraceElementProxy(bogusSTE); + PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); + // NoClassDefFoundError should be caught + pdc.calculate(tp); - int slackFactor = 8; - if (!SystemInfo.getJavaVendor().contains("Sun")) { - // be more lenient with other JDKs - slackFactor = 15; } - assertTrue("computing class packaging data (" + d1 - + ") should have been less than " + slackFactor - + " times the time it takes to process an exception " - + (d0 * slackFactor), d0 * slackFactor > d1); - - } - - private ClassLoader makeBogusClassLoader() throws MalformedURLException { - ClassLoader currentClassLoader = this.getClass().getClassLoader(); - return new BogusClassLoader(new URL[] {}, - currentClassLoader); - } - - @Test - // Test http://jira.qos.ch/browse/LBCLASSIC-125 - public void noClassDefFoundError_LBCLASSIC_125Test() - throws MalformedURLException { - ClassLoader cl = (URLClassLoader) makeBogusClassLoader(); - Thread.currentThread().setContextClassLoader(cl); - Throwable t = new Throwable("x"); - ThrowableProxy tp = new ThrowableProxy(t); - StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray(); - StackTraceElement bogusSTE = new StackTraceElement("com.Bogus", "myMethod", - "myFile", 12); - stepArray[0] = new StackTraceElementProxy(bogusSTE); - PackagingDataCalculator pdc = tp.getPackagingDataCalculator(); - // NoClassDefFoundError should be caught - pdc.calculate(tp); - - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PubLoggingEventVO.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PubLoggingEventVO.java index 6d8a9caa7df6fadcc50db90820169f0e2b84b939..775854cfdcb242b14c0633aa04d809421989c8e7 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/PubLoggingEventVO.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/PubLoggingEventVO.java @@ -31,209 +31,206 @@ import ch.qos.logback.classic.Level; */ public class PubLoggingEventVO implements ILoggingEvent, Serializable { - private static final long serialVersionUID = -3385765861078946218L; + private static final long serialVersionUID = -3385765861078946218L; - private static final int NULL_ARGUMENT_ARRAY = -1; - private static final String NULL_ARGUMENT_ARRAY_ELEMENT = "NULL_ARGUMENT_ARRAY_ELEMENT"; + private static final int NULL_ARGUMENT_ARRAY = -1; + private static final String NULL_ARGUMENT_ARRAY_ELEMENT = "NULL_ARGUMENT_ARRAY_ELEMENT"; - public String threadName; - public String loggerName; - public LoggerContextVO loggerContextVO; + public String threadName; + public String loggerName; + public LoggerContextVO loggerContextVO; - public transient Level level; - public String message; + public transient Level level; + public String message; - private transient String formattedMessage; + private transient String formattedMessage; - public Object[] argumentArray; + public Object[] argumentArray; - public IThrowableProxy throwableProxy; - public StackTraceElement[] callerDataArray; - public Marker marker; - public Map mdcPropertyMap; - public long timeStamp; + public IThrowableProxy throwableProxy; + public StackTraceElement[] callerDataArray; + public Marker marker; + public Map mdcPropertyMap; + public long timeStamp; - public String getThreadName() { - return threadName; - } - - public LoggerContextVO getLoggerContextVO() { - return loggerContextVO; - } - - public String getLoggerName() { - return loggerName; - } + public String getThreadName() { + return threadName; + } - public Level getLevel() { - return level; - } + public LoggerContextVO getLoggerContextVO() { + return loggerContextVO; + } - public String getMessage() { - return message; - } + public String getLoggerName() { + return loggerName; + } - public String getFormattedMessage() { - if (formattedMessage != null) { - return formattedMessage; + public Level getLevel() { + return level; } - if (argumentArray != null) { - formattedMessage = MessageFormatter.arrayFormat(message, argumentArray) - .getMessage(); - } else { - formattedMessage = message; + public String getMessage() { + return message; } - return formattedMessage; - } + public String getFormattedMessage() { + if (formattedMessage != null) { + return formattedMessage; + } + + if (argumentArray != null) { + formattedMessage = MessageFormatter.arrayFormat(message, argumentArray).getMessage(); + } else { + formattedMessage = message; + } + + return formattedMessage; + } - public Object[] getArgumentArray() { - return argumentArray; - } + public Object[] getArgumentArray() { + return argumentArray; + } - public IThrowableProxy getThrowableProxy() { - return throwableProxy; - } + public IThrowableProxy getThrowableProxy() { + return throwableProxy; + } - public StackTraceElement[] getCallerData() { - return callerDataArray; - } + public StackTraceElement[] getCallerData() { + return callerDataArray; + } - public boolean hasCallerData() { - return callerDataArray != null; - } + public boolean hasCallerData() { + return callerDataArray != null; + } - public Marker getMarker() { - return marker; - } + public Marker getMarker() { + return marker; + } - public long getTimeStamp() { - return timeStamp; - } + public long getTimeStamp() { + return timeStamp; + } - public long getContextBirthTime() { - return loggerContextVO.getBirthTime(); - } + public long getContextBirthTime() { + return loggerContextVO.getBirthTime(); + } - public LoggerContextVO getContextLoggerRemoteView() { - return loggerContextVO; - } + public LoggerContextVO getContextLoggerRemoteView() { + return loggerContextVO; + } - public Map getMDCPropertyMap() { - return mdcPropertyMap; - } + public Map getMDCPropertyMap() { + return mdcPropertyMap; + } - public Map getMdc() { - return mdcPropertyMap; - } + public Map getMdc() { + return mdcPropertyMap; + } - public void prepareForDeferredProcessing() { - } + public void prepareForDeferredProcessing() { + } - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeInt(level.levelInt); - if (argumentArray != null) { - int len = argumentArray.length; - out.writeInt(len); - for (int i = 0; i < argumentArray.length; i++) { - if (argumentArray[i] != null) { - out.writeObject(argumentArray[i].toString()); + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeInt(level.levelInt); + if (argumentArray != null) { + int len = argumentArray.length; + out.writeInt(len); + for (int i = 0; i < argumentArray.length; i++) { + if (argumentArray[i] != null) { + out.writeObject(argumentArray[i].toString()); + } else { + out.writeObject(NULL_ARGUMENT_ARRAY_ELEMENT); + } + } } else { - out.writeObject(NULL_ARGUMENT_ARRAY_ELEMENT); + out.writeInt(NULL_ARGUMENT_ARRAY); } - } - } else { - out.writeInt(NULL_ARGUMENT_ARRAY); - } - - } - - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException { - in.defaultReadObject(); - int levelInt = in.readInt(); - level = Level.toLevel(levelInt); - - int argArrayLen = in.readInt(); - if (argArrayLen != NULL_ARGUMENT_ARRAY) { - argumentArray = new String[argArrayLen]; - for (int i = 0; i < argArrayLen; i++) { - Object val = in.readObject(); - if (!NULL_ARGUMENT_ARRAY_ELEMENT.equals(val)) { - argumentArray[i] = val; + + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + int levelInt = in.readInt(); + level = Level.toLevel(levelInt); + + int argArrayLen = in.readInt(); + if (argArrayLen != NULL_ARGUMENT_ARRAY) { + argumentArray = new String[argArrayLen]; + for (int i = 0; i < argArrayLen; i++) { + Object val = in.readObject(); + if (!NULL_ARGUMENT_ARRAY_ELEMENT.equals(val)) { + argumentArray[i] = val; + } + } } - } - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((message == null) ? 0 : message.hashCode()); - result = prime * result - + ((threadName == null) ? 0 : threadName.hashCode()); - result = prime * result + (int) (timeStamp ^ (timeStamp >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final PubLoggingEventVO other = (PubLoggingEventVO) obj; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - - if (loggerName == null) { - if (other.loggerName != null) - return false; - } else if (!loggerName.equals(other.loggerName)) - return false; - - if (threadName == null) { - if (other.threadName != null) - return false; - } else if (!threadName.equals(other.threadName)) - return false; - if (timeStamp != other.timeStamp) - return false; - - if (marker == null) { - if (other.marker != null) - return false; - } else if (!marker.equals(other.marker)) - return false; - - if (mdcPropertyMap == null) { - if (other.mdcPropertyMap != null) - return false; - } else if (!mdcPropertyMap.equals(other.mdcPropertyMap)) - return false; - return true; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(timeStamp); - sb.append(" "); - sb.append(level); - sb.append(" ["); - sb.append(threadName); - sb.append("] "); - sb.append(loggerName); - sb.append(" - "); - sb.append(getFormattedMessage()); - return sb.toString(); - } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + result = prime * result + ((threadName == null) ? 0 : threadName.hashCode()); + result = prime * result + (int) (timeStamp ^ (timeStamp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final PubLoggingEventVO other = (PubLoggingEventVO) obj; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + + if (loggerName == null) { + if (other.loggerName != null) + return false; + } else if (!loggerName.equals(other.loggerName)) + return false; + + if (threadName == null) { + if (other.threadName != null) + return false; + } else if (!threadName.equals(other.threadName)) + return false; + if (timeStamp != other.timeStamp) + return false; + + if (marker == null) { + if (other.marker != null) + return false; + } else if (!marker.equals(other.marker)) + return false; + + if (mdcPropertyMap == null) { + if (other.mdcPropertyMap != null) + return false; + } else if (!mdcPropertyMap.equals(other.mdcPropertyMap)) + return false; + return true; + } + + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(timeStamp); + sb.append(" "); + sb.append(level); + sb.append(" ["); + sb.append(threadName); + sb.append("] "); + sb.append(loggerName); + sb.append(" - "); + sb.append(getFormattedMessage()); + return sb.toString(); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/ThrowableProxyTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/ThrowableProxyTest.java index 3e1279ff6eb7a23bb46c6ada36cdfb40670b6538..32fbb003df6978d1d7cf26f71ea0fa941c42944b 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/ThrowableProxyTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/ThrowableProxyTest.java @@ -30,153 +30,153 @@ import org.junit.Test; public class ThrowableProxyTest { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - public void verify(Throwable t) { - t.printStackTrace(pw); + public void verify(Throwable t) { + t.printStackTrace(pw); - IThrowableProxy tp = new ThrowableProxy(t); + IThrowableProxy tp = new ThrowableProxy(t); - String result = ThrowableProxyUtil.asString(tp); - result = result.replace("common frames omitted", "more"); + String result = ThrowableProxyUtil.asString(tp); + result = result.replace("common frames omitted", "more"); - String expected = sw.toString(); + String expected = sw.toString(); - System.out.println("========expected"); - System.out.println(expected); + System.out.println("========expected"); + System.out.println(expected); - System.out.println("========result"); - System.out.println(result); + System.out.println("========result"); + System.out.println(result); - assertEquals(expected, result); - } + assertEquals(expected, result); + } - @Test - public void smoke() { - Exception e = new Exception("smoke"); - verify(e); - } + @Test + public void smoke() { + Exception e = new Exception("smoke"); + verify(e); + } - @Test - public void nested() { - Exception w = null; - try { - someMethod(); - } catch (Exception e) { - w = new Exception("wrapping", e); + @Test + public void nested() { + Exception w = null; + try { + someMethod(); + } catch (Exception e) { + w = new Exception("wrapping", e); + } + verify(w); } - verify(w); - } - - @Test - public void suppressed() throws InvocationTargetException, IllegalAccessException - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(e, fooException); - addSuppressed(e, barException); - ex = e; + + @Test + public void suppressed() throws InvocationTargetException, IllegalAccessException { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(e, fooException); + addSuppressed(e, barException); + ex = e; + } + verify(ex); } - verify(ex); - } - - @Test - public void suppressedWithCause() throws InvocationTargetException, IllegalAccessException - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - ex=new Exception("Wrapper", e); - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(ex, fooException); - addSuppressed(e, barException); + + @Test + public void suppressedWithCause() throws InvocationTargetException, IllegalAccessException { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + ex = new Exception("Wrapper", e); + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(ex, fooException); + addSuppressed(e, barException); + } + verify(ex); } - verify(ex); - } - - @Test - public void suppressedWithSuppressed() throws Exception - { - assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make sense. - Exception ex = null; - try { - someMethod(); - } catch (Exception e) { - ex=new Exception("Wrapper", e); - Exception fooException = new Exception("Foo"); - Exception barException = new Exception("Bar"); - addSuppressed(barException, fooException); - addSuppressed(e, barException); + + @Test + public void suppressedWithSuppressed() throws Exception { + assumeTrue(TestHelper.suppressedSupported()); // only execute on Java 7, would work anyway but doesn't make + // sense. + Exception ex = null; + try { + someMethod(); + } catch (Exception e) { + ex = new Exception("Wrapper", e); + Exception fooException = new Exception("Foo"); + Exception barException = new Exception("Bar"); + addSuppressed(barException, fooException); + addSuppressed(e, barException); + } + verify(ex); } - verify(ex); - } - - // see also http://jira.qos.ch/browse/LBCLASSIC-216 - @Test - public void nullSTE() { - Throwable t = new Exception("someMethodWithNullException") { - @Override - public StackTraceElement[] getStackTrace() { - return null; - } - }; - // we can't test output as Throwable.printStackTrace method uses - // the private getOurStackTrace method instead of getStackTrace - - // tests ThrowableProxyUtil.steArrayToStepArray - new ThrowableProxy(t); - - // tests ThrowableProxyUtil.findNumberOfCommonFrames - Exception top = new Exception("top", t); - new ThrowableProxy(top); - } - - @Test - public void multiNested() { - Exception w = null; - try { - someOtherMethod(); - } catch (Exception e) { - w = new Exception("wrapping", e); + + // see also http://jira.qos.ch/browse/LBCLASSIC-216 + @Test + public void nullSTE() { + Throwable t = new Exception("someMethodWithNullException") { + @Override + public StackTraceElement[] getStackTrace() { + return null; + } + }; + // we can't test output as Throwable.printStackTrace method uses + // the private getOurStackTrace method instead of getStackTrace + + // tests ThrowableProxyUtil.steArrayToStepArray + new ThrowableProxy(t); + + // tests ThrowableProxyUtil.findNumberOfCommonFrames + Exception top = new Exception("top", t); + new ThrowableProxy(top); } - verify(w); - } - - void someMethod() throws Exception { - throw new Exception("someMethod"); - } - - void someMethodWithNullException() throws Exception { - throw new Exception("someMethodWithNullException") { - @Override - public StackTraceElement[] getStackTrace() { - return null; - } - }; - } - - void someOtherMethod() throws Exception { - try { - someMethod(); - } catch (Exception e) { - throw new Exception("someOtherMethod", e); + + @Test + public void multiNested() { + Exception w = null; + try { + someOtherMethod(); + } catch (Exception e) { + w = new Exception("wrapping", e); + } + verify(w); + } + + void someMethod() throws Exception { + throw new Exception("someMethod"); + } + + void someMethodWithNullException() throws Exception { + throw new Exception("someMethodWithNullException") { + @Override + public StackTraceElement[] getStackTrace() { + return null; + } + }; + } + + void someOtherMethod() throws Exception { + try { + someMethod(); + } catch (Exception e) { + throw new Exception("someOtherMethod", e); + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/spi/special/CPDCSpecialImpl.java b/logback-classic/src/test/java/ch/qos/logback/classic/spi/special/CPDCSpecialImpl.java index cfc1fdcb6aac7a317d6eadde93f5f136599d2a94..a7166530371078b7a9c3d5c9385bdf0cf2e94f70 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/spi/special/CPDCSpecialImpl.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/spi/special/CPDCSpecialImpl.java @@ -18,28 +18,27 @@ import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.PackagingDataCalculator; import ch.qos.logback.classic.spi.ThrowableProxy; - public class CPDCSpecialImpl implements CPDCSpecial { - - Throwable throwable; - IThrowableProxy throwableProxy; - - public void doTest() { - nesting(); - } - - private void nesting() { - throwable = new Throwable("x"); - throwableProxy = new ThrowableProxy(throwable); - PackagingDataCalculator pdc = new PackagingDataCalculator(); - pdc.calculate(throwableProxy); - } - - public Throwable getThrowable() { - return throwable; - } - public IThrowableProxy getThrowableProxy() { - return throwableProxy; - } + Throwable throwable; + IThrowableProxy throwableProxy; + + public void doTest() { + nesting(); + } + + private void nesting() { + throwable = new Throwable("x"); + throwableProxy = new ThrowableProxy(throwable); + PackagingDataCalculator pdc = new PackagingDataCalculator(); + pdc.calculate(throwableProxy); + } + + public Throwable getThrowable() { + return throwable; + } + + public IThrowableProxy getThrowableProxy() { + return throwableProxy; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/testUtil/SampleConverter.java b/logback-classic/src/test/java/ch/qos/logback/classic/testUtil/SampleConverter.java index 0ae0dd04179692eb8117610ff274cc751267a52d..3f4baa555ac709b0e374d8202443e1a9b0675a4f 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/testUtil/SampleConverter.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/testUtil/SampleConverter.java @@ -18,11 +18,11 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class SampleConverter extends ClassicConverter { - static public final String SAMPLE_STR = "sample"; - - @Override - public String convert(ILoggingEvent event) { - return SAMPLE_STR; - } + static public final String SAMPLE_STR = "sample"; + + @Override + public String convert(ILoggingEvent event) { + return SAMPLE_STR; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DebugUsersTurboFilter.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DebugUsersTurboFilter.java index 8af42aad242309fc83b7fde47e2a90aff7c9cd67..ce2856ad1781f2d6565f526457aedcc002692840 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DebugUsersTurboFilter.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DebugUsersTurboFilter.java @@ -37,27 +37,27 @@ import ch.qos.logback.core.spi.FilterReply; */ public class DebugUsersTurboFilter extends TurboFilter { - List userList = new ArrayList(); - - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { - if (!level.equals(Level.DEBUG)) { - return FilterReply.NEUTRAL; - } - String user = MDC.get(ClassicConstants.USER_MDC_KEY); - if (user != null && userList.contains(user)) { - return FilterReply.ACCEPT; + List userList = new ArrayList(); + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + if (!level.equals(Level.DEBUG)) { + return FilterReply.NEUTRAL; + } + String user = MDC.get(ClassicConstants.USER_MDC_KEY); + if (user != null && userList.contains(user)) { + return FilterReply.ACCEPT; + } + return FilterReply.NEUTRAL; + } + + public void addUser(String user) { + userList.add(user); + } + + // test in BasicJoranTest only, to be removed asap. + public List getUsers() { + return userList; } - return FilterReply.NEUTRAL; - } - - public void addUser(String user) { - userList.add(user); - } - - //test in BasicJoranTest only, to be removed asap. - public List getUsers() { - return userList; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DuplicateMessageFilterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DuplicateMessageFilterTest.java index 556044919d7b0274dfe2ce0366bf548111737624..e69ee8f2513449c2b936648c286647140a500ae3 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DuplicateMessageFilterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/DuplicateMessageFilterTest.java @@ -21,69 +21,57 @@ import ch.qos.logback.core.spi.FilterReply; public class DuplicateMessageFilterTest { - @Test - public void smoke() { - DuplicateMessageFilter dmf = new DuplicateMessageFilter(); - dmf.setAllowedRepetitions(0); - dmf.start(); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "x", null, - null)); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "y", null, - null)); - assertEquals(FilterReply.DENY, dmf - .decide(null, null, null, "x", null, null)); - assertEquals(FilterReply.DENY, dmf - .decide(null, null, null, "y", null, null)); - } - - @Test - public void memoryLoss() { - DuplicateMessageFilter dmf = new DuplicateMessageFilter(); - dmf.setAllowedRepetitions(1); - dmf.setCacheSize(1); - dmf.start(); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a", null, - null)); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "b", null, - null)); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a", null, - null)); - } - - @Test - public void many() { - DuplicateMessageFilter dmf = new DuplicateMessageFilter(); - dmf.setAllowedRepetitions(0); - int cacheSize = 10; - int margin = 2; - dmf.setCacheSize(cacheSize); - dmf.start(); - for (int i = 0; i < cacheSize + margin; i++) { - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a" + i, - null, null)); + @Test + public void smoke() { + DuplicateMessageFilter dmf = new DuplicateMessageFilter(); + dmf.setAllowedRepetitions(0); + dmf.start(); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "x", null, null)); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "y", null, null)); + assertEquals(FilterReply.DENY, dmf.decide(null, null, null, "x", null, null)); + assertEquals(FilterReply.DENY, dmf.decide(null, null, null, "y", null, null)); } - for (int i = cacheSize - 1; i >= margin; i--) { - assertEquals(FilterReply.DENY, dmf.decide(null, null, null, "a" + i, - null, null)); + + @Test + public void memoryLoss() { + DuplicateMessageFilter dmf = new DuplicateMessageFilter(); + dmf.setAllowedRepetitions(1); + dmf.setCacheSize(1); + dmf.start(); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a", null, null)); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "b", null, null)); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a", null, null)); } - for (int i = margin - 1; i >= 0; i--) { - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a" + i, - null, null)); + + @Test + public void many() { + DuplicateMessageFilter dmf = new DuplicateMessageFilter(); + dmf.setAllowedRepetitions(0); + int cacheSize = 10; + int margin = 2; + dmf.setCacheSize(cacheSize); + dmf.start(); + for (int i = 0; i < cacheSize + margin; i++) { + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a" + i, null, null)); + } + for (int i = cacheSize - 1; i >= margin; i--) { + assertEquals(FilterReply.DENY, dmf.decide(null, null, null, "a" + i, null, null)); + } + for (int i = margin - 1; i >= 0; i--) { + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, "a" + i, null, null)); + } } - } - @Test - // isXXXEnabled invokes decide with a null format - // http://jira.qos.ch/browse/LBCLASSIC-134 - public void nullFormat() { - DuplicateMessageFilter dmf = new DuplicateMessageFilter(); - dmf.setAllowedRepetitions(0); - dmf.setCacheSize(10); - dmf.start(); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, null, null, - null)); - assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, null, null, - null)); - } + @Test + // isXXXEnabled invokes decide with a null format + // http://jira.qos.ch/browse/LBCLASSIC-134 + public void nullFormat() { + DuplicateMessageFilter dmf = new DuplicateMessageFilter(); + dmf.setAllowedRepetitions(0); + dmf.setCacheSize(10); + dmf.start(); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, null, null, null)); + assertEquals(FilterReply.NEUTRAL, dmf.decide(null, null, null, null, null, null)); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/LRUMessageCacheTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/LRUMessageCacheTest.java index da6f3d18042781a47f6390bd53f15bb5d9af7c6e..96db9e42c5a372a7591b6b72bc095500251e2dc8 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/LRUMessageCacheTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/LRUMessageCacheTest.java @@ -19,23 +19,23 @@ import org.junit.Test; public class LRUMessageCacheTest { - @Test - public void testEldestEntriesRemoval() { - final LRUMessageCache cache = new LRUMessageCache(2); - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("0")); - Assert.assertEquals(1, cache.getMessageCountAndThenIncrement("0")); - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("1")); - Assert.assertEquals(1, cache.getMessageCountAndThenIncrement("1")); - // 0 entry should have been removed. - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("2")); - // So it is expected a returned value of 0 instead of 2. - // 1 entry should have been removed. - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("0")); - // So it is expected a returned value of 0 instead of 2. - // 2 entry should have been removed. - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("1")); - // So it is expected a returned value of 0 instead of 2. - Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("2")); - } + @Test + public void testEldestEntriesRemoval() { + final LRUMessageCache cache = new LRUMessageCache(2); + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("0")); + Assert.assertEquals(1, cache.getMessageCountAndThenIncrement("0")); + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("1")); + Assert.assertEquals(1, cache.getMessageCountAndThenIncrement("1")); + // 0 entry should have been removed. + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("2")); + // So it is expected a returned value of 0 instead of 2. + // 1 entry should have been removed. + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("0")); + // So it is expected a returned value of 0 instead of 2. + // 2 entry should have been removed. + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("1")); + // So it is expected a returned value of 0 instead of 2. + Assert.assertEquals(0, cache.getMessageCountAndThenIncrement("2")); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/MarkerFilterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/MarkerFilterTest.java index 1ef2c825f7b056a239eb4ec6778d85f0dde90834..c5fcb490475ef632ef10c0797462ef6529c15503 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/MarkerFilterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/MarkerFilterTest.java @@ -25,53 +25,51 @@ import ch.qos.logback.core.spi.FilterReply; public class MarkerFilterTest { - static String TOTO = "TOTO"; - static String COMPOSITE = "COMPOSITE"; - - Marker totoMarker = MarkerFactory.getMarker(TOTO); - - - @Test - public void testNoMarker() { - MarkerFilter mkt = new MarkerFilter(); - mkt.start(); - assertFalse(mkt.isStarted()); - assertEquals(FilterReply.NEUTRAL, mkt.decide(totoMarker, null, null, null, null, null)); - assertEquals(FilterReply.NEUTRAL, mkt.decide(null, null, null, null, null, null)); - - } - - - @Test - public void testBasic() { - MarkerFilter mkt = new MarkerFilter(); - mkt.setMarker(TOTO); - mkt.setOnMatch("ACCEPT"); - mkt.setOnMismatch("DENY"); - - mkt.start(); - assertTrue(mkt.isStarted()); - assertEquals(FilterReply.DENY, mkt.decide(null, null, null, null, null, null)); - assertEquals(FilterReply.ACCEPT, mkt.decide(totoMarker, null, null, null, null, null)); - } - - @Test - public void testComposite() { - String compositeMarkerName = COMPOSITE; - Marker compositeMarker = MarkerFactory.getMarker(compositeMarkerName); - compositeMarker.add(totoMarker); - - MarkerFilter mkt = new MarkerFilter(); - mkt.setMarker(TOTO); - mkt.setOnMatch("ACCEPT"); - mkt.setOnMismatch("DENY"); - - mkt.start(); - - assertTrue(mkt.isStarted()); - assertEquals(FilterReply.DENY, mkt.decide(null, null, null, null, null, null)); - assertEquals(FilterReply.ACCEPT, mkt.decide(totoMarker, null, null, null, null, null)); - assertEquals(FilterReply.ACCEPT, mkt.decide(compositeMarker, null, null, null, null, null)); - } + static String TOTO = "TOTO"; + static String COMPOSITE = "COMPOSITE"; + + Marker totoMarker = MarkerFactory.getMarker(TOTO); + + @Test + public void testNoMarker() { + MarkerFilter mkt = new MarkerFilter(); + mkt.start(); + assertFalse(mkt.isStarted()); + assertEquals(FilterReply.NEUTRAL, mkt.decide(totoMarker, null, null, null, null, null)); + assertEquals(FilterReply.NEUTRAL, mkt.decide(null, null, null, null, null, null)); + + } + + @Test + public void testBasic() { + MarkerFilter mkt = new MarkerFilter(); + mkt.setMarker(TOTO); + mkt.setOnMatch("ACCEPT"); + mkt.setOnMismatch("DENY"); + + mkt.start(); + assertTrue(mkt.isStarted()); + assertEquals(FilterReply.DENY, mkt.decide(null, null, null, null, null, null)); + assertEquals(FilterReply.ACCEPT, mkt.decide(totoMarker, null, null, null, null, null)); + } + + @Test + public void testComposite() { + String compositeMarkerName = COMPOSITE; + Marker compositeMarker = MarkerFactory.getMarker(compositeMarkerName); + compositeMarker.add(totoMarker); + + MarkerFilter mkt = new MarkerFilter(); + mkt.setMarker(TOTO); + mkt.setOnMatch("ACCEPT"); + mkt.setOnMismatch("DENY"); + + mkt.start(); + + assertTrue(mkt.isStarted()); + assertEquals(FilterReply.DENY, mkt.decide(null, null, null, null, null, null)); + assertEquals(FilterReply.ACCEPT, mkt.decide(totoMarker, null, null, null, null, null)); + assertEquals(FilterReply.ACCEPT, mkt.decide(compositeMarker, null, null, null, null, null)); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/NOPTurboFilter.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/NOPTurboFilter.java index 6d6cb3e5c2b24801e66f21e2005a7069f89ab702..a4be245a4afb8dba413620478151cdc6fec32819 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/NOPTurboFilter.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/NOPTurboFilter.java @@ -21,11 +21,10 @@ import ch.qos.logback.core.spi.FilterReply; public class NOPTurboFilter extends TurboFilter { - @Override - public FilterReply decide(final Marker marker, final Logger logger, final Level level, final String format, - final Object[] params, final Throwable t) { - - return FilterReply.NEUTRAL; - } + @Override + public FilterReply decide(final Marker marker, final Logger logger, final Level level, final String format, final Object[] params, final Throwable t) { + + return FilterReply.NEUTRAL; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/PackageTest.java index 8ecc6d4d16bf6c208b301dbb8f0d9a8d3f7f48a5..763f4b7fff389a9bab273f90e500ceae5bf053ec 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/PackageTest.java @@ -18,7 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { ReconfigureOnChangeTest.class, MarkerFilterTest.class, - DuplicateMessageFilterTest.class }) +@SuiteClasses({ ReconfigureOnChangeTest.class, MarkerFilterTest.class, DuplicateMessageFilterTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java index 99a5f29a3caefd72325d077c36ce18366438685e..63996ebbc78cef3350238124246fb173e34b2f2d 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigureOnChangeTest.java @@ -49,400 +49,381 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class ReconfigureOnChangeTest { - final static int THREAD_COUNT = 5; - final static int LOOP_LEN = 1000 * 1000; + final static int THREAD_COUNT = 5; + final static int LOOP_LEN = 1000 * 1000; - int diff = RandomUtil.getPositiveInt(); + int diff = RandomUtil.getPositiveInt(); - // the space in the file name mandated by - // http://jira.qos.ch/browse/LBCORE-119 - final static String SCAN1_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/scan 1.xml"; + // the space in the file name mandated by + // http://jira.qos.ch/browse/LBCORE-119 + final static String SCAN1_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/scan 1.xml"; - final static String G_SCAN1_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/scan 1.groovy"; + final static String G_SCAN1_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/scan 1.groovy"; - final static String SCAN_LOGBACK_474_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/scan_logback_474.xml"; + final static String SCAN_LOGBACK_474_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/scan_logback_474.xml"; - final static String INCLUSION_SCAN_TOPLEVEL0_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/inclusion/topLevel0.xml"; + final static String INCLUSION_SCAN_TOPLEVEL0_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/inclusion/topLevel0.xml"; - final static String INCLUSION_SCAN_TOP_BY_RESOURCE_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/inclusion/topByResource.xml"; + final static String INCLUSION_SCAN_TOP_BY_RESOURCE_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/inclusion/topByResource.xml"; - final static String INCLUSION_SCAN_INNER0_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/inclusion/inner0.xml"; + final static String INCLUSION_SCAN_INNER0_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/inclusion/inner0.xml"; - final static String INCLUSION_SCAN_INNER1_AS_STR = "target/test-classes/asResource/inner1.xml"; + final static String INCLUSION_SCAN_INNER1_AS_STR = "target/test-classes/asResource/inner1.xml"; - // it actually takes time for Windows to propagate file modification changes - // values below 100 milliseconds can be problematic the same propagation - // latency occurs in Linux but is even larger (>600 ms) - // final static int DEFAULT_SLEEP_BETWEEN_UPDATES = 60; + // it actually takes time for Windows to propagate file modification changes + // values below 100 milliseconds can be problematic the same propagation + // latency occurs in Linux but is even larger (>600 ms) + // final static int DEFAULT_SLEEP_BETWEEN_UPDATES = 60; - int sleepBetweenUpdates = 100; + int sleepBetweenUpdates = 100; - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(this.getClass()); - ExecutorService executorService = loggerContext.getExecutorService(); + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(this.getClass()); + ExecutorService executorService = loggerContext.getExecutorService(); - StatusChecker checker = new StatusChecker(loggerContext); - AbstractMultiThreadedHarness harness; + StatusChecker checker = new StatusChecker(loggerContext); + AbstractMultiThreadedHarness harness; - ThreadPoolExecutor executor = (ThreadPoolExecutor) loggerContext.getExecutorService(); + ThreadPoolExecutor executor = (ThreadPoolExecutor) loggerContext.getExecutorService(); - int expectedResets = 2; + int expectedResets = 2; - @BeforeClass - static public void classSetup() { - FileTestUtil.makeTestOutputDir(); - } + @BeforeClass + static public void classSetup() { + FileTestUtil.makeTestOutputDir(); + } - @Before - public void setUp() { - harness = new WaitOnExecutionMultiThreadedHarness(executor, expectedResets); - } + @Before + public void setUp() { + harness = new WaitOnExecutionMultiThreadedHarness(executor, expectedResets); + } - @After - public void tearDown() { - } + @After + public void tearDown() { + } - void configure(File file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(file); - } + void configure(File file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(file); + } - void configure(InputStream is) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(is); - } + void configure(InputStream is) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(is); + } - void gConfigure(File file) throws JoranException { - GafferConfigurator gc = new GafferConfigurator(loggerContext); - gc.run(file); - } + void gConfigure(File file) throws JoranException { + GafferConfigurator gc = new GafferConfigurator(loggerContext); + gc.run(file); + } - RunnableWithCounterAndDone[] buildRunnableArray(File configFile, UpdateType updateType) { - RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; - rArray[0] = new Updater(configFile, updateType); - for (int i = 1; i < THREAD_COUNT; i++) { - rArray[i] = new LoggingRunnable(logger); + RunnableWithCounterAndDone[] buildRunnableArray(File configFile, UpdateType updateType) { + RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; + rArray[0] = new Updater(configFile, updateType); + for (int i = 1; i < THREAD_COUNT; i++) { + rArray[i] = new LoggingRunnable(logger); + } + return rArray; } - return rArray; - } - - // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter - @Test - public void installFilter() throws JoranException, IOException, InterruptedException { - File file = new File(SCAN1_FILE_AS_STR); - configure(file); - List fileList = getConfigurationFileList(loggerContext); - assertThatListContainsFile(fileList, file); - assertThatFirstFilterIsROCF(); - StatusPrinter.print(loggerContext); - } - - - @Test - public void gafferInstallFilter() throws JoranException, IOException, InterruptedException { - File file = new File(G_SCAN1_FILE_AS_STR); - gConfigure(file); - List fileList = getConfigurationFileList(loggerContext); - assertThatListContainsFile(fileList, file); - assertThatFirstFilterIsROCF(); - - rocfDetachReconfigurationToNewThreadAndAwaitTermination(); - - fileList = getConfigurationFileList(loggerContext); - assertThatListContainsFile(fileList, file); - assertThatFirstFilterIsROCF(); - - // check that rcof filter installed on two occasions - assertEquals(2, checker.matchCount("Will scan for changes in")); - } - - private void rocfDetachReconfigurationToNewThreadAndAwaitTermination() throws InterruptedException { - ReconfigureOnChangeFilter reconfigureOnChangeFilter = (ReconfigureOnChangeFilter) getFirstTurboFilter(); - reconfigureOnChangeFilter.detachReconfigurationToNewThread(); - executorService.shutdown(); - executorService.awaitTermination(1000, TimeUnit.MILLISECONDS); - } - - List getConfigurationFileList(LoggerContext context) { - ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(loggerContext); - return configurationWatchList.getCopyOfFileWatchList(); - } - - @Test(timeout = 4000L) - public void scanWithFileInclusion() throws JoranException, IOException, InterruptedException { - File topLevelFile = new File(INCLUSION_SCAN_TOPLEVEL0_AS_STR); - File innerFile = new File(INCLUSION_SCAN_INNER0_AS_STR); - configure(topLevelFile); - List fileList = getConfigurationFileList(loggerContext); - assertThatListContainsFile(fileList, topLevelFile); - assertThatListContainsFile(fileList, innerFile); - } - - @Test(timeout = 4000L) - public void scanWithResourceInclusion() throws JoranException, IOException, InterruptedException { - File topLevelFile = new File(INCLUSION_SCAN_TOP_BY_RESOURCE_AS_STR); - File innerFile = new File(INCLUSION_SCAN_INNER1_AS_STR); - configure(topLevelFile); - - List fileList = getConfigurationFileList(loggerContext); - assertThatListContainsFile(fileList, topLevelFile); - assertThatListContainsFile(fileList, innerFile); - } - - // See also http://jira.qos.ch/browse/LOGBACK-338 - @Test - public void includeScanViaInputStreamSuppliedConfigFile() throws IOException, JoranException, InterruptedException { - String configurationStr = ""; - configure(new ByteArrayInputStream(configurationStr.getBytes("UTF-8"))); - - ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(loggerContext); - assertNull(configurationWatchList.getMainURL()); - - ReconfigureOnChangeFilter reconfigureOnChangeFilter = (ReconfigureOnChangeFilter) getFirstTurboFilter(); - // without a top level file, reconfigureOnChangeFilter should not start - assertFalse(reconfigureOnChangeFilter.isStarted()); - } - - @Test(timeout = 4000L) - public void fallbackToSafe() throws IOException, JoranException, InterruptedException { - String path = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_fallbackToSafe-" + diff + ".xml"; - File topLevelFile = new File(path); - writeToFile(topLevelFile, " "); - configure(topLevelFile); - - writeToFile(topLevelFile, "\n" + - " "); - - rocfDetachReconfigurationToNewThreadAndAwaitTermination(); - - checker.assertContainsMatch(Status.WARN, "Falling back to previously registered safe configuration."); - checker.assertContainsMatch(Status.INFO, "Re-registering previous fallback configuration once more"); - - assertThatFirstFilterIsROCF(); - } - - @Test(timeout = 4000L) - public void fallbackToSafeWithIncludedFile() throws IOException, JoranException, InterruptedException { - String topLevelFileAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_top-" + diff + ".xml"; - String innerFileAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_inner-" + diff + ".xml"; - File topLevelFile = new File(topLevelFileAsStr); - writeToFile(topLevelFile, " "); - - File innerFile = new File(innerFileAsStr); - writeToFile(innerFile, " "); - configure(topLevelFile); - writeToFile(innerFile, "\n\n"); - rocfDetachReconfigurationToNewThreadAndAwaitTermination(); - - checker.assertContainsMatch(Status.WARN, "Falling back to previously registered safe configuration."); - checker.assertContainsMatch(Status.INFO, "Re-registering previous fallback configuration once more"); - assertThatFirstFilterIsROCF(); - } - - - // check for deadlocks - @Test(timeout = 4000L) - public void scan_LOGBACK_474() throws JoranException, IOException, - InterruptedException { - File file = new File(SCAN_LOGBACK_474_FILE_AS_STR); - configure(file); - - RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(file, UpdateType.TOUCH); - harness.execute(runnableArray); - - loggerContext.getStatusManager().add( - new InfoStatus("end of execution ", this)); - - verify(expectedResets); - } - - - private void assertThatListContainsFile(List fileList, File file) { - // conversion to absolute file seems to work nicely - assertTrue(fileList.contains(file.getAbsoluteFile())); - } + // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter + @Test + public void installFilter() throws JoranException, IOException, InterruptedException { + File file = new File(SCAN1_FILE_AS_STR); + configure(file); + List fileList = getConfigurationFileList(loggerContext); + assertThatListContainsFile(fileList, file); + assertThatFirstFilterIsROCF(); + StatusPrinter.print(loggerContext); + } - private TurboFilter getFirstTurboFilter() { - TurboFilterList turboFilterList = loggerContext.getTurboFilterList(); - return turboFilterList.get(0); - } + @Test + public void gafferInstallFilter() throws JoranException, IOException, InterruptedException { + File file = new File(G_SCAN1_FILE_AS_STR); + gConfigure(file); + List fileList = getConfigurationFileList(loggerContext); + assertThatListContainsFile(fileList, file); + assertThatFirstFilterIsROCF(); + rocfDetachReconfigurationToNewThreadAndAwaitTermination(); - private void assertThatFirstFilterIsROCF() { - assertTrue(getFirstTurboFilter() instanceof ReconfigureOnChangeFilter); - } + fileList = getConfigurationFileList(loggerContext); + assertThatListContainsFile(fileList, file); + assertThatFirstFilterIsROCF(); + // check that rcof filter installed on two occasions + assertEquals(2, checker.matchCount("Will scan for changes in")); + } - private void verify(int expected) { - StatusChecker checker = new StatusChecker(loggerContext); - //StatusPrinter.print(loggerContext); - checker.assertIsErrorFree(); - - int effectiveResets = checker - .matchCount(CoreConstants.RESET_MSG_PREFIX); - - String failMsg = "effective=" + effectiveResets + ", expected=" - + expected; - - // there might be more effective resets than the expected amount - // since the harness may be sleeping while a reset occurs - assertTrue(failMsg, expected <= effectiveResets && (expected + 2) >= effectiveResets); - - } - - ReconfigureOnChangeFilter initROCF() throws MalformedURLException { - ReconfigureOnChangeFilter rocf = new ReconfigureOnChangeFilter(); - rocf.setContext(loggerContext); - File file = new File(SCAN1_FILE_AS_STR); - ConfigurationWatchListUtil.setMainWatchURL(loggerContext, file.toURI().toURL()); - rocf.start(); - return rocf; - } - - @Test - @Ignore - public void directPerfTest() throws MalformedURLException { - if (EnvUtilForTests.isLinux()) { - // for some reason this test does not pass on Linux (AMD 64 bit, - // Dual Core Opteron 170) - return; + private void rocfDetachReconfigurationToNewThreadAndAwaitTermination() throws InterruptedException { + ReconfigureOnChangeFilter reconfigureOnChangeFilter = (ReconfigureOnChangeFilter) getFirstTurboFilter(); + reconfigureOnChangeFilter.detachReconfigurationToNewThread(); + executorService.shutdown(); + executorService.awaitTermination(1000, TimeUnit.MILLISECONDS); } - ReconfigureOnChangeFilter rocf = initROCF(); - assertTrue(rocf.isStarted()); + List getConfigurationFileList(LoggerContext context) { + ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(loggerContext); + return configurationWatchList.getCopyOfFileWatchList(); + } - for (int i = 0; i < 30; i++) { - directLoop(rocf); + @Test(timeout = 4000L) + public void scanWithFileInclusion() throws JoranException, IOException, InterruptedException { + File topLevelFile = new File(INCLUSION_SCAN_TOPLEVEL0_AS_STR); + File innerFile = new File(INCLUSION_SCAN_INNER0_AS_STR); + configure(topLevelFile); + List fileList = getConfigurationFileList(loggerContext); + assertThatListContainsFile(fileList, topLevelFile); + assertThatListContainsFile(fileList, innerFile); } - double avg = directLoop(rocf); - System.out.println("directPerfTest: " + avg); - } - - public double directLoop(ReconfigureOnChangeFilter rocf) { - long start = System.nanoTime(); - for (int i = 0; i < LOOP_LEN; i++) { - rocf.decide(null, logger, Level.DEBUG, " ", null, null); + + @Test(timeout = 4000L) + public void scanWithResourceInclusion() throws JoranException, IOException, InterruptedException { + File topLevelFile = new File(INCLUSION_SCAN_TOP_BY_RESOURCE_AS_STR); + File innerFile = new File(INCLUSION_SCAN_INNER1_AS_STR); + configure(topLevelFile); + + List fileList = getConfigurationFileList(loggerContext); + assertThatListContainsFile(fileList, topLevelFile); + assertThatListContainsFile(fileList, innerFile); } - long end = System.nanoTime(); - return (end - start) / (1.0d * LOOP_LEN); - } - - @Ignore - @Test - public void indirectPerfTest() throws MalformedURLException { - if (EnvUtilForTests.isLinux()) { - // for some reason this test does not pass on Linux (AMD 64 bit, - // Dual Core - // Opteron 170) - return; + + // See also http://jira.qos.ch/browse/LOGBACK-338 + @Test + public void includeScanViaInputStreamSuppliedConfigFile() throws IOException, JoranException, InterruptedException { + String configurationStr = ""; + configure(new ByteArrayInputStream(configurationStr.getBytes("UTF-8"))); + + ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(loggerContext); + assertNull(configurationWatchList.getMainURL()); + + ReconfigureOnChangeFilter reconfigureOnChangeFilter = (ReconfigureOnChangeFilter) getFirstTurboFilter(); + // without a top level file, reconfigureOnChangeFilter should not start + assertFalse(reconfigureOnChangeFilter.isStarted()); } - ReconfigureOnChangeFilter rocf = initROCF(); - assertTrue(rocf.isStarted()); - loggerContext.addTurboFilter(rocf); - logger.setLevel(Level.ERROR); - - indirectLoop(); - double avg = indirectLoop(); - System.out.println(avg); - // the reference was computed on Orion (Ceki's computer) - long referencePerf = 68; - BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); - } - - void addInfo(String msg, Object o) { - loggerContext.getStatusManager().add(new InfoStatus(msg, o)); - } - - public double indirectLoop() { - long start = System.nanoTime(); - for (int i = 0; i < LOOP_LEN; i++) { - logger.debug("hello"); + @Test(timeout = 4000L) + public void fallbackToSafe() throws IOException, JoranException, InterruptedException { + String path = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_fallbackToSafe-" + diff + ".xml"; + File topLevelFile = new File(path); + writeToFile(topLevelFile, " "); + configure(topLevelFile); + + writeToFile(topLevelFile, "\n" + " "); + + rocfDetachReconfigurationToNewThreadAndAwaitTermination(); + + checker.assertContainsMatch(Status.WARN, "Falling back to previously registered safe configuration."); + checker.assertContainsMatch(Status.INFO, "Re-registering previous fallback configuration once more"); + + assertThatFirstFilterIsROCF(); + } + + @Test(timeout = 4000L) + public void fallbackToSafeWithIncludedFile() throws IOException, JoranException, InterruptedException { + String topLevelFileAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_top-" + diff + ".xml"; + String innerFileAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_inner-" + diff + ".xml"; + File topLevelFile = new File(topLevelFileAsStr); + writeToFile(topLevelFile, " "); + + File innerFile = new File(innerFileAsStr); + writeToFile(innerFile, " "); + configure(topLevelFile); + writeToFile(innerFile, "\n\n"); + rocfDetachReconfigurationToNewThreadAndAwaitTermination(); + + checker.assertContainsMatch(Status.WARN, "Falling back to previously registered safe configuration."); + checker.assertContainsMatch(Status.INFO, "Re-registering previous fallback configuration once more"); + + assertThatFirstFilterIsROCF(); } - long end = System.nanoTime(); - return (end - start) / (1.0d * LOOP_LEN); - } - enum UpdateType {TOUCH, MALFORMED, MALFORMED_INNER} + // check for deadlocks + @Test(timeout = 4000L) + public void scan_LOGBACK_474() throws JoranException, IOException, InterruptedException { + File file = new File(SCAN_LOGBACK_474_FILE_AS_STR); + configure(file); + + RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(file, UpdateType.TOUCH); + harness.execute(runnableArray); - void writeToFile(File file, String contents) throws IOException { - FileWriter fw = new FileWriter(file); - fw.write(contents); - fw.close(); - } + loggerContext.getStatusManager().add(new InfoStatus("end of execution ", this)); + + verify(expectedResets); + } - class Updater extends RunnableWithCounterAndDone { - File configFile; - UpdateType updateType; + private void assertThatListContainsFile(List fileList, File file) { + // conversion to absolute file seems to work nicely + assertTrue(fileList.contains(file.getAbsoluteFile())); + } - Updater(File configFile, UpdateType updateType) { - this.configFile = configFile; - this.updateType = updateType; + private TurboFilter getFirstTurboFilter() { + TurboFilterList turboFilterList = loggerContext.getTurboFilterList(); + return turboFilterList.get(0); } - Updater(File configFile) { - this(configFile, UpdateType.TOUCH); + private void assertThatFirstFilterIsROCF() { + assertTrue(getFirstTurboFilter() instanceof ReconfigureOnChangeFilter); } - public void run() { - while (!isDone()) { - try { - Thread.sleep(sleepBetweenUpdates); - } catch (InterruptedException e) { + private void verify(int expected) { + StatusChecker checker = new StatusChecker(loggerContext); + // StatusPrinter.print(loggerContext); + checker.assertIsErrorFree(); + + int effectiveResets = checker.matchCount(CoreConstants.RESET_MSG_PREFIX); + + String failMsg = "effective=" + effectiveResets + ", expected=" + expected; + + // there might be more effective resets than the expected amount + // since the harness may be sleeping while a reset occurs + assertTrue(failMsg, expected <= effectiveResets && (expected + 2) >= effectiveResets); + + } + + ReconfigureOnChangeFilter initROCF() throws MalformedURLException { + ReconfigureOnChangeFilter rocf = new ReconfigureOnChangeFilter(); + rocf.setContext(loggerContext); + File file = new File(SCAN1_FILE_AS_STR); + ConfigurationWatchListUtil.setMainWatchURL(loggerContext, file.toURI().toURL()); + rocf.start(); + return rocf; + } + + @Test + @Ignore + public void directPerfTest() throws MalformedURLException { + if (EnvUtilForTests.isLinux()) { + // for some reason this test does not pass on Linux (AMD 64 bit, + // Dual Core Opteron 170) + return; } - if (isDone()) { - return; + + ReconfigureOnChangeFilter rocf = initROCF(); + assertTrue(rocf.isStarted()); + + for (int i = 0; i < 30; i++) { + directLoop(rocf); } - counter++; - ReconfigureOnChangeTest.this.addInfo("***settting last modified", this); - switch (updateType) { - case TOUCH: - touchFile(); - break; - case MALFORMED: - try { - malformedUpdate(); - } catch (IOException e) { - e.printStackTrace(); - fail("malformedUpdate failed"); - } - break; - case MALFORMED_INNER: - try { - malformedInnerUpdate(); - } catch (IOException e) { - e.printStackTrace(); - fail("malformedInnerUpdate failed"); - } + double avg = directLoop(rocf); + System.out.println("directPerfTest: " + avg); + } + + public double directLoop(ReconfigureOnChangeFilter rocf) { + long start = System.nanoTime(); + for (int i = 0; i < LOOP_LEN; i++) { + rocf.decide(null, logger, Level.DEBUG, " ", null, null); + } + long end = System.nanoTime(); + return (end - start) / (1.0d * LOOP_LEN); + } + + @Ignore + @Test + public void indirectPerfTest() throws MalformedURLException { + if (EnvUtilForTests.isLinux()) { + // for some reason this test does not pass on Linux (AMD 64 bit, + // Dual Core + // Opteron 170) + return; } - } + + ReconfigureOnChangeFilter rocf = initROCF(); + assertTrue(rocf.isStarted()); + loggerContext.addTurboFilter(rocf); + logger.setLevel(Level.ERROR); + + indirectLoop(); + double avg = indirectLoop(); + System.out.println(avg); + // the reference was computed on Orion (Ceki's computer) + long referencePerf = 68; + BogoPerf.assertDuration(avg, referencePerf, CoreConstants.REFERENCE_BIPS); + } + + void addInfo(String msg, Object o) { + loggerContext.getStatusManager().add(new InfoStatus(msg, o)); } - private void malformedUpdate() throws IOException { - writeToFile(configFile, "\n" + - " \n" + - ""); + public double indirectLoop() { + long start = System.nanoTime(); + for (int i = 0; i < LOOP_LEN; i++) { + logger.debug("hello"); + } + long end = System.nanoTime(); + return (end - start) / (1.0d * LOOP_LEN); } - private void malformedInnerUpdate() throws IOException { - writeToFile(configFile, "\n" + - " \n" + - ""); + enum UpdateType { + TOUCH, MALFORMED, MALFORMED_INNER } - void touchFile() { - configFile.setLastModified(System.currentTimeMillis()); + void writeToFile(File file, String contents) throws IOException { + FileWriter fw = new FileWriter(file); + fw.write(contents); + fw.close(); } - } + class Updater extends RunnableWithCounterAndDone { + File configFile; + UpdateType updateType; + + Updater(File configFile, UpdateType updateType) { + this.configFile = configFile; + this.updateType = updateType; + } + + Updater(File configFile) { + this(configFile, UpdateType.TOUCH); + } + + public void run() { + while (!isDone()) { + try { + Thread.sleep(sleepBetweenUpdates); + } catch (InterruptedException e) { + } + if (isDone()) { + return; + } + counter++; + ReconfigureOnChangeTest.this.addInfo("***settting last modified", this); + switch (updateType) { + case TOUCH: + touchFile(); + break; + case MALFORMED: + try { + malformedUpdate(); + } catch (IOException e) { + e.printStackTrace(); + fail("malformedUpdate failed"); + } + break; + case MALFORMED_INNER: + try { + malformedInnerUpdate(); + } catch (IOException e) { + e.printStackTrace(); + fail("malformedInnerUpdate failed"); + } + } + } + } + + private void malformedUpdate() throws IOException { + writeToFile(configFile, "\n" + " \n" + ""); + } + + private void malformedInnerUpdate() throws IOException { + writeToFile(configFile, "\n" + " \n" + ""); + } + + void touchFile() { + configFile.setLastModified(System.currentTimeMillis()); + } + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigurePerf.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigurePerf.java index 2e671c32f7aec5dc11f82df1ba43e3e92e1ad36b..0eb7c26d01f411081172aa73f909aa65d8b46ec7 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigurePerf.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/ReconfigurePerf.java @@ -32,65 +32,64 @@ import ch.qos.logback.core.joran.spi.JoranException; @Ignore public class ReconfigurePerf { - final static int THREAD_COUNT = 500; - //final static int LOOP_LEN = 1000 * 1000; + final static int THREAD_COUNT = 500; + // final static int LOOP_LEN = 1000 * 1000; - // the space in the file name mandated by - // http://jira.qos.ch/browse/LBCORE-119 - final static String CONF_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX - + "turbo/scan_perf.xml"; + // the space in the file name mandated by + // http://jira.qos.ch/browse/LBCORE-119 + final static String CONF_FILE_AS_STR = ClassicTestConstants.INPUT_PREFIX + "turbo/scan_perf.xml"; - // it actually takes time for Windows to propagate file modification changes - // values below 100 milliseconds can be problematic the same propagation - // latency occurs in Linux but is even larger (>600 ms) - final static int DEFAULT_SLEEP_BETWEEN_UPDATES = 110; + // it actually takes time for Windows to propagate file modification changes + // values below 100 milliseconds can be problematic the same propagation + // latency occurs in Linux but is even larger (>600 ms) + final static int DEFAULT_SLEEP_BETWEEN_UPDATES = 110; - int sleepBetweenUpdates = DEFAULT_SLEEP_BETWEEN_UPDATES; + int sleepBetweenUpdates = DEFAULT_SLEEP_BETWEEN_UPDATES; - static int numberOfCycles = 100; - static int totalTestDuration; + static int numberOfCycles = 100; + static int totalTestDuration; - LoggerContext loggerContext = new LoggerContext(); - Logger logger = loggerContext.getLogger(this.getClass()); - MultiThreadedHarness harness; + LoggerContext loggerContext = new LoggerContext(); + Logger logger = loggerContext.getLogger(this.getClass()); + MultiThreadedHarness harness; - @Before - public void setUp() { - // take into account propagation latency occurs on Linux - if (EnvUtilForTests.isLinux()) { - sleepBetweenUpdates = 850; - totalTestDuration = sleepBetweenUpdates * numberOfCycles; - } else { - totalTestDuration = sleepBetweenUpdates * numberOfCycles * 2; + @Before + public void setUp() { + // take into account propagation latency occurs on Linux + if (EnvUtilForTests.isLinux()) { + sleepBetweenUpdates = 850; + totalTestDuration = sleepBetweenUpdates * numberOfCycles; + } else { + totalTestDuration = sleepBetweenUpdates * numberOfCycles * 2; + } + harness = new MultiThreadedHarness(totalTestDuration); } - harness = new MultiThreadedHarness(totalTestDuration); - } - void configure(File file) throws JoranException { - JoranConfigurator jc = new JoranConfigurator(); - jc.setContext(loggerContext); - jc.doConfigure(file); - } + void configure(File file) throws JoranException { + JoranConfigurator jc = new JoranConfigurator(); + jc.setContext(loggerContext); + jc.doConfigure(file); + } - RunnableWithCounterAndDone[] buildRunnableArray() { - RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - rArray[i] = new LoggingRunnable(logger); + RunnableWithCounterAndDone[] buildRunnableArray() { + RunnableWithCounterAndDone[] rArray = new RunnableWithCounterAndDone[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + rArray[i] = new LoggingRunnable(logger); + } + return rArray; } - return rArray; - } - // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter - @Test - public void scan1() throws JoranException, IOException, InterruptedException { - File file = new File(CONF_FILE_AS_STR); - configure(file); - System.out.println("Running scan1()"); - doRun(); - } + // Tests whether ConfigurationAction is installing ReconfigureOnChangeFilter + @Test + public void scan1() throws JoranException, IOException, InterruptedException { + File file = new File(CONF_FILE_AS_STR); + configure(file); + System.out.println("Running scan1()"); + doRun(); + } - void doRun() throws InterruptedException { - RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); - harness.execute(runnableArray); - } + void doRun() throws InterruptedException { + RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(); + harness.execute(runnableArray); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Event.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Event.java index 63d3a5ab5c0647d39d22be75621bf5fd032aadad..01378954e0bb5cb9d8acab9b415a6e9d37a544e6 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Event.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Event.java @@ -15,19 +15,19 @@ package ch.qos.logback.classic.turbo.lru; public class Event { - final public boolean put; - final public K k; - - public Event(boolean put, K k) { - this.put = put; - this.k = k; - } - - public String toString() { - if(put) { - return "Event: put, "+k; - } else { - return "Event: get, "+k; + final public boolean put; + final public K k; + + public Event(boolean put, K k) { + this.put = put; + this.k = k; + } + + public String toString() { + if (put) { + return "Event: put, " + k; + } else { + return "Event: get, " + k; + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCache.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCache.java index 10b544e3b0c6bfabbd0f9e66c89609ace112d067..a7edb06b90957f01460620c800cfc21484afd813 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCache.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCache.java @@ -27,25 +27,25 @@ import java.util.Map; * @param */ public class LRUCache extends LinkedHashMap { - private static final long serialVersionUID = -6592964689843698200L; + private static final long serialVersionUID = -6592964689843698200L; - final int cacheSize; + final int cacheSize; - public LRUCache(int cacheSize) { - super((int) (cacheSize*(4.0f/3)), 0.75f, true); - if(cacheSize < 1) { - throw new IllegalArgumentException("Cache size cannnot be smaller than 1"); - } - this.cacheSize = cacheSize; - } - - protected boolean removeEldestEntry(Map.Entry eldest) { - return (size() > cacheSize); - } - - List keyList() { - ArrayList al = new ArrayList(); - al.addAll(keySet()); - return al; - } + public LRUCache(int cacheSize) { + super((int) (cacheSize * (4.0f / 3)), 0.75f, true); + if (cacheSize < 1) { + throw new IllegalArgumentException("Cache size cannnot be smaller than 1"); + } + this.cacheSize = cacheSize; + } + + protected boolean removeEldestEntry(Map.Entry eldest) { + return (size() > cacheSize); + } + + List keyList() { + ArrayList al = new ArrayList(); + al.addAll(keySet()); + return al; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCacheTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCacheTest.java index a00aa286baa4fa95739a3b19a6d877aad4e1fe06..82463250e6f6076e7ac0409bdfb4668962615106 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCacheTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/LRUCacheTest.java @@ -24,99 +24,97 @@ import org.junit.Test; @Ignore public class LRUCacheTest { - @Test - public void smoke() { - - LRUCache cache = new LRUCache(2); - cache.put("a", "a"); - cache.put("b", "b"); - cache.put("c", "c"); - List witness = new LinkedList(); - witness.add("b"); - witness.add("c"); - assertEquals(witness, cache.keyList()); - } - - @Test - public void typicalScenarioTest() { - int simulationLen = 1000 * 10; - int cacheSize = 100; - int worldSize = 1000; - doScenario(simulationLen, cacheSize, worldSize); - } - - @Test - public void scenarioCoverageTest() { - int simulationLen = 1000 * 10; - - int[] cacheSizes = new int[] { 1, 10, 100}; - // tests with large worldSizes are slow because with a large - // world size the probability of a cache miss is high. - int[] worldSizes = new int[] { 1, 10, 100 }; - - for (int i = 0; i < cacheSizes.length; i++) { - for (int j = 0; j < worldSizes.length; j++) { - doScenario(simulationLen, cacheSizes[i], worldSizes[j]); - } + @Test + public void smoke() { + + LRUCache cache = new LRUCache(2); + cache.put("a", "a"); + cache.put("b", "b"); + cache.put("c", "c"); + List witness = new LinkedList(); + witness.add("b"); + witness.add("c"); + assertEquals(witness, cache.keyList()); } - } - - void doScenario(int simulationLen, int cacheSize, int worldSize) { - int get2PutRatio = 10; - Simulator simulator = new Simulator(worldSize, get2PutRatio, false); - List scenario = simulator.generateScenario(simulationLen); - LRUCache lruCache = new LRUCache(cacheSize); - T_LRUCache tlruCache = new T_LRUCache(cacheSize); - long start = System.nanoTime(); - simulator.simulate(scenario, lruCache, tlruCache); - //assertEquals(tlruCache.keyList(), lruCache.keyList()); - long end = System.nanoTime(); - System.out.println("cacheSize=" + cacheSize + ", worldSize=" + worldSize - + ", elapsed time=" + ((end - start) / (1000 * 1000)) + " in millis"); - } - - - - @Test - @Ignore // slow test that is known to pass - public void multiThreadedScenario() throws InterruptedException { - int cacheSize = 100; - int worldSize = cacheSize*2; - LRUCache lruCache = new LRUCache(cacheSize); - T_LRUCache tlruCache = new T_LRUCache(cacheSize); - SimulatorRunnable[] simulatorArray = new SimulatorRunnable[5]; - for(int i = 0; i < simulatorArray.length; i++) { - simulatorArray[i] = new SimulatorRunnable(lruCache, tlruCache, worldSize); + + @Test + public void typicalScenarioTest() { + int simulationLen = 1000 * 10; + int cacheSize = 100; + int worldSize = 1000; + doScenario(simulationLen, cacheSize, worldSize); } - for(int i = 0; i < simulatorArray.length; i++) { - simulatorArray[i].start(); + + @Test + public void scenarioCoverageTest() { + int simulationLen = 1000 * 10; + + int[] cacheSizes = new int[] { 1, 10, 100 }; + // tests with large worldSizes are slow because with a large + // world size the probability of a cache miss is high. + int[] worldSizes = new int[] { 1, 10, 100 }; + + for (int i = 0; i < cacheSizes.length; i++) { + for (int j = 0; j < worldSizes.length; j++) { + doScenario(simulationLen, cacheSizes[i], worldSizes[j]); + } + } } - for(int i = 0; i < simulatorArray.length; i++) { - simulatorArray[i].join(); + + void doScenario(int simulationLen, int cacheSize, int worldSize) { + int get2PutRatio = 10; + Simulator simulator = new Simulator(worldSize, get2PutRatio, false); + List scenario = simulator.generateScenario(simulationLen); + LRUCache lruCache = new LRUCache(cacheSize); + T_LRUCache tlruCache = new T_LRUCache(cacheSize); + long start = System.nanoTime(); + simulator.simulate(scenario, lruCache, tlruCache); + // assertEquals(tlruCache.keyList(), lruCache.keyList()); + long end = System.nanoTime(); + System.out.println("cacheSize=" + cacheSize + ", worldSize=" + worldSize + ", elapsed time=" + ((end - start) / (1000 * 1000)) + " in millis"); } - assertEquals(tlruCache.keyList(), lruCache.keyList()); - } - - private class SimulatorRunnable extends Thread { - - LRUCache lruCache; - T_LRUCache tlruCache; - int worldSize; - - SimulatorRunnable(LRUCache lruCache, T_LRUCache tlruCache, int worldSize) { - this.lruCache = lruCache; - this.tlruCache = tlruCache; - this.worldSize = worldSize; + + @Test + @Ignore + // slow test that is known to pass + public void multiThreadedScenario() throws InterruptedException { + int cacheSize = 100; + int worldSize = cacheSize * 2; + LRUCache lruCache = new LRUCache(cacheSize); + T_LRUCache tlruCache = new T_LRUCache(cacheSize); + SimulatorRunnable[] simulatorArray = new SimulatorRunnable[5]; + for (int i = 0; i < simulatorArray.length; i++) { + simulatorArray[i] = new SimulatorRunnable(lruCache, tlruCache, worldSize); + } + for (int i = 0; i < simulatorArray.length; i++) { + simulatorArray[i].start(); + } + for (int i = 0; i < simulatorArray.length; i++) { + simulatorArray[i].join(); + } + assertEquals(tlruCache.keyList(), lruCache.keyList()); } - - public void run() { - int get2PutRatio = 10; - int simulationLen = 1000*50; - Simulator simulator = new Simulator(worldSize, get2PutRatio, true); - List scenario = simulator.generateScenario(simulationLen); - simulator.simulate(scenario, lruCache, tlruCache); - System.out.println("done"); + + private class SimulatorRunnable extends Thread { + + LRUCache lruCache; + T_LRUCache tlruCache; + int worldSize; + + SimulatorRunnable(LRUCache lruCache, T_LRUCache tlruCache, int worldSize) { + this.lruCache = lruCache; + this.tlruCache = tlruCache; + this.worldSize = worldSize; + } + + public void run() { + int get2PutRatio = 10; + int simulationLen = 1000 * 50; + Simulator simulator = new Simulator(worldSize, get2PutRatio, true); + List scenario = simulator.generateScenario(simulationLen); + simulator.simulate(scenario, lruCache, tlruCache); + System.out.println("done"); + } } - } - + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Simulator.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Simulator.java index aabe869ece3e7e5ea7a2d27462fbc724727864ff..bc7e1c96c0ee3f45b4804c1ed98f9fa33444e104 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Simulator.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/Simulator.java @@ -21,69 +21,68 @@ import java.util.Random; public class Simulator { - Random random; + Random random; - int worldSize; - int get2PutRatio; - boolean multiThreaded; + int worldSize; + int get2PutRatio; + boolean multiThreaded; - public Simulator(int worldSize, int get2PutRatio, boolean multiThreaded) { - this.worldSize = worldSize; - this.get2PutRatio = get2PutRatio; - long seed = System.nanoTime(); - // System.out.println("seed is "+seed); - random = new Random(seed); - this.multiThreaded = multiThreaded; - } + public Simulator(int worldSize, int get2PutRatio, boolean multiThreaded) { + this.worldSize = worldSize; + this.get2PutRatio = get2PutRatio; + long seed = System.nanoTime(); + // System.out.println("seed is "+seed); + random = new Random(seed); + this.multiThreaded = multiThreaded; + } - public List generateScenario(int len) { - List scenario = new ArrayList(); + public List generateScenario(int len) { + List scenario = new ArrayList(); - for (int i = 0; i < len; i++) { + for (int i = 0; i < len; i++) { - int r = random.nextInt(get2PutRatio); - boolean put = false; - if (r == 0) { - put = true; - } - r = random.nextInt(worldSize); - Event e = new Event(put, String.valueOf(r)); - scenario.add(e); + int r = random.nextInt(get2PutRatio); + boolean put = false; + if (r == 0) { + put = true; + } + r = random.nextInt(worldSize); + Event e = new Event(put, String.valueOf(r)); + scenario.add(e); + } + return scenario; } - return scenario; - } - public void simulate(List scenario, LRUCache lruCache, - T_LRUCache tlruCache) { - for (Event e : scenario) { - if (e.put) { - lruCache.put(e.k, e.k); - tlruCache.put(e.k); - } else { - String r0 = lruCache.get(e.k); - String r1 = tlruCache.get(e.k); - if (!multiThreaded) { - // if the simulation is used in a multi-threaded - // context, then the state of lruCache may be different than - // that of tlruCache. In single threaded mode, they should - // return the same values all the time - if (r0 != null) { - assertEquals(r0, e.k); - } - assertEquals(r0, r1); + public void simulate(List scenario, LRUCache lruCache, T_LRUCache tlruCache) { + for (Event e : scenario) { + if (e.put) { + lruCache.put(e.k, e.k); + tlruCache.put(e.k); + } else { + String r0 = lruCache.get(e.k); + String r1 = tlruCache.get(e.k); + if (!multiThreaded) { + // if the simulation is used in a multi-threaded + // context, then the state of lruCache may be different than + // that of tlruCache. In single threaded mode, they should + // return the same values all the time + if (r0 != null) { + assertEquals(r0, e.k); + } + assertEquals(r0, r1); + } + } } - } } - } - // void compareAndDumpIfDifferent(LRUCache lruCache, - // T_LRUCache tlruCache) { - // lruCache.dump(); - // tlruCache.dump(); - // if(!lruCache.keyList().equals(tlruCache.ketList())) { - // lruCache.dump(); - // tlruCache.dump(); - // throw new AssertionFailedError("s"); - // } - // } + // void compareAndDumpIfDifferent(LRUCache lruCache, + // T_LRUCache tlruCache) { + // lruCache.dump(); + // tlruCache.dump(); + // if(!lruCache.keyList().equals(tlruCache.ketList())) { + // lruCache.dump(); + // tlruCache.dump(); + // throw new AssertionFailedError("s"); + // } + // } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_Entry.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_Entry.java index 7557fab8a6ed206f0629fb90392107267f83c136..92537bcb3433751c1ee051efe356def1c6ab360a 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_Entry.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_Entry.java @@ -15,31 +15,32 @@ package ch.qos.logback.classic.turbo.lru; public class T_Entry implements Comparable { - K k; - long sequenceNumber; + K k; + long sequenceNumber; - T_Entry(K k, long sn) { - this.k = k; - this.sequenceNumber = sn; - } - - public int compareTo(Object o) { - if(!(o instanceof T_Entry)) { - throw new IllegalArgumentException("arguments must be of type "+T_Entry.class); + T_Entry(K k, long sn) { + this.k = k; + this.sequenceNumber = sn; } - - T_Entry other = (T_Entry) o; - if(sequenceNumber > other.sequenceNumber) { - return 1; + + public int compareTo(Object o) { + if (!(o instanceof T_Entry)) { + throw new IllegalArgumentException("arguments must be of type " + T_Entry.class); + } + + T_Entry other = (T_Entry) o; + if (sequenceNumber > other.sequenceNumber) { + return 1; + } + if (sequenceNumber == other.sequenceNumber) { + return 0; + } + return -1; } - if(sequenceNumber == other.sequenceNumber) { - return 0; + + @Override + public String toString() { + return "(" + k + "," + sequenceNumber + ")"; + // return "("+k+")"; } - return -1; - } - @Override - public String toString() { - return "("+k+","+sequenceNumber+")"; - //return "("+k+")"; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_LRUCache.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_LRUCache.java index 92529f011134183bf2441ecfb7ed75342eafb34f..fe2b55184c24550f4ba5b6788e73511d1ce702b4 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_LRUCache.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/T_LRUCache.java @@ -26,69 +26,67 @@ import java.util.List; */ public class T_LRUCache { - int sequenceNumber; - final int cacheSize; - List> cacheList = new LinkedList>(); + int sequenceNumber; + final int cacheSize; + List> cacheList = new LinkedList>(); - public T_LRUCache(int size) { - this.cacheSize = size; - } - - @SuppressWarnings("unchecked") - synchronized public void put(K k) { - sequenceNumber++; - T_Entry te = getEntry(k); - if (te != null) { - te.sequenceNumber = sequenceNumber; - } else { - te = new T_Entry(k, sequenceNumber); - cacheList.add(te); - } - Collections.sort(cacheList); - while(cacheList.size() > cacheSize) { - cacheList.remove(0); + public T_LRUCache(int size) { + this.cacheSize = size; } - } - @SuppressWarnings("unchecked") - synchronized public K get(K k) { - T_Entry te = getEntry(k); - if (te == null) { - return null; - } else { - te.sequenceNumber = ++sequenceNumber; - Collections.sort(cacheList); - return te.k; + @SuppressWarnings("unchecked") + synchronized public void put(K k) { + sequenceNumber++; + T_Entry te = getEntry(k); + if (te != null) { + te.sequenceNumber = sequenceNumber; + } else { + te = new T_Entry(k, sequenceNumber); + cacheList.add(te); + } + Collections.sort(cacheList); + while (cacheList.size() > cacheSize) { + cacheList.remove(0); + } } - } - synchronized public List keyList() { - List keyList = new ArrayList(); - for (T_Entry e : cacheList) { - keyList.add(e.k); + @SuppressWarnings("unchecked") + synchronized public K get(K k) { + T_Entry te = getEntry(k); + if (te == null) { + return null; + } else { + te.sequenceNumber = ++sequenceNumber; + Collections.sort(cacheList); + return te.k; + } } - return keyList; - } - private T_Entry getEntry(K k) { - for (int i = 0; i < cacheList.size(); i++) { - T_Entry te = cacheList.get(i); - if (te.k.equals(k)) { - return te; - } + synchronized public List keyList() { + List keyList = new ArrayList(); + for (T_Entry e : cacheList) { + keyList.add(e.k); + } + return keyList; } - return null; - } + private T_Entry getEntry(K k) { + for (int i = 0; i < cacheList.size(); i++) { + T_Entry te = cacheList.get(i); + if (te.k.equals(k)) { + return te; + } + } + return null; + } - public void dump() { - System.out.print("T:"); - for (T_Entry te : cacheList) { - //System.out.print(te.toString()+"->"); - System.out.print(te.k+", "); + public void dump() { + System.out.print("T:"); + for (T_Entry te : cacheList) { + // System.out.print(te.toString()+"->"); + System.out.print(te.k + ", "); + } + System.out.println(); } - System.out.println(); - } } - diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/X_LRUCache.java b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/X_LRUCache.java index 6baab27932d25db9bd748f5cc7634df9da5ad12b..b7f667a1d13783910291cec274f9f2a7699dfde6 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/X_LRUCache.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/turbo/lru/X_LRUCache.java @@ -27,25 +27,25 @@ import java.util.Map; * @param */ public class X_LRUCache extends LinkedHashMap { - private static final long serialVersionUID = -6592964689843698200L; + private static final long serialVersionUID = -6592964689843698200L; - final int cacheSize; + final int cacheSize; - public X_LRUCache(int cacheSize) { - super((int) (cacheSize*(4.0f/3)), 0.75f, true); - if(cacheSize < 1) { - throw new IllegalArgumentException("Cache size cannnot be smaller than 1"); - } - this.cacheSize = cacheSize; - } - - protected boolean removeEldestEntry(Map.Entry eldest) { - return (size() > cacheSize); - } - - List keyList() { - ArrayList al = new ArrayList(); - al.addAll(keySet()); - return al; - } + public X_LRUCache(int cacheSize) { + super((int) (cacheSize * (4.0f / 3)), 0.75f, true); + if (cacheSize < 1) { + throw new IllegalArgumentException("Cache size cannnot be smaller than 1"); + } + this.cacheSize = cacheSize; + } + + protected boolean removeEldestEntry(Map.Entry eldest) { + return (size() > cacheSize); + } + + List keyList() { + ArrayList al = new ArrayList(); + al.addAll(keySet()); + return al; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerAutoConfigTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerAutoConfigTest.java index 4299f7106fcd4ef42743bb5b670b6ab1432f374f..bd27b27271947141c39fd7849691b499b074b6bf 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerAutoConfigTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerAutoConfigTest.java @@ -31,30 +31,30 @@ import ch.qos.logback.core.CoreConstants; public class ContextInitializerAutoConfigTest { - org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); - Logger root = (Logger) LoggerFactory.getLogger("root"); - - @Before - public void setUp() throws Exception { - logger.debug("Hello-didily-odily"); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); - System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); - } - - @Test - @Ignore - // this test works only if logback-test.xml or logback.xml files are on the classpath. - // However, this is something we try to avoid in order to simplify the life - // of users trying to follows the manual and logback-examples from an IDE - public void autoconfig() { - LoggerContext iLoggerFactory = (LoggerContext) LoggerFactory.getILoggerFactory(); - iLoggerFactory.reset(); - Appender appender = root.getAppender("STDOUT"); - assertNotNull(appender); - assertTrue(appender instanceof ConsoleAppender); - } + org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); + Logger root = (Logger) LoggerFactory.getLogger("root"); + + @Before + public void setUp() throws Exception { + logger.debug("Hello-didily-odily"); + } + + @After + public void tearDown() throws Exception { + System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); + System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); + } + + @Test + @Ignore + // this test works only if logback-test.xml or logback.xml files are on the classpath. + // However, this is something we try to avoid in order to simplify the life + // of users trying to follows the manual and logback-examples from an IDE + public void autoconfig() { + LoggerContext iLoggerFactory = (LoggerContext) LoggerFactory.getILoggerFactory(); + iLoggerFactory.reset(); + Appender appender = root.getAppender("STDOUT"); + assertNotNull(appender); + assertTrue(appender instanceof ConsoleAppender); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerTest.java index b2ae3ab6c9779c02b3062b1de8ba495bbdd18c05..ad42a2960cb7da18dff0f640d144435911eca901 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/ContextInitializerTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.classic.util; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -50,192 +49,200 @@ import ch.qos.logback.core.util.Loader; public class ContextInitializerTest { - LoggerContext loggerContext = new LoggerContext(); - Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); - System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); - MockConfigurator.context = null; - } - - - @Test - @Ignore - // this test works only if logback-test.xml or logback.xml files are on the classpath. - // However, this is something we try to avoid in order to simplify the life - // of users trying to follow the manual and logback-examples from an IDE - public void reset() throws JoranException { - { - new ContextInitializer(loggerContext).autoConfig(); - Appender appender = root.getAppender("STDOUT"); - assertNotNull(appender); - assertTrue(appender instanceof ConsoleAppender); - } - { - loggerContext.stop(); - Appender appender = root.getAppender("STDOUT"); - assertNull(appender); - } - } - - @Test - public void autoConfigFromSystemProperties() throws JoranException { - doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); - doAutoConfigFromSystemProperties("autoConfigAsResource.xml"); - // test passing a URL. note the relative path syntax with file:src/test/... - doAutoConfigFromSystemProperties("file:"+ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); - } - - public void doAutoConfigFromSystemProperties(String val) throws JoranException { - //lc.reset(); - System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, val); - new ContextInitializer(loggerContext).autoConfig(); - Appender appender = root.getAppender("AUTO_BY_SYSTEM_PROPERTY"); - assertNotNull(appender); - } - - @Test - public void autoConfigFromServiceLoaderJDK6andAbove() throws Exception { - assumeTrue(!isJDK5()); - setupMockServiceLoader(); - assertNull(MockConfigurator.context); - new ContextInitializer(loggerContext).autoConfig(); - assertNotNull(MockConfigurator.context); - assertSame(loggerContext, MockConfigurator.context); - } - - @Test - public void autoConfigFromServiceLoaderJDK5() throws Exception { - assumeTrue(isJDK5()); - setupMockServiceLoader(); - assertNull(MockConfigurator.context); - new ContextInitializer(loggerContext).autoConfig(); - assertNull(MockConfigurator.context); - } - - @Test - public void autoStatusListener() throws JoranException { - System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, TrivialStatusListener.class.getName()); - List statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList(); - assertEquals(0, statusListenerList.size()); - doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); - statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList(); - assertTrue(statusListenerList.size() +" should be 1", statusListenerList.size() == 1); - // LOGBACK-767 - TrivialStatusListener tsl = (TrivialStatusListener) statusListenerList.get(0); - assertTrue("expecting at least one event in list", tsl.list.size() > 0); - } - - @Test - public void autoOnConsoleStatusListener() throws JoranException { - System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, CoreConstants.SYSOUT); - List sll = loggerContext.getStatusManager().getCopyOfStatusListenerList(); - assertEquals(0, sll.size()); - doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); - sll = loggerContext.getStatusManager().getCopyOfStatusListenerList(); - assertTrue(sll.size() +" should be 1", sll.size() == 1); - } - - @Test - public void shouldConfigureFromXmlFile() throws MalformedURLException, JoranException { LoggerContext loggerContext = new LoggerContext(); - ContextInitializer initializer = new ContextInitializer(loggerContext); - assertNull(loggerContext.getObject(CoreConstants.SAFE_JORAN_CONFIGURATION)); + Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - URL configurationFileUrl = Loader.getResource("BOO_logback-test.xml", Thread.currentThread().getContextClassLoader()); - initializer.configureByResource(configurationFileUrl); + @Before + public void setUp() throws Exception { + } - assertNotNull(loggerContext.getObject(CoreConstants.SAFE_JORAN_CONFIGURATION)); - } + @After + public void tearDown() throws Exception { + System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); + System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); + MockConfigurator.context = null; + } - @Test - public void shouldConfigureFromGroovyScript() throws MalformedURLException, JoranException { - LoggerContext loggerContext = new LoggerContext(); - ContextInitializer initializer = new ContextInitializer(loggerContext); - assertNull(loggerContext.getObject(CoreConstants.CONFIGURATION_WATCH_LIST)); + @Test + @Ignore + // this test works only if logback-test.xml or logback.xml files are on the classpath. + // However, this is something we try to avoid in order to simplify the life + // of users trying to follow the manual and logback-examples from an IDE + public void reset() throws JoranException { + { + new ContextInitializer(loggerContext).autoConfig(); + Appender appender = root.getAppender("STDOUT"); + assertNotNull(appender); + assertTrue(appender instanceof ConsoleAppender); + } + { + loggerContext.stop(); + Appender appender = root.getAppender("STDOUT"); + assertNull(appender); + } + } - URL configurationFileUrl = Loader.getResource("test.groovy", Thread.currentThread().getContextClassLoader()); - initializer.configureByResource(configurationFileUrl); + @Test + public void autoConfigFromSystemProperties() throws JoranException { + doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); + doAutoConfigFromSystemProperties("autoConfigAsResource.xml"); + // test passing a URL. note the relative path syntax with file:src/test/... + doAutoConfigFromSystemProperties("file:" + ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); + } - assertNotNull(loggerContext.getObject(CoreConstants.CONFIGURATION_WATCH_LIST)); - } + public void doAutoConfigFromSystemProperties(String val) throws JoranException { + // lc.reset(); + System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, val); + new ContextInitializer(loggerContext).autoConfig(); + Appender appender = root.getAppender("AUTO_BY_SYSTEM_PROPERTY"); + assertNotNull(appender); + } - @Test - public void shouldThrowExceptionIfUnexpectedConfigurationFileExtension() throws JoranException { - LoggerContext loggerContext = new LoggerContext(); - ContextInitializer initializer = new ContextInitializer(loggerContext); - - URL configurationFileUrl = Loader.getResource("README.txt", Thread.currentThread().getContextClassLoader()); - try { - initializer.configureByResource(configurationFileUrl); - fail("Should throw LogbackException"); - } catch (LogbackException expectedException) { - // pass + @Test + public void autoConfigFromServiceLoaderJDK6andAbove() throws Exception { + assumeTrue(!isJDK5()); + setupMockServiceLoader(); + assertNull(MockConfigurator.context); + new ContextInitializer(loggerContext).autoConfig(); + assertNotNull(MockConfigurator.context); + assertSame(loggerContext, MockConfigurator.context); } - } - - private static boolean isJDK5() { - String ver = System.getProperty("java.version"); - boolean jdk5 = ver.startsWith("1.5.") || ver.equals("1.5"); - return jdk5; - } - - private void setupMockServiceLoader() { - final ClassLoader realLoader = EnvUtil.class.getClassLoader(); - EnvUtil.testServiceLoaderClassLoader = new WrappedClassLoader(realLoader) { - - @Override - public Enumeration getResources(String name) throws IOException { - final Enumeration r; - if (name.endsWith("META-INF/services/ch.qos.logback.classic.spi.Configurator")) { - Vector vs = new Vector(); - URL u = super.getResource("FAKE_META_INF_SERVICES_ch_qos_logback_classic_spi_Configurator"); - vs.add(u); - return vs.elements(); - } else { - r = super.getResources(name); - } - return r; - } - }; - } - - static class WrappedClassLoader extends ClassLoader { - final ClassLoader delegate; - public WrappedClassLoader(ClassLoader delegate) { - super(); - this.delegate = delegate; + + @Test + public void autoConfigFromServiceLoaderJDK5() throws Exception { + assumeTrue(isJDK5()); + setupMockServiceLoader(); + assertNull(MockConfigurator.context); + new ContextInitializer(loggerContext).autoConfig(); + assertNull(MockConfigurator.context); } - public Class loadClass(String name) throws ClassNotFoundException { - return delegate.loadClass(name); + + @Test + public void autoStatusListener() throws JoranException { + System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, TrivialStatusListener.class.getName()); + List statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList(); + assertEquals(0, statusListenerList.size()); + doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); + statusListenerList = loggerContext.getStatusManager().getCopyOfStatusListenerList(); + assertTrue(statusListenerList.size() + " should be 1", statusListenerList.size() == 1); + // LOGBACK-767 + TrivialStatusListener tsl = (TrivialStatusListener) statusListenerList.get(0); + assertTrue("expecting at least one event in list", tsl.list.size() > 0); } - public URL getResource(String name) { - return delegate.getResource(name); + + @Test + public void autoOnConsoleStatusListener() throws JoranException { + System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, CoreConstants.SYSOUT); + List sll = loggerContext.getStatusManager().getCopyOfStatusListenerList(); + assertEquals(0, sll.size()); + doAutoConfigFromSystemProperties(ClassicTestConstants.INPUT_PREFIX + "autoConfig.xml"); + sll = loggerContext.getStatusManager().getCopyOfStatusListenerList(); + assertTrue(sll.size() + " should be 1", sll.size() == 1); } - public Enumeration getResources(String name) throws IOException { - return delegate.getResources(name); + + @Test + public void shouldConfigureFromXmlFile() throws MalformedURLException, JoranException { + LoggerContext loggerContext = new LoggerContext(); + ContextInitializer initializer = new ContextInitializer(loggerContext); + assertNull(loggerContext.getObject(CoreConstants.SAFE_JORAN_CONFIGURATION)); + + URL configurationFileUrl = Loader.getResource("BOO_logback-test.xml", Thread.currentThread().getContextClassLoader()); + initializer.configureByResource(configurationFileUrl); + + assertNotNull(loggerContext.getObject(CoreConstants.SAFE_JORAN_CONFIGURATION)); } - public InputStream getResourceAsStream(String name) { - return delegate.getResourceAsStream(name); + + @Test + public void shouldConfigureFromGroovyScript() throws MalformedURLException, JoranException { + LoggerContext loggerContext = new LoggerContext(); + ContextInitializer initializer = new ContextInitializer(loggerContext); + assertNull(loggerContext.getObject(CoreConstants.CONFIGURATION_WATCH_LIST)); + + URL configurationFileUrl = Loader.getResource("test.groovy", Thread.currentThread().getContextClassLoader()); + initializer.configureByResource(configurationFileUrl); + + assertNotNull(loggerContext.getObject(CoreConstants.CONFIGURATION_WATCH_LIST)); } - public void setDefaultAssertionStatus(boolean enabled) { - delegate.setDefaultAssertionStatus(enabled); + + @Test + public void shouldThrowExceptionIfUnexpectedConfigurationFileExtension() throws JoranException { + LoggerContext loggerContext = new LoggerContext(); + ContextInitializer initializer = new ContextInitializer(loggerContext); + + URL configurationFileUrl = Loader.getResource("README.txt", Thread.currentThread().getContextClassLoader()); + try { + initializer.configureByResource(configurationFileUrl); + fail("Should throw LogbackException"); + } catch (LogbackException expectedException) { + // pass + } } - public void setPackageAssertionStatus(String packageName, boolean enabled) { - delegate.setPackageAssertionStatus(packageName, enabled); + + private static boolean isJDK5() { + String ver = System.getProperty("java.version"); + boolean jdk5 = ver.startsWith("1.5.") || ver.equals("1.5"); + return jdk5; } - public void setClassAssertionStatus(String className, boolean enabled) { - delegate.setClassAssertionStatus(className, enabled); + + private void setupMockServiceLoader() { + final ClassLoader realLoader = EnvUtil.class.getClassLoader(); + EnvUtil.testServiceLoaderClassLoader = new WrappedClassLoader(realLoader) { + + @Override + public Enumeration getResources(String name) throws IOException { + final Enumeration r; + if (name.endsWith("META-INF/services/ch.qos.logback.classic.spi.Configurator")) { + Vector vs = new Vector(); + URL u = super.getResource("FAKE_META_INF_SERVICES_ch_qos_logback_classic_spi_Configurator"); + vs.add(u); + return vs.elements(); + } else { + r = super.getResources(name); + } + return r; + } + }; } - public void clearAssertionStatus() { - delegate.clearAssertionStatus(); + + static class WrappedClassLoader extends ClassLoader { + final ClassLoader delegate; + + public WrappedClassLoader(ClassLoader delegate) { + super(); + this.delegate = delegate; + } + + public Class loadClass(String name) throws ClassNotFoundException { + return delegate.loadClass(name); + } + + public URL getResource(String name) { + return delegate.getResource(name); + } + + public Enumeration getResources(String name) throws IOException { + return delegate.getResources(name); + } + + public InputStream getResourceAsStream(String name) { + return delegate.getResourceAsStream(name); + } + + public void setDefaultAssertionStatus(boolean enabled) { + delegate.setDefaultAssertionStatus(enabled); + } + + public void setPackageAssertionStatus(String packageName, boolean enabled) { + delegate.setPackageAssertionStatus(packageName, enabled); + } + + public void setClassAssertionStatus(String className, boolean enabled) { + delegate.setClassAssertionStatus(className, enabled); + } + + public void clearAssertionStatus() { + delegate.clearAssertionStatus(); + } } - } - + } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/InitializationIntegrationTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/InitializationIntegrationTest.java index e0d6123584ed268198a61006c631f53c34551ecf..5ee7def08abbe7f637051be6d0eaf595fe2f2252 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/InitializationIntegrationTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/InitializationIntegrationTest.java @@ -27,11 +27,11 @@ import static org.junit.Assert.assertNotNull; */ public class InitializationIntegrationTest { - @Test - public void smoke() { - Logger logger = (Logger) LoggerFactory.getLogger(this.getClass()); - Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - ListAppender la = (ListAppender) root.getAppender("LIST"); - assertNotNull(la); - } + @Test + public void smoke() { + Logger logger = (Logger) LoggerFactory.getLogger(this.getClass()); + Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + ListAppender la = (ListAppender) root.getAppender("LIST"); + assertNotNull(la); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/LevelToSyslogSeverityTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/LevelToSyslogSeverityTest.java index 5fbc80e70e1551cb9b4e209684b3489b2ea5a381..af14591271fb39a7aaf600f13db0ce94fe330669 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/LevelToSyslogSeverityTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/LevelToSyslogSeverityTest.java @@ -24,30 +24,25 @@ import ch.qos.logback.core.net.SyslogConstants; public class LevelToSyslogSeverityTest { - @Test - public void smoke() { + @Test + public void smoke() { - assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity - .convert(createEventOfLevel(Level.TRACE))); + assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.TRACE))); - assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity - .convert(createEventOfLevel(Level.DEBUG))); + assertEquals(SyslogConstants.DEBUG_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.DEBUG))); - assertEquals(SyslogConstants.INFO_SEVERITY, LevelToSyslogSeverity - .convert(createEventOfLevel(Level.INFO))); + assertEquals(SyslogConstants.INFO_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.INFO))); - assertEquals(SyslogConstants.WARNING_SEVERITY, LevelToSyslogSeverity - .convert(createEventOfLevel(Level.WARN))); + assertEquals(SyslogConstants.WARNING_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.WARN))); - assertEquals(SyslogConstants.ERROR_SEVERITY, LevelToSyslogSeverity - .convert(createEventOfLevel(Level.ERROR))); + assertEquals(SyslogConstants.ERROR_SEVERITY, LevelToSyslogSeverity.convert(createEventOfLevel(Level.ERROR))); - } + } - ILoggingEvent createEventOfLevel(Level level) { - LoggingEvent event = new LoggingEvent(); - event.setLevel(level); - return event; - } + ILoggingEvent createEventOfLevel(Level level) { + LoggingEvent event = new LoggingEvent(); + event.setLevel(level); + return event; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/LogbackMDCAdapterTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/LogbackMDCAdapterTest.java index 74b0c44f23797f3da74566aad9b66f91f021b44f..5c6de129cc1588e7c925b1698a468b9356fa79a9 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/LogbackMDCAdapterTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/LogbackMDCAdapterTest.java @@ -28,230 +28,226 @@ import ch.qos.logback.core.testUtil.RandomUtil; public class LogbackMDCAdapterTest { - final static String A_SUFFIX = "A_SUFFIX"; - final static String B_SUFFIX = "B_SUFFIX"; - - int diff = RandomUtil.getPositiveInt(); - - private final LogbackMDCAdapter mdcAdapter = new LogbackMDCAdapter(); - - /** - * Test that CopyOnInheritThreadLocal does not barf when the - * MDC hashmap is null - * - * @throws InterruptedException - */ - @Test - public void LOGBACK_442() throws InterruptedException { - Map parentHM = getMapFromMDCAdapter(mdcAdapter); - assertNull(parentHM); - - ChildThreadForMDCAdapter childThread = new ChildThreadForMDCAdapter(mdcAdapter); - childThread.start(); - childThread.join(); - assertTrue(childThread.successul); - assertNull(childThread.childHM); - } - - @Test - public void removeForNullKeyTest() { - mdcAdapter.remove(null); - } - - @Test - public void removeInexistentKey() { - mdcAdapter.remove("abcdlw0"); - } - - @Test - public void sequenceWithGet() { - mdcAdapter.put("k0", "v0"); - Map map0 = mdcAdapter.copyOnThreadLocal.get(); - mdcAdapter.get("k0"); - mdcAdapter.put("k1", "v1"); // no map copy required - - // verify that map0 is the same instance and that value was updated - assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); - } - - - @Test - public void sequenceWithGetPropertyMap() { - mdcAdapter.put("k0", "v0"); - Map map0 = mdcAdapter.getPropertyMap(); // point 0 - mdcAdapter.put("k0", "v1"); // new map should be created - // verify that map0 is that in point 0 - assertEquals("v0", map0.get("k0")); - } - - @Test - public void sequenceWithCopyContextMap() { - mdcAdapter.put("k0", "v0"); - Map map0 = mdcAdapter.copyOnThreadLocal.get(); - mdcAdapter.getCopyOfContextMap(); - mdcAdapter.put("k1", "v1"); // no map copy required - - // verify that map0 is the same instance and that value was updated - assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); - } - - - // ================================================= - - /** - * Test that LogbackMDCAdapter does not copy its hashmap when a child - * thread inherits it. - * - * @throws InterruptedException - */ - @Test - public void noCopyOnInheritenceTest() throws InterruptedException { - CountDownLatch countDownLatch = new CountDownLatch(1); - String firstKey = "x" + diff; - String secondKey = "o" + diff; - mdcAdapter.put(firstKey, firstKey + A_SUFFIX); - - ChildThread childThread = new ChildThread(mdcAdapter, firstKey, secondKey, countDownLatch); - childThread.start(); - countDownLatch.await(); - mdcAdapter.put(firstKey, firstKey + B_SUFFIX); - childThread.join(); - - assertNull(mdcAdapter.get(secondKey)); - assertTrue(childThread.successful); - - Map parentHM = getMapFromMDCAdapter(mdcAdapter); - assertTrue(parentHM != childThread.childHM); - - HashMap parentHMWitness = new HashMap(); - parentHMWitness.put(firstKey, firstKey + B_SUFFIX); - assertEquals(parentHMWitness, parentHM); - - HashMap childHMWitness = new HashMap(); - childHMWitness.put(secondKey, secondKey + A_SUFFIX); - assertEquals(childHMWitness, childThread.childHM); - - } - - // see also http://jira.qos.ch/browse/LBCLASSIC-253 - @Test - public void clearOnChildThreadShouldNotAffectParent() throws InterruptedException { - String firstKey = "x" + diff; - String secondKey = "o" + diff; - - mdcAdapter.put(firstKey, firstKey + A_SUFFIX); - assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); - - Thread clearer = new ChildThread(mdcAdapter, firstKey, secondKey) { - @Override - public void run() { - mdcAdapter.clear(); - assertNull(mdcAdapter.get(firstKey)); - } - }; - - clearer.start(); - clearer.join(); - - assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); - } - - // see http://jira.qos.ch/browse/LBCLASSIC-289 - // this test used to fail without synchronization code in LogbackMDCAdapter - @Test - public void nearSimultaneousPutsShouldNotCauseConcurrentModificationException() throws InterruptedException { - // For the weirdest reason, modifications to mdcAdapter must be done - // before the definition anonymous ChildThread class below. Otherwise, the - // map in the child thread, the one contained in mdcAdapter.copyOnInheritThreadLocal, - // is null. How strange is that? - - // let the map have lots of elements so that copying it takes time - for (int i = 0; i < 2048; i++) { - mdcAdapter.put("k" + i, "v" + i); + final static String A_SUFFIX = "A_SUFFIX"; + final static String B_SUFFIX = "B_SUFFIX"; + + int diff = RandomUtil.getPositiveInt(); + + private final LogbackMDCAdapter mdcAdapter = new LogbackMDCAdapter(); + + /** + * Test that CopyOnInheritThreadLocal does not barf when the + * MDC hashmap is null + * + * @throws InterruptedException + */ + @Test + public void LOGBACK_442() throws InterruptedException { + Map parentHM = getMapFromMDCAdapter(mdcAdapter); + assertNull(parentHM); + + ChildThreadForMDCAdapter childThread = new ChildThreadForMDCAdapter(mdcAdapter); + childThread.start(); + childThread.join(); + assertTrue(childThread.successul); + assertNull(childThread.childHM); } - ChildThread childThread = new ChildThread(mdcAdapter, null, null) { - @Override - public void run() { - for (int i = 0; i < 16; i++) { - mdcAdapter.put("ck" + i, "cv" + i); - Thread.yield(); - } - successful = true; - } - }; - + @Test + public void removeForNullKeyTest() { + mdcAdapter.remove(null); + } - childThread.start(); - Thread.sleep(1); - for (int i = 0; i < 16; i++) { - mdcAdapter.put("K" + i, "V" + i); + @Test + public void removeInexistentKey() { + mdcAdapter.remove("abcdlw0"); } - childThread.join(); - assertTrue(childThread.successful); - } + @Test + public void sequenceWithGet() { + mdcAdapter.put("k0", "v0"); + Map map0 = mdcAdapter.copyOnThreadLocal.get(); + mdcAdapter.get("k0"); + mdcAdapter.put("k1", "v1"); // no map copy required - Map getMapFromMDCAdapter(LogbackMDCAdapter lma) { - ThreadLocal> copyOnThreadLocal = lma.copyOnThreadLocal; - return copyOnThreadLocal.get(); - } + // verify that map0 is the same instance and that value was updated + assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); + } - // ========================== various thread classes - class ChildThreadForMDCAdapter extends Thread { + @Test + public void sequenceWithGetPropertyMap() { + mdcAdapter.put("k0", "v0"); + Map map0 = mdcAdapter.getPropertyMap(); // point 0 + mdcAdapter.put("k0", "v1"); // new map should be created + // verify that map0 is that in point 0 + assertEquals("v0", map0.get("k0")); + } - LogbackMDCAdapter logbackMDCAdapter; - boolean successul; - Map childHM; + @Test + public void sequenceWithCopyContextMap() { + mdcAdapter.put("k0", "v0"); + Map map0 = mdcAdapter.copyOnThreadLocal.get(); + mdcAdapter.getCopyOfContextMap(); + mdcAdapter.put("k1", "v1"); // no map copy required - ChildThreadForMDCAdapter(LogbackMDCAdapter logbackMDCAdapter) { - this.logbackMDCAdapter = logbackMDCAdapter; + // verify that map0 is the same instance and that value was updated + assertSame(map0, mdcAdapter.copyOnThreadLocal.get()); } - @Override - public void run() { - childHM = getMapFromMDCAdapter(logbackMDCAdapter); - logbackMDCAdapter.get(""); - successul = true; + // ================================================= + + /** + * Test that LogbackMDCAdapter does not copy its hashmap when a child + * thread inherits it. + * + * @throws InterruptedException + */ + @Test + public void noCopyOnInheritenceTest() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + String firstKey = "x" + diff; + String secondKey = "o" + diff; + mdcAdapter.put(firstKey, firstKey + A_SUFFIX); + + ChildThread childThread = new ChildThread(mdcAdapter, firstKey, secondKey, countDownLatch); + childThread.start(); + countDownLatch.await(); + mdcAdapter.put(firstKey, firstKey + B_SUFFIX); + childThread.join(); + + assertNull(mdcAdapter.get(secondKey)); + assertTrue(childThread.successful); + + Map parentHM = getMapFromMDCAdapter(mdcAdapter); + assertTrue(parentHM != childThread.childHM); + + HashMap parentHMWitness = new HashMap(); + parentHMWitness.put(firstKey, firstKey + B_SUFFIX); + assertEquals(parentHMWitness, parentHM); + + HashMap childHMWitness = new HashMap(); + childHMWitness.put(secondKey, secondKey + A_SUFFIX); + assertEquals(childHMWitness, childThread.childHM); + } - } + // see also http://jira.qos.ch/browse/LBCLASSIC-253 + @Test + public void clearOnChildThreadShouldNotAffectParent() throws InterruptedException { + String firstKey = "x" + diff; + String secondKey = "o" + diff; - class ChildThread extends Thread { + mdcAdapter.put(firstKey, firstKey + A_SUFFIX); + assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); - LogbackMDCAdapter logbackMDCAdapter; - String firstKey; - String secondKey; - boolean successful; - Map childHM; - CountDownLatch countDownLatch; + Thread clearer = new ChildThread(mdcAdapter, firstKey, secondKey) { + @Override + public void run() { + mdcAdapter.clear(); + assertNull(mdcAdapter.get(firstKey)); + } + }; - ChildThread(LogbackMDCAdapter logbackMDCAdapter) { - this(logbackMDCAdapter, null, null); + clearer.start(); + clearer.join(); + + assertEquals(firstKey + A_SUFFIX, mdcAdapter.get(firstKey)); + } + + // see http://jira.qos.ch/browse/LBCLASSIC-289 + // this test used to fail without synchronization code in LogbackMDCAdapter + @Test + public void nearSimultaneousPutsShouldNotCauseConcurrentModificationException() throws InterruptedException { + // For the weirdest reason, modifications to mdcAdapter must be done + // before the definition anonymous ChildThread class below. Otherwise, the + // map in the child thread, the one contained in mdcAdapter.copyOnInheritThreadLocal, + // is null. How strange is that? + + // let the map have lots of elements so that copying it takes time + for (int i = 0; i < 2048; i++) { + mdcAdapter.put("k" + i, "v" + i); + } + + ChildThread childThread = new ChildThread(mdcAdapter, null, null) { + @Override + public void run() { + for (int i = 0; i < 16; i++) { + mdcAdapter.put("ck" + i, "cv" + i); + Thread.yield(); + } + successful = true; + } + }; + + childThread.start(); + Thread.sleep(1); + for (int i = 0; i < 16; i++) { + mdcAdapter.put("K" + i, "V" + i); + } + childThread.join(); + assertTrue(childThread.successful); } - ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey) { - this(logbackMDCAdapter, firstKey, secondKey, null); + Map getMapFromMDCAdapter(LogbackMDCAdapter lma) { + ThreadLocal> copyOnThreadLocal = lma.copyOnThreadLocal; + return copyOnThreadLocal.get(); } - ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey, CountDownLatch countDownLatch) { - super("chil"); - this.logbackMDCAdapter = logbackMDCAdapter; - this.firstKey = firstKey; - this.secondKey = secondKey; - this.countDownLatch = countDownLatch; + // ========================== various thread classes + class ChildThreadForMDCAdapter extends Thread { + + LogbackMDCAdapter logbackMDCAdapter; + boolean successul; + Map childHM; + + ChildThreadForMDCAdapter(LogbackMDCAdapter logbackMDCAdapter) { + this.logbackMDCAdapter = logbackMDCAdapter; + } + + @Override + public void run() { + childHM = getMapFromMDCAdapter(logbackMDCAdapter); + logbackMDCAdapter.get(""); + successul = true; + } } - @Override - public void run() { - logbackMDCAdapter.put(secondKey, secondKey + A_SUFFIX); - assertNull(logbackMDCAdapter.get(firstKey)); - if (countDownLatch != null) countDownLatch.countDown(); - assertNotNull(logbackMDCAdapter.get(secondKey)); - assertEquals(secondKey + A_SUFFIX, logbackMDCAdapter.get(secondKey)); - - successful = true; - childHM = getMapFromMDCAdapter(logbackMDCAdapter); + class ChildThread extends Thread { + + LogbackMDCAdapter logbackMDCAdapter; + String firstKey; + String secondKey; + boolean successful; + Map childHM; + CountDownLatch countDownLatch; + + ChildThread(LogbackMDCAdapter logbackMDCAdapter) { + this(logbackMDCAdapter, null, null); + } + + ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey) { + this(logbackMDCAdapter, firstKey, secondKey, null); + } + + ChildThread(LogbackMDCAdapter logbackMDCAdapter, String firstKey, String secondKey, CountDownLatch countDownLatch) { + super("chil"); + this.logbackMDCAdapter = logbackMDCAdapter; + this.firstKey = firstKey; + this.secondKey = secondKey; + this.countDownLatch = countDownLatch; + } + + @Override + public void run() { + logbackMDCAdapter.put(secondKey, secondKey + A_SUFFIX); + assertNull(logbackMDCAdapter.get(firstKey)); + if (countDownLatch != null) + countDownLatch.countDown(); + assertNotNull(logbackMDCAdapter.get(secondKey)); + assertEquals(secondKey + A_SUFFIX, logbackMDCAdapter.get(secondKey)); + + successful = true; + childHM = getMapFromMDCAdapter(logbackMDCAdapter); + } } - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/LoggerNameUtilTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/LoggerNameUtilTest.java index d3ac852e2f91e359dce7e055e1165ac1db0c8124..e4be285948ee6fc465839f022db521d0ad91eb57 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/LoggerNameUtilTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/LoggerNameUtilTest.java @@ -22,81 +22,80 @@ import static org.junit.Assert.assertEquals; public class LoggerNameUtilTest { - - @Test - public void smoke0() { - List witnessList = new ArrayList(); - witnessList.add("a"); - witnessList.add("b"); - witnessList.add("c"); - List partList = LoggerNameUtil.computeNameParts("a.b.c"); - assertEquals(witnessList, partList); - } - - @Test - public void smoke1() { - List witnessList = new ArrayList(); - witnessList.add("com"); - witnessList.add("foo"); - witnessList.add("Bar"); - List partList = LoggerNameUtil.computeNameParts("com.foo.Bar"); - assertEquals(witnessList, partList); - } - - @Test - public void emptyStringShouldReturnAListContainingOneEmptyString() { - List witnessList = new ArrayList(); - witnessList.add(""); - List partList = LoggerNameUtil.computeNameParts(""); - assertEquals(witnessList, partList); - } - - @Test - public void dotAtLastPositionShouldReturnAListWithAnEmptyStringAsLastElement() { - List witnessList = new ArrayList(); - witnessList.add("com"); - witnessList.add("foo"); - witnessList.add(""); - - List partList = LoggerNameUtil.computeNameParts("com.foo."); - assertEquals(witnessList, partList); - } - - @Test - public void supportNestedClasses() { - List witnessList = new ArrayList(); - witnessList.add("com"); - witnessList.add("foo"); - witnessList.add("Bar"); - witnessList.add("Nested"); - - List partList = LoggerNameUtil.computeNameParts("com.foo.Bar$Nested"); - assertEquals(witnessList, partList); - } - - @Test - public void supportNestedClassesWithNestedDot() { - //LOGBACK-384 - List witnessList = new ArrayList(); - witnessList.add("com"); - witnessList.add("foo"); - witnessList.add("Bar"); - witnessList.add("Nested"); - witnessList.add("dot"); - - List partList = LoggerNameUtil.computeNameParts("com.foo.Bar$Nested.dot"); - assertEquals(witnessList, partList); - } - - @Test - public void supportNestedClassesAtBeginning() { - List witnessList = new ArrayList(); - witnessList.add("foo"); - witnessList.add("Nested"); - witnessList.add("bar"); - - List partList = LoggerNameUtil.computeNameParts("foo$Nested.bar"); - assertEquals(witnessList, partList); - } + @Test + public void smoke0() { + List witnessList = new ArrayList(); + witnessList.add("a"); + witnessList.add("b"); + witnessList.add("c"); + List partList = LoggerNameUtil.computeNameParts("a.b.c"); + assertEquals(witnessList, partList); + } + + @Test + public void smoke1() { + List witnessList = new ArrayList(); + witnessList.add("com"); + witnessList.add("foo"); + witnessList.add("Bar"); + List partList = LoggerNameUtil.computeNameParts("com.foo.Bar"); + assertEquals(witnessList, partList); + } + + @Test + public void emptyStringShouldReturnAListContainingOneEmptyString() { + List witnessList = new ArrayList(); + witnessList.add(""); + List partList = LoggerNameUtil.computeNameParts(""); + assertEquals(witnessList, partList); + } + + @Test + public void dotAtLastPositionShouldReturnAListWithAnEmptyStringAsLastElement() { + List witnessList = new ArrayList(); + witnessList.add("com"); + witnessList.add("foo"); + witnessList.add(""); + + List partList = LoggerNameUtil.computeNameParts("com.foo."); + assertEquals(witnessList, partList); + } + + @Test + public void supportNestedClasses() { + List witnessList = new ArrayList(); + witnessList.add("com"); + witnessList.add("foo"); + witnessList.add("Bar"); + witnessList.add("Nested"); + + List partList = LoggerNameUtil.computeNameParts("com.foo.Bar$Nested"); + assertEquals(witnessList, partList); + } + + @Test + public void supportNestedClassesWithNestedDot() { + // LOGBACK-384 + List witnessList = new ArrayList(); + witnessList.add("com"); + witnessList.add("foo"); + witnessList.add("Bar"); + witnessList.add("Nested"); + witnessList.add("dot"); + + List partList = LoggerNameUtil.computeNameParts("com.foo.Bar$Nested.dot"); + assertEquals(witnessList, partList); + } + + @Test + public void supportNestedClassesAtBeginning() { + List witnessList = new ArrayList(); + witnessList.add("foo"); + witnessList.add("Nested"); + witnessList.add("bar"); + + List partList = LoggerNameUtil.computeNameParts("foo$Nested.bar"); + assertEquals(witnessList, partList); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockConfigurator.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockConfigurator.java index 301e2ec5b2ac7f7fe2d7e002e0bfb8912d2a09a1..69b9fc838405d091bf56bf2ab6b9b82bd435030d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockConfigurator.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockConfigurator.java @@ -19,9 +19,9 @@ import ch.qos.logback.core.spi.ContextAwareBase; public class MockConfigurator extends ContextAwareBase implements Configurator { - static LoggerContext context = null; + static LoggerContext context = null; - public void configure(LoggerContext loggerContext) { - context = loggerContext; - } + public void configure(LoggerContext loggerContext) { + context = loggerContext; + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContext.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContext.java index 837ba3a3dd46c9a277e9d870ecf2449b2a9aadd0..e478da6c34cba78d77a4e066526d8ce01884a2b2 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContext.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContext.java @@ -21,19 +21,19 @@ import javax.naming.NamingException; public class MockInitialContext extends InitialContext { - public Map map = new HashMap(); + public Map map = new HashMap(); - public MockInitialContext() throws NamingException { - super(); - } - - @Override - public Object lookup(String name) throws NamingException { - if (name == null) { - return null; + public MockInitialContext() throws NamingException { + super(); } - return map.get(name); - } + @Override + public Object lookup(String name) throws NamingException { + if (name == null) { + return null; + } + + return map.get(name); + } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContextFactory.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContextFactory.java index 0a779d7c0a3e8b73ae6460d2c6793f87c2b87cbf..7c3b0e124aa5d661406de13ebfab2997efe60c4e 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContextFactory.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/MockInitialContextFactory.java @@ -19,30 +19,28 @@ import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; - public class MockInitialContextFactory implements InitialContextFactory { - static MockInitialContext mic; - - static { - System.out.println("MockInitialContextFactory static called"); - initialize(); - } - - public static void initialize() { - try { - mic = new MockInitialContext(); - } catch (NamingException e) { - e.printStackTrace(); + static MockInitialContext mic; + + static { + System.out.println("MockInitialContextFactory static called"); + initialize(); + } + + public static void initialize() { + try { + mic = new MockInitialContext(); + } catch (NamingException e) { + e.printStackTrace(); + } + } + + public Context getInitialContext(Hashtable environment) throws NamingException { + return mic; + } + + public static MockInitialContext getContext() { + return mic; } - } - - public Context getInitialContext(Hashtable environment) - throws NamingException { - return mic; - } - - public static MockInitialContext getContext() { - return mic; - } } diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/PackageTest.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/PackageTest.java index f21c4ecff7eafb22f5d283688f23f952b5de93c5..af623d6bbc52608782beda650ef27e38a6cfcc94 100755 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/PackageTest.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/PackageTest.java @@ -13,14 +13,11 @@ */ package ch.qos.logback.classic.util; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ContextInitializerTest.class, ContextInitializerAutoConfigTest.class, - LogbackMDCAdapterTest.class, LevelToSyslogSeverityTest.class}) - +@SuiteClasses({ ContextInitializerTest.class, ContextInitializerAutoConfigTest.class, LogbackMDCAdapterTest.class, LevelToSyslogSeverityTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/ch/qos/logback/classic/util/TestHelper.java b/logback-classic/src/test/java/ch/qos/logback/classic/util/TestHelper.java index 7eae9cf83db18ed218b32754bdeb15ae26cc0f0c..ec4368ca56ff852eec7e5be4b67c3a530c37a01d 100644 --- a/logback-classic/src/test/java/ch/qos/logback/classic/util/TestHelper.java +++ b/logback-classic/src/test/java/ch/qos/logback/classic/util/TestHelper.java @@ -18,64 +18,64 @@ import java.lang.reflect.Method; public class TestHelper { - private static final Method ADD_SUPPRESSED_METHOD; + private static final Method ADD_SUPPRESSED_METHOD; - static { - Method method = null; - try { - method = Throwable.class.getMethod("addSuppressed", Throwable.class); - } catch (NoSuchMethodException e) { - // ignore, will get thrown in Java < 7 + static { + Method method = null; + try { + method = Throwable.class.getMethod("addSuppressed", Throwable.class); + } catch (NoSuchMethodException e) { + // ignore, will get thrown in Java < 7 + } + ADD_SUPPRESSED_METHOD = method; } - ADD_SUPPRESSED_METHOD = method; - } - public static boolean suppressedSupported() { - return ADD_SUPPRESSED_METHOD != null; - } + public static boolean suppressedSupported() { + return ADD_SUPPRESSED_METHOD != null; + } - public static void addSuppressed(Throwable outer, Throwable suppressed) throws InvocationTargetException, IllegalAccessException { - if(suppressedSupported()) { - ADD_SUPPRESSED_METHOD.invoke(outer, suppressed); + public static void addSuppressed(Throwable outer, Throwable suppressed) throws InvocationTargetException, IllegalAccessException { + if (suppressedSupported()) { + ADD_SUPPRESSED_METHOD.invoke(outer, suppressed); + } } - } - static public Throwable makeNestedException(int level) { - if (level == 0) { - return new Exception("nesting level=" + level); + static public Throwable makeNestedException(int level) { + if (level == 0) { + return new Exception("nesting level=" + level); + } + Throwable cause = makeNestedException(level - 1); + return new Exception("nesting level =" + level, cause); } - Throwable cause = makeNestedException(level - 1); - return new Exception("nesting level =" + level, cause); - } - /** - * Usage: - *
-   * String s = "123";
-   * positionOf("1").in(s) < positionOf("3").in(s)
-   * 
- * - * @param pattern Plain text to be found - * @return StringPosition fluent interface - */ - public static StringPosition positionOf(String pattern) { - return new StringPosition(pattern); - } + /** + * Usage: + *
+     * String s = "123";
+     * positionOf("1").in(s) < positionOf("3").in(s)
+     * 
+ * + * @param pattern Plain text to be found + * @return StringPosition fluent interface + */ + public static StringPosition positionOf(String pattern) { + return new StringPosition(pattern); + } - public static class StringPosition { - private final String pattern; + public static class StringPosition { + private final String pattern; - public StringPosition(String pattern) { - this.pattern = pattern; - } + public StringPosition(String pattern) { + this.pattern = pattern; + } - public int in(String s) { - final int position = s.indexOf(pattern); - if(position < 0) - throw new IllegalArgumentException("String '" + pattern + "' not found in: '" + s + "'"); - return position; - } + public int in(String s) { + final int position = s.indexOf(pattern); + if (position < 0) + throw new IllegalArgumentException("String '" + pattern + "' not found in: '" + s + "'"); + return position; + } - } + } } diff --git a/logback-classic/src/test/java/integrator/Activator.java b/logback-classic/src/test/java/integrator/Activator.java index 649cf7d78441792c6ca8b2d503d89ad36661b583..b4abb2bf727341b2af9c1575be092b51035c91da 100644 --- a/logback-classic/src/test/java/integrator/Activator.java +++ b/logback-classic/src/test/java/integrator/Activator.java @@ -31,39 +31,38 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class Activator implements BundleActivator { - private BundleContext m_context = null; + private BundleContext m_context = null; - public void start(BundleContext context) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - // the context was probably already configured by default configuration - // rules - lc.reset(); - configurator.doConfigure("src/test/input/osgi/simple.xml"); - } catch (JoranException je) { - je.printStackTrace(); - } - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + public void start(BundleContext context) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + // the context was probably already configured by default configuration + // rules + lc.reset(); + configurator.doConfigure("src/test/input/osgi/simple.xml"); + } catch (JoranException je) { + je.printStackTrace(); + } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.start()"); - m_context = context; - } + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.start()"); + m_context = context; + } - public void stop(BundleContext context) { - m_context = null; - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.stop"); - } + public void stop(BundleContext context) { + m_context = null; + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.stop"); + } - public Bundle[] getBundles() { - if (m_context != null) { - return m_context.getBundles(); + public Bundle[] getBundles() { + if (m_context != null) { + return m_context.getBundles(); + } + return null; } - return null; - } } \ No newline at end of file diff --git a/logback-classic/src/test/java/org/dummy/DummyLBAppender.java b/logback-classic/src/test/java/org/dummy/DummyLBAppender.java index ef0599dce48203e2a82f7429508059a3ecd1ee60..1542a4f0427b3e54761488d01f00b253e0107b0b 100644 --- a/logback-classic/src/test/java/org/dummy/DummyLBAppender.java +++ b/logback-classic/src/test/java/org/dummy/DummyLBAppender.java @@ -22,24 +22,24 @@ import ch.qos.logback.core.AppenderBase; public class DummyLBAppender extends AppenderBase { - public List list = new ArrayList(); - public List stringList = new ArrayList(); - - PatternLayout layout; - - DummyLBAppender() { - this(null); - } - - DummyLBAppender(PatternLayout layout) { - this.layout = layout; - } - - protected void append(ILoggingEvent e) { - list.add(e); - if(layout != null) { - String s = layout.doLayout(e); - stringList.add(s); + public List list = new ArrayList(); + public List stringList = new ArrayList(); + + PatternLayout layout; + + DummyLBAppender() { + this(null); + } + + DummyLBAppender(PatternLayout layout) { + this.layout = layout; + } + + protected void append(ILoggingEvent e) { + list.add(e); + if (layout != null) { + String s = layout.doLayout(e); + stringList.add(s); + } } - } } diff --git a/logback-classic/src/test/java/org/dummy/Log4jInvocation.java b/logback-classic/src/test/java/org/dummy/Log4jInvocation.java index bf8dea7a8e388a70f8666b979ab511ad918c0190..9cd8beb23ecff302c3a580326dbf9d639b1116f7 100644 --- a/logback-classic/src/test/java/org/dummy/Log4jInvocation.java +++ b/logback-classic/src/test/java/org/dummy/Log4jInvocation.java @@ -33,59 +33,58 @@ import ch.qos.logback.classic.spi.ILoggingEvent; */ public class Log4jInvocation { - static final String HELLO = "Hello"; - - DummyLBAppender listAppender; - LoggerContext lc; - ch.qos.logback.classic.Logger rootLogger; - - @Before - public void fixture() { - lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - - listAppender = new DummyLBAppender(); - listAppender.setContext(lc); - listAppender.start(); - rootLogger = lc.getLogger("root"); - rootLogger.addAppender(listAppender); - } - - @Test - public void basic() { - assertEquals(0, listAppender.list.size()); - - Logger logger = Logger.getLogger("basic-test"); - logger.debug(HELLO); - - assertEquals(1, listAppender.list.size()); - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals(HELLO, event.getMessage()); - } - - @Test - public void callerData() { - assertEquals(0, listAppender.list.size()); - - PatternLayout pl = new PatternLayout(); - pl.setPattern("%-5level [%class] %logger - %msg"); - pl.setContext(lc); - pl.start(); - listAppender.layout = pl; - - Logger logger = Logger.getLogger("basic-test"); - logger.trace("none"); - assertEquals(0, listAppender.list.size()); - - rootLogger.setLevel(Level.TRACE); - logger.trace(HELLO); - assertEquals(1, listAppender.list.size()); - - ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); - assertEquals(HELLO, event.getMessage()); - - assertEquals(1, listAppender.stringList.size()); - assertEquals("TRACE [" + Log4jInvocation.class.getName() - + "] basic-test - Hello", listAppender.stringList.get(0)); - } + static final String HELLO = "Hello"; + + DummyLBAppender listAppender; + LoggerContext lc; + ch.qos.logback.classic.Logger rootLogger; + + @Before + public void fixture() { + lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + + listAppender = new DummyLBAppender(); + listAppender.setContext(lc); + listAppender.start(); + rootLogger = lc.getLogger("root"); + rootLogger.addAppender(listAppender); + } + + @Test + public void basic() { + assertEquals(0, listAppender.list.size()); + + Logger logger = Logger.getLogger("basic-test"); + logger.debug(HELLO); + + assertEquals(1, listAppender.list.size()); + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals(HELLO, event.getMessage()); + } + + @Test + public void callerData() { + assertEquals(0, listAppender.list.size()); + + PatternLayout pl = new PatternLayout(); + pl.setPattern("%-5level [%class] %logger - %msg"); + pl.setContext(lc); + pl.start(); + listAppender.layout = pl; + + Logger logger = Logger.getLogger("basic-test"); + logger.trace("none"); + assertEquals(0, listAppender.list.size()); + + rootLogger.setLevel(Level.TRACE); + logger.trace(HELLO); + assertEquals(1, listAppender.list.size()); + + ILoggingEvent event = (ILoggingEvent) listAppender.list.get(0); + assertEquals(HELLO, event.getMessage()); + + assertEquals(1, listAppender.stringList.size()); + assertEquals("TRACE [" + Log4jInvocation.class.getName() + "] basic-test - Hello", listAppender.stringList.get(0)); + } } diff --git a/logback-classic/src/test/java/org/slf4j/LoggerFactoryFriend.java b/logback-classic/src/test/java/org/slf4j/LoggerFactoryFriend.java index abe19a876e7a875d919701e9d0671955ec51ebb9..96e43b6b029f7abf5080e796a240cc4ed0c53f29 100644 --- a/logback-classic/src/test/java/org/slf4j/LoggerFactoryFriend.java +++ b/logback-classic/src/test/java/org/slf4j/LoggerFactoryFriend.java @@ -14,7 +14,7 @@ package org.slf4j; public class LoggerFactoryFriend { - static public void reset() { - LoggerFactory.reset(); - } + static public void reset() { + LoggerFactory.reset(); + } } diff --git a/logback-classic/src/test/java/org/slf4j/impl/InitializationOutputTest.java b/logback-classic/src/test/java/org/slf4j/impl/InitializationOutputTest.java index b9de6c55e9b779ecf5084d2fd4e8916e391cdbb7..6ae991e495bdc6d68ce19f998bdbdbd0578d9964 100644 --- a/logback-classic/src/test/java/org/slf4j/impl/InitializationOutputTest.java +++ b/logback-classic/src/test/java/org/slf4j/impl/InitializationOutputTest.java @@ -33,40 +33,39 @@ import static org.junit.Assert.assertEquals; */ public class InitializationOutputTest { - int diff = RandomUtil.getPositiveInt(); + int diff = RandomUtil.getPositiveInt(); - TeeOutputStream tee; - PrintStream original; + TeeOutputStream tee; + PrintStream original; - @Before - public void setUp() { - original = System.out; - // tee will output bytes on System out but it will also - // collect them so that the output can be compared against - // some expected output data + @Before + public void setUp() { + original = System.out; + // tee will output bytes on System out but it will also + // collect them so that the output can be compared against + // some expected output data - // keep the console quiet - tee = new TeeOutputStream(null); + // keep the console quiet + tee = new TeeOutputStream(null); - // redirect System.out to tee - System.setOut(new PrintStream(tee)); - } + // redirect System.out to tee + System.setOut(new PrintStream(tee)); + } - @After - public void tearDown() { - System.setOut(original); - System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); - System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); - } + @After + public void tearDown() { + System.setOut(original); + System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); + System.clearProperty(CoreConstants.STATUS_LISTENER_CLASS); + } + @Test + public void noOutputIfContextHasAStatusListener() { + System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX + "issue/logback292.xml"); + System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, NopStatusListener.class.getName()); - @Test - public void noOutputIfContextHasAStatusListener() { - System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX + "issue/logback292.xml"); - System.setProperty(CoreConstants.STATUS_LISTENER_CLASS, NopStatusListener.class.getName()); - - StaticLoggerBinderFriend.reset(); - assertEquals(0, tee.baos.size()); - } + StaticLoggerBinderFriend.reset(); + assertEquals(0, tee.baos.size()); + } } diff --git a/logback-classic/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java b/logback-classic/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java index 9b91cf718b688bd4d997f37fe2b8a2b169525f38..929bdb58e2b67609d98c6c6790a848e26677be13 100755 --- a/logback-classic/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java +++ b/logback-classic/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java @@ -23,85 +23,84 @@ import ch.qos.logback.core.read.ListAppender; public class MultithreadedInitializationTest { - final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; - private static AtomicLong EVENT_COUNT = new AtomicLong(0); - final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - - int diff = new Random().nextInt(10000); - String loggerName = "org.slf4j.impl.MultithreadedInitializationTest"; - - @Before - public void setUp() throws Exception { - System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX + "listAppender.xml"); - LoggerFactoryFriend.reset(); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); - } - - @Test - public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { - LoggerAccessingThread[] accessors = harness(); - - for (LoggerAccessingThread accessor : accessors) { - EVENT_COUNT.getAndIncrement(); - accessor.logger.info("post harness"); - } + final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; + private static AtomicLong EVENT_COUNT = new AtomicLong(0); + final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff); - logger.info("hello"); - EVENT_COUNT.getAndIncrement(); + int diff = new Random().nextInt(10000); + String loggerName = "org.slf4j.impl.MultithreadedInitializationTest"; - List events = getRecordedEvents(); - assertEquals(EVENT_COUNT.get(), events.size()); - } + @Before + public void setUp() throws Exception { + System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, ClassicTestConstants.INPUT_PREFIX + "listAppender.xml"); + LoggerFactoryFriend.reset(); + } - private List getRecordedEvents() { - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger(Logger.ROOT_LOGGER_NAME); + @After + public void tearDown() throws Exception { + System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); + } - ListAppender la = (ListAppender) root.getAppender("LIST"); - assertNotNull(la); - return la.list; - } + @Test + public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { + LoggerAccessingThread[] accessors = harness(); - private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { - LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; - final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i] = new LoggerAccessingThread(barrier, i); - threads[i].start(); - } + for (LoggerAccessingThread accessor : accessors) { + EVENT_COUNT.getAndIncrement(); + accessor.logger.info("post harness"); + } + + Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff); + logger.info("hello"); + EVENT_COUNT.getAndIncrement(); - barrier.await(); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i].join(); + List events = getRecordedEvents(); + assertEquals(EVENT_COUNT.get(), events.size()); } - return threads; - } - static class LoggerAccessingThread extends Thread { - final CyclicBarrier barrier; - Logger logger; - int count; + private List getRecordedEvents() { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - LoggerAccessingThread(CyclicBarrier barrier, int count) { - this.barrier = barrier; - this.count = count; + ListAppender la = (ListAppender) root.getAppender("LIST"); + assertNotNull(la); + return la.list; } - public void run() { - try { + private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { + LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; + final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i] = new LoggerAccessingThread(barrier, i); + threads[i].start(); + } + barrier.await(); - } catch (Exception e) { - e.printStackTrace(); - } - logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count); - logger.info("in run method"); - EVENT_COUNT.getAndIncrement(); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i].join(); + } + return threads; } - }; + + static class LoggerAccessingThread extends Thread { + final CyclicBarrier barrier; + Logger logger; + int count; + + LoggerAccessingThread(CyclicBarrier barrier, int count) { + this.barrier = barrier; + this.count = count; + } + + public void run() { + try { + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count); + logger.info("in run method"); + EVENT_COUNT.getAndIncrement(); + } + }; } diff --git a/logback-classic/src/test/java/org/slf4j/impl/PackageTest.java b/logback-classic/src/test/java/org/slf4j/impl/PackageTest.java index 2ae2a80ed0381321382595ea2d25ac076ef1e869..0a13e35a1b2f5468149c66af2cc70195f2f80650 100644 --- a/logback-classic/src/test/java/org/slf4j/impl/PackageTest.java +++ b/logback-classic/src/test/java/org/slf4j/impl/PackageTest.java @@ -20,7 +20,7 @@ import org.junit.runners.Suite.SuiteClasses; import ch.qos.logback.classic.LoggerPerfTest; @RunWith(Suite.class) -@SuiteClasses( { RecursiveInitializationTest.class, LoggerPerfTest.class, InitializationOutputTest.class}) +@SuiteClasses({ RecursiveInitializationTest.class, LoggerPerfTest.class, InitializationOutputTest.class }) public class PackageTest { } \ No newline at end of file diff --git a/logback-classic/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java b/logback-classic/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java index 9ffffeebbb21d2a0d1e43ac2e17a8c5edbc28f6d..35fefc2259c9b166f857a989d9054c7275510b6f 100644 --- a/logback-classic/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java +++ b/logback-classic/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java @@ -31,29 +31,29 @@ import ch.qos.logback.core.util.StatusPrinter; public class RecursiveInitializationTest { - int diff = RandomUtil.getPositiveInt(); - - @Before - public void setUp() throws Exception { - System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "recursiveInit.xml"); - StaticLoggerBinderFriend.reset(); - LoggerFactoryFriend.reset(); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); - } - - @Test - public void recursiveLogbackInitialization() { - Logger logger = LoggerFactory.getLogger("RecursiveInitializationTest" + diff); - logger.info("RecursiveInitializationTest"); - - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); - StatusChecker statusChecker = new StatusChecker(loggerContext); - assertEquals("Was expecting no errors", Status.WARN, statusChecker.getHighestLevel(0)); - } + int diff = RandomUtil.getPositiveInt(); + + @Before + public void setUp() throws Exception { + System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "recursiveInit.xml"); + StaticLoggerBinderFriend.reset(); + LoggerFactoryFriend.reset(); + } + + @After + public void tearDown() throws Exception { + System.clearProperty(ContextInitializer.CONFIG_FILE_PROPERTY); + } + + @Test + public void recursiveLogbackInitialization() { + Logger logger = LoggerFactory.getLogger("RecursiveInitializationTest" + diff); + logger.info("RecursiveInitializationTest"); + + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); + StatusChecker statusChecker = new StatusChecker(loggerContext); + assertEquals("Was expecting no errors", Status.WARN, statusChecker.getHighestLevel(0)); + } } diff --git a/logback-classic/src/test/java/org/slf4j/impl/RecursiveLBAppender.java b/logback-classic/src/test/java/org/slf4j/impl/RecursiveLBAppender.java index b164ea9b908e4162f5bfc00f61da5cb13f61724a..2096618cda1be5c3dd87290582795e5beffc5120 100644 --- a/logback-classic/src/test/java/org/slf4j/impl/RecursiveLBAppender.java +++ b/logback-classic/src/test/java/org/slf4j/impl/RecursiveLBAppender.java @@ -26,32 +26,32 @@ import ch.qos.logback.core.testUtil.RandomUtil; public class RecursiveLBAppender extends AppenderBase { - public List list = new ArrayList(); - public List stringList = new ArrayList(); - - PatternLayout layout; - - public RecursiveLBAppender() { - this(null); - } - - public RecursiveLBAppender(PatternLayout layout) { - this.layout = layout; - } - - @Override - public void start() { - int diff = RandomUtil.getPositiveInt(); - Logger logger = LoggerFactory.getLogger("ResursiveLBAppender"+diff); - logger.info("testing"); - super.start(); - } - - protected void append(ILoggingEvent e) { - list.add(e); - if(layout != null) { - String s = layout.doLayout(e); - stringList.add(s); + public List list = new ArrayList(); + public List stringList = new ArrayList(); + + PatternLayout layout; + + public RecursiveLBAppender() { + this(null); + } + + public RecursiveLBAppender(PatternLayout layout) { + this.layout = layout; + } + + @Override + public void start() { + int diff = RandomUtil.getPositiveInt(); + Logger logger = LoggerFactory.getLogger("ResursiveLBAppender" + diff); + logger.info("testing"); + super.start(); + } + + protected void append(ILoggingEvent e) { + list.add(e); + if (layout != null) { + String s = layout.doLayout(e); + stringList.add(s); + } } - } } diff --git a/logback-classic/src/test/java/org/slf4j/impl/StaticLoggerBinderFriend.java b/logback-classic/src/test/java/org/slf4j/impl/StaticLoggerBinderFriend.java index a2b7880843645680a6b44329cb9a1aa915e7a61d..f93ff5fdd58fb5049af849c6d18bbb4af70ce1df 100644 --- a/logback-classic/src/test/java/org/slf4j/impl/StaticLoggerBinderFriend.java +++ b/logback-classic/src/test/java/org/slf4j/impl/StaticLoggerBinderFriend.java @@ -21,9 +21,9 @@ package org.slf4j.impl; * */ public class StaticLoggerBinderFriend { - - static public void reset() { - StaticLoggerBinder.reset(); - } + + static public void reset() { + StaticLoggerBinder.reset(); + } } diff --git a/logback-classic/src/test/java/org/slf4j/test_osgi/BundleTest.java b/logback-classic/src/test/java/org/slf4j/test_osgi/BundleTest.java index c974444e0dfd2d4580bd4fd7961cd2c259d09af4..6aadd515f5c571c83b32b18e75da4c1fd9e9f473 100644 --- a/logback-classic/src/test/java/org/slf4j/test_osgi/BundleTest.java +++ b/logback-classic/src/test/java/org/slf4j/test_osgi/BundleTest.java @@ -19,30 +19,30 @@ import junit.framework.TestCase; public class BundleTest extends TestCase { - FrameworkErrorListener fel = new FrameworkErrorListener(); - CheckingBundleListener mbl = new CheckingBundleListener(); - - FelixHost felixHost = new FelixHost(fel, mbl); - - protected void setUp() throws Exception { - super.setUp(); - felixHost.doLaunch(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - felixHost.stop(); - } - - public void testSmoke() { - System.out.println("==========="+new File(".").getAbsolutePath()); - mbl.dumpAll(); - // check that the bundle was installed - assertTrue(mbl.exists("iBundle")); - if(fel.errorList.size() != 0) { - fel.dumpAll(); + FrameworkErrorListener fel = new FrameworkErrorListener(); + CheckingBundleListener mbl = new CheckingBundleListener(); + + FelixHost felixHost = new FelixHost(fel, mbl); + + protected void setUp() throws Exception { + super.setUp(); + felixHost.doLaunch(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + felixHost.stop(); + } + + public void testSmoke() { + System.out.println("===========" + new File(".").getAbsolutePath()); + mbl.dumpAll(); + // check that the bundle was installed + assertTrue(mbl.exists("iBundle")); + if (fel.errorList.size() != 0) { + fel.dumpAll(); + } + // check that no errors occured + assertEquals(0, fel.errorList.size()); } - // check that no errors occured - assertEquals(0, fel.errorList.size()); - } } diff --git a/logback-classic/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java b/logback-classic/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java index 025ab2875d7611867f6ebf32a90d31d5ec72100e..4b2779abfd3ff4d017676644f03c19c7342dc4d8 100644 --- a/logback-classic/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java +++ b/logback-classic/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java @@ -22,36 +22,35 @@ import org.osgi.framework.BundleListener; public class CheckingBundleListener implements BundleListener { - List eventList = new ArrayList(); + List eventList = new ArrayList(); - @SuppressWarnings("unchecked") - public void bundleChanged(BundleEvent be) { - eventList.add(be); - } + @SuppressWarnings("unchecked") + public void bundleChanged(BundleEvent be) { + eventList.add(be); + } - private void dump(BundleEvent be) { - System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" - + be.getBundle() + ", type=" + be.getType()); + private void dump(BundleEvent be) { + System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType()); - } + } - public void dumpAll() { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - dump(fe); + public void dumpAll() { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + dump(fe); + } } - } - - boolean exists(String bundleName) { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - Bundle b = fe.getBundle(); - System.out.println("===["+b+"]"); - if (bundleName.equals(b.getSymbolicName())) { - return true; - } + + boolean exists(String bundleName) { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + Bundle b = fe.getBundle(); + System.out.println("===[" + b + "]"); + if (bundleName.equals(b.getSymbolicName())) { + return true; + } + } + return false; } - return false; - } } diff --git a/logback-classic/src/test/java/org/slf4j/test_osgi/FelixHost.java b/logback-classic/src/test/java/org/slf4j/test_osgi/FelixHost.java index af068498ac2936cadc42c80b800333e846c81844..84548398f7cb626015c9160161d54cd8280febb9 100644 --- a/logback-classic/src/test/java/org/slf4j/test_osgi/FelixHost.java +++ b/logback-classic/src/test/java/org/slf4j/test_osgi/FelixHost.java @@ -35,85 +35,76 @@ import org.osgi.framework.Constants; */ public class FelixHost { - private Felix felix = null; - - Properties otherProps = new Properties(); - - final FrameworkErrorListener frameworkErrorListener; - final CheckingBundleListener myBundleListener; - - public FelixHost(FrameworkErrorListener frameworkErrorListener, - CheckingBundleListener myBundleListener) { - this.frameworkErrorListener = frameworkErrorListener; - this.myBundleListener = myBundleListener; - } - - @SuppressWarnings("unchecked") - public void doLaunch() { - // Create a case-insensitive configuration property map. - Map configMap = new StringMap(false); - // Configure the Felix instance to be embedded. - // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true"); - // Add core OSGi packages to be exported from the class path - // via the system bundle. - configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, - "org.osgi.framework; version=1.3.0," - + "org.osgi.service.packageadmin; version=1.2.0," - + "org.osgi.service.startlevel; version=1.0.0," - + "org.osgi.service.url; version=1.0.0"); - - configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, - Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); - - // Explicitly specify the directory to use for caching bundles. - // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache"); - - try { - // Create host activator; - - List list = new ArrayList(); - - // list.add(new HostActivator()); - configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, - "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming"); - configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); - configMap.put("felix.log.level", "4"); - - // Now create an instance of the framework with - // our configuration properties and activator. - felix = new Felix(configMap); - felix.init(); - - // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles"); - - otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, - AutoProcessor.AUTO_DEPLOY_DIR_VALUE); - otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, - AutoProcessor.AUTO_DEPLOY_START_VALUE + "," - + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE); - - BundleContext felixBudleContext = felix.getBundleContext(); - - AutoProcessor.process(otherProps, felixBudleContext); - // listen to errors - felixBudleContext.addFrameworkListener(frameworkErrorListener); - felixBudleContext.addBundleListener(myBundleListener); - // Now start Felix instance. - felix.start(); - System.out.println("felix started"); - - } catch (Exception ex) { - ex.printStackTrace(); + private Felix felix = null; + + Properties otherProps = new Properties(); + + final FrameworkErrorListener frameworkErrorListener; + final CheckingBundleListener myBundleListener; + + public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) { + this.frameworkErrorListener = frameworkErrorListener; + this.myBundleListener = myBundleListener; + } + + @SuppressWarnings("unchecked") + public void doLaunch() { + // Create a case-insensitive configuration property map. + Map configMap = new StringMap(false); + // Configure the Felix instance to be embedded. + // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true"); + // Add core OSGi packages to be exported from the class path + // via the system bundle. + configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0," + + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0"); + + configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + + // Explicitly specify the directory to use for caching bundles. + // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache"); + + try { + // Create host activator; + + List list = new ArrayList(); + + // list.add(new HostActivator()); + configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming"); + configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); + configMap.put("felix.log.level", "4"); + + // Now create an instance of the framework with + // our configuration properties and activator. + felix = new Felix(configMap); + felix.init(); + + // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles"); + + otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE); + otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE); + + BundleContext felixBudleContext = felix.getBundleContext(); + + AutoProcessor.process(otherProps, felixBudleContext); + // listen to errors + felixBudleContext.addFrameworkListener(frameworkErrorListener); + felixBudleContext.addBundleListener(myBundleListener); + // Now start Felix instance. + felix.start(); + System.out.println("felix started"); + + } catch (Exception ex) { + ex.printStackTrace(); + } } - } - public void stop() throws BundleException { - felix.stop(); - } + public void stop() throws BundleException { + felix.stop(); + } - public Bundle[] getInstalledBundles() { - // Use the system bundle activator to gain external - // access to the set of installed bundles. - return null;// m_activator.getBundles(); - } + public Bundle[] getInstalledBundles() { + // Use the system bundle activator to gain external + // access to the set of installed bundles. + return null;// m_activator.getBundles(); + } } \ No newline at end of file diff --git a/logback-classic/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java b/logback-classic/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java index c2df0de832e85f1a3cd0d720b4397391074c0f97..9c7cd64cb7d21e0cee1f384b802fccb4ef21aa32 100644 --- a/logback-classic/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java +++ b/logback-classic/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java @@ -21,32 +21,31 @@ import org.osgi.framework.FrameworkListener; public class FrameworkErrorListener implements FrameworkListener { - public List errorList = new ArrayList(); - - @SuppressWarnings("unchecked") - public void frameworkEvent(FrameworkEvent fe) { - if (fe.getType() == FrameworkEvent.ERROR) { - errorList.add(fe); - } - } - - private void dump(FrameworkEvent fe) { - Throwable t = fe.getThrowable(); - String tString = null; - if (t != null) { - tString = t.toString(); + public List errorList = new ArrayList(); + + @SuppressWarnings("unchecked") + public void frameworkEvent(FrameworkEvent fe) { + if (fe.getType() == FrameworkEvent.ERROR) { + errorList.add(fe); + } } - System.out.println("Framework ERROR:" + ", source " + fe.getSource() - + ", bundle=" + fe.getBundle() + ", ex=" + tString); - if(t != null) { - t.printStackTrace(); + + private void dump(FrameworkEvent fe) { + Throwable t = fe.getThrowable(); + String tString = null; + if (t != null) { + tString = t.toString(); + } + System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString); + if (t != null) { + t.printStackTrace(); + } } - } - public void dumpAll() { - for(int i = 0; i < errorList.size(); i++) { - FrameworkEvent fe = (FrameworkEvent) errorList.get(i); - dump(fe); + public void dumpAll() { + for (int i = 0; i < errorList.size(); i++) { + FrameworkEvent fe = (FrameworkEvent) errorList.get(i); + dump(fe); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/Appender.java b/logback-core/src/main/java/ch/qos/logback/core/Appender.java index af798437ea53a1090f242978d87944dd83d45e4a..581fd8a13208e81dea1967e1bfb0d658180ab98a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/Appender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/Appender.java @@ -12,31 +12,30 @@ * as published by the Free Software Foundation. */ package ch.qos.logback.core; - + import ch.qos.logback.core.spi.ContextAware; import ch.qos.logback.core.spi.FilterAttachable; import ch.qos.logback.core.spi.LifeCycle; - public interface Appender extends LifeCycle, ContextAware, FilterAttachable { - /** - * Get the name of this appender. The name uniquely identifies the appender. - */ - String getName(); + /** + * Get the name of this appender. The name uniquely identifies the appender. + */ + String getName(); + + /** + * This is where an appender accomplishes its work. Note that the argument + * is of type Object. + * @param event + */ + void doAppend(E event) throws LogbackException; - /** - * This is where an appender accomplishes its work. Note that the argument - * is of type Object. - * @param event - */ - void doAppend(E event) throws LogbackException; + /** + * Set the name of this appender. The name is used by other components to + * identify this appender. + * + */ + void setName(String name); - /** - * Set the name of this appender. The name is used by other components to - * identify this appender. - * - */ - void setName(String name); - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/AppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/AppenderBase.java index 589e5febb44c6425d40b248afa7b686c928d0174..f5a27b55a98fb5760d20308ff7c8cf420bde6b00 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/AppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/AppenderBase.java @@ -29,109 +29,106 @@ import ch.qos.logback.core.status.WarnStatus; * * @author Ceki Gülcü */ -abstract public class AppenderBase extends ContextAwareBase implements - Appender { +abstract public class AppenderBase extends ContextAwareBase implements Appender { - protected volatile boolean started = false; + protected volatile boolean started = false; - /** - * The guard prevents an appender from repeatedly calling its own doAppend - * method. - */ - private boolean guard = false; + /** + * The guard prevents an appender from repeatedly calling its own doAppend + * method. + */ + private boolean guard = false; - /** - * Appenders are named. - */ - protected String name; + /** + * Appenders are named. + */ + protected String name; - private FilterAttachableImpl fai = new FilterAttachableImpl(); + private FilterAttachableImpl fai = new FilterAttachableImpl(); - public String getName() { - return name; - } - - private int statusRepeatCount = 0; - private int exceptionCount = 0; + public String getName() { + return name; + } - static final int ALLOWED_REPEATS = 5; + private int statusRepeatCount = 0; + private int exceptionCount = 0; - public synchronized void doAppend(E eventObject) { - // WARNING: The guard check MUST be the first statement in the - // doAppend() method. + static final int ALLOWED_REPEATS = 5; - // prevent re-entry. - if (guard) { - return; - } + public synchronized void doAppend(E eventObject) { + // WARNING: The guard check MUST be the first statement in the + // doAppend() method. - try { - guard = true; + // prevent re-entry. + if (guard) { + return; + } - if (!this.started) { - if (statusRepeatCount++ < ALLOWED_REPEATS) { - addStatus(new WarnStatus( - "Attempted to append to non started appender [" + name + "].", - this)); + try { + guard = true; + + if (!this.started) { + if (statusRepeatCount++ < ALLOWED_REPEATS) { + addStatus(new WarnStatus("Attempted to append to non started appender [" + name + "].", this)); + } + return; + } + + if (getFilterChainDecision(eventObject) == FilterReply.DENY) { + return; + } + + // ok, we now invoke derived class' implementation of append + this.append(eventObject); + + } catch (Exception e) { + if (exceptionCount++ < ALLOWED_REPEATS) { + addError("Appender [" + name + "] failed to append.", e); + } + } finally { + guard = false; } - return; - } - - if (getFilterChainDecision(eventObject) == FilterReply.DENY) { - return; - } - - // ok, we now invoke derived class' implementation of append - this.append(eventObject); - - } catch (Exception e) { - if (exceptionCount++ < ALLOWED_REPEATS) { - addError("Appender [" + name + "] failed to append.", e); - } - } finally { - guard = false; } - } - abstract protected void append(E eventObject); + abstract protected void append(E eventObject); - /** - * Set the name of this appender. - */ - public void setName(String name) { - this.name = name; - } + /** + * Set the name of this appender. + */ + public void setName(String name) { + this.name = name; + } - public void start() { - started = true; - } + public void start() { + started = true; + } - public void stop() { - started = false; - } + public void stop() { + started = false; + } - public boolean isStarted() { - return started; - } + public boolean isStarted() { + return started; + } - public String toString() { - return this.getClass().getName() + "[" + name + "]"; - } + public String toString() { + return this.getClass().getName() + "[" + name + "]"; + } - public void addFilter(Filter newFilter) { - fai.addFilter(newFilter); - } + public void addFilter(Filter newFilter) { + fai.addFilter(newFilter); + } - public void clearAllFilters() { - fai.clearAllFilters(); - } + public void clearAllFilters() { + fai.clearAllFilters(); + } - public List> getCopyOfAttachedFiltersList() { - return fai.getCopyOfAttachedFiltersList(); - } + public List> getCopyOfAttachedFiltersList() { + return fai.getCopyOfAttachedFiltersList(); + } - public FilterReply getFilterChainDecision(E event) { - return fai.getFilterChainDecision(event); - } + public FilterReply getFilterChainDecision(E event) { + return fai.getFilterChainDecision(event); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/AsyncAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/AsyncAppenderBase.java index 437a15c1cb83aa900a8e606ac536d60360cb58a7..d22ee683f959a9f3fc82f06e02ed005f8bc560ba 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/AsyncAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/AsyncAppenderBase.java @@ -38,248 +38,242 @@ import java.util.concurrent.BlockingQueue; */ public class AsyncAppenderBase extends UnsynchronizedAppenderBase implements AppenderAttachable { - AppenderAttachableImpl aai = new AppenderAttachableImpl(); - BlockingQueue blockingQueue; - - /** - * The default buffer size. - */ - public static final int DEFAULT_QUEUE_SIZE = 256; - int queueSize = DEFAULT_QUEUE_SIZE; - - int appenderCount = 0; - - static final int UNDEFINED = -1; - int discardingThreshold = UNDEFINED; - boolean neverBlock = false; - - Worker worker = new Worker(); - - /** - * The default maximum queue flush time allowed during appender stop. If the - * worker takes longer than this time it will exit, discarding any remaining - * items in the queue - */ - public static final int DEFAULT_MAX_FLUSH_TIME = 1000; - int maxFlushTime = DEFAULT_MAX_FLUSH_TIME; - - /** - * Is the eventObject passed as parameter discardable? The base class's implementation of this method always returns - * 'false' but sub-classes may (and do) override this method. - *

- *

Note that only if the buffer is nearly full are events discarded. Otherwise, when the buffer is "not full" - * all events are logged. - * - * @param eventObject - * @return - true if the event can be discarded, false otherwise - */ - protected boolean isDiscardable(E eventObject) { - return false; - } - - - /** - * Pre-process the event prior to queueing. The base class does no pre-processing but sub-classes can - * override this behavior. - * - * @param eventObject - */ - protected void preprocess(E eventObject) { - } - - - @Override - public void start() { - if (appenderCount == 0) { - addError("No attached appenders found."); - return; + AppenderAttachableImpl aai = new AppenderAttachableImpl(); + BlockingQueue blockingQueue; + + /** + * The default buffer size. + */ + public static final int DEFAULT_QUEUE_SIZE = 256; + int queueSize = DEFAULT_QUEUE_SIZE; + + int appenderCount = 0; + + static final int UNDEFINED = -1; + int discardingThreshold = UNDEFINED; + boolean neverBlock = false; + + Worker worker = new Worker(); + + /** + * The default maximum queue flush time allowed during appender stop. If the + * worker takes longer than this time it will exit, discarding any remaining + * items in the queue + */ + public static final int DEFAULT_MAX_FLUSH_TIME = 1000; + int maxFlushTime = DEFAULT_MAX_FLUSH_TIME; + + /** + * Is the eventObject passed as parameter discardable? The base class's implementation of this method always returns + * 'false' but sub-classes may (and do) override this method. + *

+ *

Note that only if the buffer is nearly full are events discarded. Otherwise, when the buffer is "not full" + * all events are logged. + * + * @param eventObject + * @return - true if the event can be discarded, false otherwise + */ + protected boolean isDiscardable(E eventObject) { + return false; } - if (queueSize < 1) { - addError("Invalid queue size [" + queueSize + "]"); - return; + + /** + * Pre-process the event prior to queueing. The base class does no pre-processing but sub-classes can + * override this behavior. + * + * @param eventObject + */ + protected void preprocess(E eventObject) { } - blockingQueue = new ArrayBlockingQueue(queueSize); - - if (discardingThreshold == UNDEFINED) - discardingThreshold = queueSize / 5; - addInfo("Setting discardingThreshold to " + discardingThreshold); - worker.setDaemon(true); - worker.setName("AsyncAppender-Worker-" + getName()); - // make sure this instance is marked as "started" before staring the worker Thread - super.start(); - worker.start(); - } - - @Override - public void stop() { - if (!isStarted()) - return; - - // mark this appender as stopped so that Worker can also processPriorToRemoval if it is invoking aii.appendLoopOnAppenders - // and sub-appenders consume the interruption - super.stop(); - - // interrupt the worker thread so that it can terminate. Note that the interruption can be consumed - // by sub-appenders - worker.interrupt(); - try { - worker.join(maxFlushTime); - - //check to see if the thread ended and if not add a warning message - if(worker.isAlive()) { - addWarn("Max queue flush timeout (" + maxFlushTime + " ms) exceeded. Approximately " + blockingQueue.size() + - " queued events were possibly discarded."); - }else { - addInfo("Queue flush finished successfully within timeout."); - } - - } catch (InterruptedException e) { - addError("Failed to join worker thread. " + blockingQueue.size() + " queued events may be discarded.", e); + + @Override + public void start() { + if (appenderCount == 0) { + addError("No attached appenders found."); + return; + } + if (queueSize < 1) { + addError("Invalid queue size [" + queueSize + "]"); + return; + } + blockingQueue = new ArrayBlockingQueue(queueSize); + + if (discardingThreshold == UNDEFINED) + discardingThreshold = queueSize / 5; + addInfo("Setting discardingThreshold to " + discardingThreshold); + worker.setDaemon(true); + worker.setName("AsyncAppender-Worker-" + getName()); + // make sure this instance is marked as "started" before staring the worker Thread + super.start(); + worker.start(); } - } + @Override + public void stop() { + if (!isStarted()) + return; + + // mark this appender as stopped so that Worker can also processPriorToRemoval if it is invoking + // aii.appendLoopOnAppenders + // and sub-appenders consume the interruption + super.stop(); - @Override - protected void append(E eventObject) { - if (isQueueBelowDiscardingThreshold() && isDiscardable(eventObject)) { - return; + // interrupt the worker thread so that it can terminate. Note that the interruption can be consumed + // by sub-appenders + worker.interrupt(); + try { + worker.join(maxFlushTime); + + // check to see if the thread ended and if not add a warning message + if (worker.isAlive()) { + addWarn("Max queue flush timeout (" + maxFlushTime + " ms) exceeded. Approximately " + blockingQueue.size() + + " queued events were possibly discarded."); + } else { + addInfo("Queue flush finished successfully within timeout."); + } + + } catch (InterruptedException e) { + addError("Failed to join worker thread. " + blockingQueue.size() + " queued events may be discarded.", e); + } } - preprocess(eventObject); - put(eventObject); - } - - private boolean isQueueBelowDiscardingThreshold() { - return (blockingQueue.remainingCapacity() < discardingThreshold); - } - - private void put(E eventObject) { - if (neverBlock) { - blockingQueue.offer(eventObject); - } else { - try { - blockingQueue.put(eventObject); - } catch (InterruptedException e) { - // Interruption of current thread when in doAppend method should not be consumed - // by AsyncAppender - Thread.currentThread().interrupt(); - } + + @Override + protected void append(E eventObject) { + if (isQueueBelowDiscardingThreshold() && isDiscardable(eventObject)) { + return; + } + preprocess(eventObject); + put(eventObject); + } + + private boolean isQueueBelowDiscardingThreshold() { + return (blockingQueue.remainingCapacity() < discardingThreshold); } - } - - public int getQueueSize() { - return queueSize; - } - - public void setQueueSize(int queueSize) { - this.queueSize = queueSize; - } - - public int getDiscardingThreshold() { - return discardingThreshold; - } - - public void setDiscardingThreshold(int discardingThreshold) { - this.discardingThreshold = discardingThreshold; - } - - public int getMaxFlushTime() { - return maxFlushTime; - } - - public void setMaxFlushTime(int maxFlushTime) { - this.maxFlushTime = maxFlushTime; - } - - /** - * Returns the number of elements currently in the blocking queue. - * - * @return number of elements currently in the queue. - */ - public int getNumberOfElementsInQueue() { - return blockingQueue.size(); - } - - - public void setNeverBlock(boolean neverBlock) { - this.neverBlock = neverBlock; - } - - public boolean isNeverBlock() { - return neverBlock; - } - - /** - * The remaining capacity available in the blocking queue. - * - * @return the remaining capacity - * @see {@link java.util.concurrent.BlockingQueue#remainingCapacity()} - */ - public int getRemainingCapacity() { - return blockingQueue.remainingCapacity(); - } - - - - public void addAppender(Appender newAppender) { - if (appenderCount == 0) { - appenderCount++; - addInfo("Attaching appender named ["+newAppender.getName()+"] to AsyncAppender."); - aai.addAppender(newAppender); - } else { - addWarn("One and only one appender may be attached to AsyncAppender."); - addWarn("Ignoring additional appender named [" + newAppender.getName() + "]"); + + private void put(E eventObject) { + if (neverBlock) { + blockingQueue.offer(eventObject); + } else { + try { + blockingQueue.put(eventObject); + } catch (InterruptedException e) { + // Interruption of current thread when in doAppend method should not be consumed + // by AsyncAppender + Thread.currentThread().interrupt(); + } + } } - } - public Iterator> iteratorForAppenders() { - return aai.iteratorForAppenders(); - } + public int getQueueSize() { + return queueSize; + } - public Appender getAppender(String name) { - return aai.getAppender(name); - } + public void setQueueSize(int queueSize) { + this.queueSize = queueSize; + } - public boolean isAttached(Appender eAppender) { - return aai.isAttached(eAppender); - } + public int getDiscardingThreshold() { + return discardingThreshold; + } - public void detachAndStopAllAppenders() { - aai.detachAndStopAllAppenders(); - } + public void setDiscardingThreshold(int discardingThreshold) { + this.discardingThreshold = discardingThreshold; + } - public boolean detachAppender(Appender eAppender) { - return aai.detachAppender(eAppender); - } + public int getMaxFlushTime() { + return maxFlushTime; + } - public boolean detachAppender(String name) { - return aai.detachAppender(name); - } + public void setMaxFlushTime(int maxFlushTime) { + this.maxFlushTime = maxFlushTime; + } - class Worker extends Thread { + /** + * Returns the number of elements currently in the blocking queue. + * + * @return number of elements currently in the queue. + */ + public int getNumberOfElementsInQueue() { + return blockingQueue.size(); + } - public void run() { - AsyncAppenderBase parent = AsyncAppenderBase.this; - AppenderAttachableImpl aai = parent.aai; + public void setNeverBlock(boolean neverBlock) { + this.neverBlock = neverBlock; + } - // loop while the parent is started - while (parent.isStarted()) { - try { - E e = parent.blockingQueue.take(); - aai.appendLoopOnAppenders(e); - } catch (InterruptedException ie) { - break; + public boolean isNeverBlock() { + return neverBlock; + } + + /** + * The remaining capacity available in the blocking queue. + * + * @return the remaining capacity + * @see {@link java.util.concurrent.BlockingQueue#remainingCapacity()} + */ + public int getRemainingCapacity() { + return blockingQueue.remainingCapacity(); + } + + public void addAppender(Appender newAppender) { + if (appenderCount == 0) { + appenderCount++; + addInfo("Attaching appender named [" + newAppender.getName() + "] to AsyncAppender."); + aai.addAppender(newAppender); + } else { + addWarn("One and only one appender may be attached to AsyncAppender."); + addWarn("Ignoring additional appender named [" + newAppender.getName() + "]"); } - } + } - addInfo("Worker thread will flush remaining events before exiting. "); + public Iterator> iteratorForAppenders() { + return aai.iteratorForAppenders(); + } - for (E e : parent.blockingQueue) { - aai.appendLoopOnAppenders(e); - parent.blockingQueue.remove(e); - } - + public Appender getAppender(String name) { + return aai.getAppender(name); + } + + public boolean isAttached(Appender eAppender) { + return aai.isAttached(eAppender); + } + + public void detachAndStopAllAppenders() { + aai.detachAndStopAllAppenders(); + } - aai.detachAndStopAllAppenders(); + public boolean detachAppender(Appender eAppender) { + return aai.detachAppender(eAppender); + } + + public boolean detachAppender(String name) { + return aai.detachAppender(name); + } + + class Worker extends Thread { + + public void run() { + AsyncAppenderBase parent = AsyncAppenderBase.this; + AppenderAttachableImpl aai = parent.aai; + + // loop while the parent is started + while (parent.isStarted()) { + try { + E e = parent.blockingQueue.take(); + aai.appendLoopOnAppenders(e); + } catch (InterruptedException ie) { + break; + } + } + + addInfo("Worker thread will flush remaining events before exiting. "); + + for (E e : parent.blockingQueue) { + aai.appendLoopOnAppenders(e); + parent.blockingQueue.remove(e); + } + + aai.detachAndStopAllAppenders(); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/BasicStatusManager.java b/logback-core/src/main/java/ch/qos/logback/core/BasicStatusManager.java index 2b3a05129bb86844014b44aad116c33d9219ffbe..dc724808da61b795fe42eeb841fd46c3335b8e50 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/BasicStatusManager.java +++ b/logback-core/src/main/java/ch/qos/logback/core/BasicStatusManager.java @@ -25,122 +25,120 @@ import ch.qos.logback.core.status.StatusManager; public class BasicStatusManager implements StatusManager { - public static final int MAX_HEADER_COUNT = 150; - public static final int TAIL_SIZE = 150; - - int count = 0; - - // protected access was requested in http://jira.qos.ch/browse/LBCORE-36 - final protected List statusList = new ArrayList(); - final protected CyclicBuffer tailBuffer = new CyclicBuffer( - TAIL_SIZE); - final protected LogbackLock statusListLock = new LogbackLock(); - - int level = Status.INFO; - - // protected access was requested in http://jira.qos.ch/browse/LBCORE-36 - final protected List statusListenerList = new ArrayList(); - final protected LogbackLock statusListenerListLock = new LogbackLock(); - - // Note on synchronization - // This class contains two separate locks statusListLock and - // statusListenerListLock guarding respectively the statusList+tailBuffer and - // statusListenerList fields. The locks are used internally - // without cycles. They are exposed to derived classes which should be careful - // not to create deadlock cycles. - - /** - * Add a new status object. - * - * @param newStatus - * the status message to add - */ - public void add(Status newStatus) { - // LBCORE-72: fire event before the count check - fireStatusAddEvent(newStatus); - - count++; - if (newStatus.getLevel() > level) { - level = newStatus.getLevel(); - } + public static final int MAX_HEADER_COUNT = 150; + public static final int TAIL_SIZE = 150; + + int count = 0; + + // protected access was requested in http://jira.qos.ch/browse/LBCORE-36 + final protected List statusList = new ArrayList(); + final protected CyclicBuffer tailBuffer = new CyclicBuffer(TAIL_SIZE); + final protected LogbackLock statusListLock = new LogbackLock(); + + int level = Status.INFO; + + // protected access was requested in http://jira.qos.ch/browse/LBCORE-36 + final protected List statusListenerList = new ArrayList(); + final protected LogbackLock statusListenerListLock = new LogbackLock(); + + // Note on synchronization + // This class contains two separate locks statusListLock and + // statusListenerListLock guarding respectively the statusList+tailBuffer and + // statusListenerList fields. The locks are used internally + // without cycles. They are exposed to derived classes which should be careful + // not to create deadlock cycles. + + /** + * Add a new status object. + * + * @param newStatus + * the status message to add + */ + public void add(Status newStatus) { + // LBCORE-72: fire event before the count check + fireStatusAddEvent(newStatus); + + count++; + if (newStatus.getLevel() > level) { + level = newStatus.getLevel(); + } + + synchronized (statusListLock) { + if (statusList.size() < MAX_HEADER_COUNT) { + statusList.add(newStatus); + } else { + tailBuffer.add(newStatus); + } + } - synchronized (statusListLock) { - if (statusList.size() < MAX_HEADER_COUNT) { - statusList.add(newStatus); - } else { - tailBuffer.add(newStatus); - } } - } + public List getCopyOfStatusList() { + synchronized (statusListLock) { + List tList = new ArrayList(statusList); + tList.addAll(tailBuffer.asList()); + return tList; + } + } - public List getCopyOfStatusList() { - synchronized (statusListLock) { - List tList = new ArrayList(statusList); - tList.addAll(tailBuffer.asList()); - return tList; + private void fireStatusAddEvent(Status status) { + synchronized (statusListenerListLock) { + for (StatusListener sl : statusListenerList) { + sl.addStatusEvent(status); + } + } } - } - private void fireStatusAddEvent(Status status) { - synchronized (statusListenerListLock) { - for (StatusListener sl : statusListenerList) { - sl.addStatusEvent(status); - } + public void clear() { + synchronized (statusListLock) { + count = 0; + statusList.clear(); + tailBuffer.clear(); + } } - } - public void clear() { - synchronized (statusListLock) { - count = 0; - statusList.clear(); - tailBuffer.clear(); + public int getLevel() { + return level; } - } - - public int getLevel() { - return level; - } - - public int getCount() { - return count; - } - - /** - * This implementation does not allow duplicate installations of OnConsoleStatusListener - * @param listener - */ - public boolean add(StatusListener listener) { - synchronized (statusListenerListLock) { - if(listener instanceof OnConsoleStatusListener) { - boolean alreadyPresent = checkForPresence(statusListenerList, listener.getClass()); - if(alreadyPresent) - return false; - } - statusListenerList.add(listener); + + public int getCount() { + return count; } - return true; - } - private boolean checkForPresence(List statusListenerList, Class aClass) { - for(StatusListener e: statusListenerList) { - if(e.getClass() == aClass) + /** + * This implementation does not allow duplicate installations of OnConsoleStatusListener + * @param listener + */ + public boolean add(StatusListener listener) { + synchronized (statusListenerListLock) { + if (listener instanceof OnConsoleStatusListener) { + boolean alreadyPresent = checkForPresence(statusListenerList, listener.getClass()); + if (alreadyPresent) + return false; + } + statusListenerList.add(listener); + } return true; } - return false; - } + private boolean checkForPresence(List statusListenerList, Class aClass) { + for (StatusListener e : statusListenerList) { + if (e.getClass() == aClass) + return true; + } + return false; + } - public void remove(StatusListener listener) { - synchronized (statusListenerListLock) { - statusListenerList.remove(listener); + public void remove(StatusListener listener) { + synchronized (statusListenerListLock) { + statusListenerList.remove(listener); + } } - } - public List getCopyOfStatusListenerList() { - synchronized (statusListenerListLock) { - return new ArrayList(statusListenerList); + public List getCopyOfStatusListenerList() { + synchronized (statusListenerListLock) { + return new ArrayList(statusListenerList); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/ConsoleAppender.java b/logback-core/src/main/java/ch/qos/logback/core/ConsoleAppender.java index f1127913bf3f96cffb7e20e7bd2b7790b65f134d..8cba2ddf301061ea3bef49a35cb62a07331d3e01 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/ConsoleAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/ConsoleAppender.java @@ -37,80 +37,78 @@ import ch.qos.logback.core.util.OptionHelper; public class ConsoleAppender extends OutputStreamAppender { - protected ConsoleTarget target = ConsoleTarget.SystemOut; - protected boolean withJansi = false; + protected ConsoleTarget target = ConsoleTarget.SystemOut; + protected boolean withJansi = false; - private final static String WindowsAnsiOutputStream_CLASS_NAME = "org.fusesource.jansi.WindowsAnsiOutputStream"; + private final static String WindowsAnsiOutputStream_CLASS_NAME = "org.fusesource.jansi.WindowsAnsiOutputStream"; - /** - * Sets the value of the Target option. Recognized values are - * "System.out" and "System.err". Any other value will be ignored. - */ - public void setTarget(String value) { - ConsoleTarget t = ConsoleTarget.findByName(value.trim()); - if (t == null) { - targetWarn(value); - } else { - target = t; + /** + * Sets the value of the Target option. Recognized values are + * "System.out" and "System.err". Any other value will be ignored. + */ + public void setTarget(String value) { + ConsoleTarget t = ConsoleTarget.findByName(value.trim()); + if (t == null) { + targetWarn(value); + } else { + target = t; + } } - } - /** - * Returns the current value of the target property. The default value - * of the option is "System.out". - *

- * See also {@link #setTarget}. - */ - public String getTarget() { - return target.getName(); - } + /** + * Returns the current value of the target property. The default value + * of the option is "System.out". + *

+ * See also {@link #setTarget}. + */ + public String getTarget() { + return target.getName(); + } - private void targetWarn(String val) { - Status status = new WarnStatus("[" + val + "] should be one of " - + Arrays.toString(ConsoleTarget.values()), this); - status.add(new WarnStatus( - "Using previously set target, System.out by default.", this)); - addStatus(status); - } + private void targetWarn(String val) { + Status status = new WarnStatus("[" + val + "] should be one of " + Arrays.toString(ConsoleTarget.values()), this); + status.add(new WarnStatus("Using previously set target, System.out by default.", this)); + addStatus(status); + } - @Override - public void start() { - OutputStream targetStream = target.getStream(); - // enable jansi only on Windows and only if withJansi set to true - if (EnvUtil.isWindows() && withJansi) { - targetStream = getTargetStreamForWindows(targetStream); + @Override + public void start() { + OutputStream targetStream = target.getStream(); + // enable jansi only on Windows and only if withJansi set to true + if (EnvUtil.isWindows() && withJansi) { + targetStream = getTargetStreamForWindows(targetStream); + } + setOutputStream(targetStream); + super.start(); } - setOutputStream(targetStream); - super.start(); - } - private OutputStream getTargetStreamForWindows(OutputStream targetStream) { - try { - addInfo("Enabling JANSI WindowsAnsiOutputStream for the console."); - Object windowsAnsiOutputStream = OptionHelper.instantiateByClassNameAndParameter(WindowsAnsiOutputStream_CLASS_NAME, Object.class, context, - OutputStream.class, targetStream); - return (OutputStream) windowsAnsiOutputStream; - } catch (Exception e) { - addWarn("Failed to create WindowsAnsiOutputStream. Falling back on the default stream.", e); + private OutputStream getTargetStreamForWindows(OutputStream targetStream) { + try { + addInfo("Enabling JANSI WindowsAnsiOutputStream for the console."); + Object windowsAnsiOutputStream = OptionHelper.instantiateByClassNameAndParameter(WindowsAnsiOutputStream_CLASS_NAME, Object.class, context, + OutputStream.class, targetStream); + return (OutputStream) windowsAnsiOutputStream; + } catch (Exception e) { + addWarn("Failed to create WindowsAnsiOutputStream. Falling back on the default stream.", e); + } + return targetStream; } - return targetStream; - } - /** - * @return - */ - public boolean isWithJansi() { - return withJansi; - } + /** + * @return + */ + public boolean isWithJansi() { + return withJansi; + } - /** - * If true, this appender will output to a stream which - * - * @param withJansi - * @since 1.0.5 - */ - public void setWithJansi(boolean withJansi) { - this.withJansi = withJansi; - } + /** + * If true, this appender will output to a stream which + * + * @param withJansi + * @since 1.0.5 + */ + public void setWithJansi(boolean withJansi) { + this.withJansi = withJansi; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/Context.java b/logback-core/src/main/java/ch/qos/logback/core/Context.java index b2409642dfccdbb37da4ed8439ce5922fef13e4a..f261eae51adc6b49aa6b481dcda8efd62cb1f429 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/Context.java +++ b/logback-core/src/main/java/ch/qos/logback/core/Context.java @@ -28,101 +28,99 @@ import ch.qos.logback.core.status.StatusManager; */ public interface Context extends PropertyContainer { - /** - * Return the StatusManager instance in use. - * - * @return the {@link StatusManager} instance in use. - */ - StatusManager getStatusManager(); - - /** - * A Context can act as a store for various objects used by LOGBack - * components. - * - * @return The object stored under 'key'. - */ - Object getObject(String key); - - /** - * Store an object under 'key'. If no object can be found, null is returned. - * - * @param key - * @param value - */ - void putObject(String key, Object value); - - /** - * Get all the properties for this context as a Map. Note that the returned - * cop might be a copy not the original. Thus, modifying the returned Map will - * have no effect (on the original.) - * - * @return - */ - // public Map getPropertyMap(); - /** - * Get the property of this context. - */ - String getProperty(String key); - - /** - * Set a property of this context. - */ - void putProperty(String key, String value); - - - /** - * Get a copy of the property map - * @return - * @since 0.9.20 - */ - Map getCopyOfPropertyMap(); - - /** - * Contexts are named objects. - * - * @return the name for this context - */ - String getName(); - - /** - * The name of the context can be set only once. - * - * @param name - */ - void setName(String name); - - /** - * The time at which this context was created, expressed in - * millisecond elapsed since the epoch (1.1.1970). - * - * @return The time as measured when this class was created. - */ - long getBirthTime(); - - /** - * Object used for synchronization purposes. - * INTENDED FOR INTERNAL USAGE. - */ - Object getConfigurationLock(); - - - /** - * Every context has an ExecutorService which be invoked to execute certain - * tasks in a separate thread. - * - * @return the executor for this context. - * @since 1.0.0 - */ - ExecutorService getExecutorService(); - - /** - * Register a component that participates in the context's life cycle. - *

- * All components registered via this method will be stopped and removed - * from the context when the context is reset. - * - * @param component the subject component - */ - void register(LifeCycle component); - + /** + * Return the StatusManager instance in use. + * + * @return the {@link StatusManager} instance in use. + */ + StatusManager getStatusManager(); + + /** + * A Context can act as a store for various objects used by LOGBack + * components. + * + * @return The object stored under 'key'. + */ + Object getObject(String key); + + /** + * Store an object under 'key'. If no object can be found, null is returned. + * + * @param key + * @param value + */ + void putObject(String key, Object value); + + /** + * Get all the properties for this context as a Map. Note that the returned + * cop might be a copy not the original. Thus, modifying the returned Map will + * have no effect (on the original.) + * + * @return + */ + // public Map getPropertyMap(); + /** + * Get the property of this context. + */ + String getProperty(String key); + + /** + * Set a property of this context. + */ + void putProperty(String key, String value); + + /** + * Get a copy of the property map + * @return + * @since 0.9.20 + */ + Map getCopyOfPropertyMap(); + + /** + * Contexts are named objects. + * + * @return the name for this context + */ + String getName(); + + /** + * The name of the context can be set only once. + * + * @param name + */ + void setName(String name); + + /** + * The time at which this context was created, expressed in + * millisecond elapsed since the epoch (1.1.1970). + * + * @return The time as measured when this class was created. + */ + long getBirthTime(); + + /** + * Object used for synchronization purposes. + * INTENDED FOR INTERNAL USAGE. + */ + Object getConfigurationLock(); + + /** + * Every context has an ExecutorService which be invoked to execute certain + * tasks in a separate thread. + * + * @return the executor for this context. + * @since 1.0.0 + */ + ExecutorService getExecutorService(); + + /** + * Register a component that participates in the context's life cycle. + *

+ * All components registered via this method will be stopped and removed + * from the context when the context is reset. + * + * @param component the subject component + */ + void register(LifeCycle component); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/ContextBase.java b/logback-core/src/main/java/ch/qos/logback/core/ContextBase.java index 4de25d089ae399cbc18c236a38f62e292b9f2fe0..2adeb8c242663d495557c33b10b4f128a39afdcf 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/ContextBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/ContextBase.java @@ -28,204 +28,203 @@ import ch.qos.logback.core.util.ExecutorServiceUtil; public class ContextBase implements Context, LifeCycle { - private long birthTime = System.currentTimeMillis(); - - private String name; - private StatusManager sm = new BasicStatusManager(); - // TODO propertyMap should be observable so that we can be notified - // when it changes so that a new instance of propertyMap can be - // serialized. For the time being, we ignore this shortcoming. - Map propertyMap = new HashMap(); - Map objectMap = new HashMap(); - - LogbackLock configurationLock = new LogbackLock(); - - private volatile ExecutorService executorService; - private LifeCycleManager lifeCycleManager; - private boolean started; - - public ContextBase() { - initCollisionMaps(); - } - - public StatusManager getStatusManager() { - return sm; - } - - /** - * Set the {@link StatusManager} for this context. Note that by default this - * context is initialized with a {@link BasicStatusManager}. A null value for - * the 'statusManager' argument is not allowed. - *

- *

A malicious attacker can set the status manager to a dummy instance, - * disabling internal error reporting. - * - * @param statusManager the new status manager - */ - public void setStatusManager(StatusManager statusManager) { - // this method was added in response to http://jira.qos.ch/browse/LBCORE-35 - if (statusManager == null) { - throw new IllegalArgumentException("null StatusManager not allowed"); - } - this.sm = statusManager; - } - - public Map getCopyOfPropertyMap() { - return new HashMap(propertyMap); - } - - public void putProperty(String key, String val) { - this.propertyMap.put(key, val); - } - - protected void initCollisionMaps() { - putObject(FA_FILENAME_COLLISION_MAP, new HashMap()); - putObject(RFA_FILENAME_PATTERN_COLLISION_MAP, new HashMap()); - } - /** - * Given a key, return the corresponding property value. If invoked with - * the special key "CONTEXT_NAME", the name of the context is returned. - * - * @param key - * @return - */ - public String getProperty(String key) { - if (CONTEXT_NAME_KEY.equals(key)) - return getName(); - - return (String) this.propertyMap.get(key); - } - - public Object getObject(String key) { - return objectMap.get(key); - } - - public void putObject(String key, Object value) { - objectMap.put(key, value); - } - - public void removeObject(String key) { - objectMap.remove(key); - } - - - public String getName() { - return name; - } - - public void start() { - // We'd like to create the executor service here, but we can't; - // ContextBase has not always implemented LifeCycle and there are *many* - // uses (mostly in tests) that would need to be modified. - started = true; - } - - public void stop() { - // We don't check "started" here, because the executor service uses - // lazy initialization, rather than being created in the start method - stopExecutorService(); - started = false; - } - - public boolean isStarted() { - return started; - } - - /** - * Clear the internal objectMap and all properties. Removes registered - * shutdown hook - */ - public void reset() { - removeShutdownHook(); - getLifeCycleManager().reset(); - propertyMap.clear(); - objectMap.clear(); - } - - /** - * The context name can be set only if it is not already set, or if the - * current name is the default context name, namely "default", or if the - * current name and the old name are the same. - * - * @throws IllegalStateException if the context already has a name, other than "default". - */ - public void setName(String name) throws IllegalStateException { - if (name != null && name.equals(this.name)) { - return; // idempotent naming - } - if (this.name == null - || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { - this.name = name; - } else { - throw new IllegalStateException("Context has been already given a name"); - } - } - - public long getBirthTime() { - return birthTime; - } - - public Object getConfigurationLock() { - return configurationLock; - } - - public ExecutorService getExecutorService() { - if (executorService == null) { - synchronized (this) { + private long birthTime = System.currentTimeMillis(); + + private String name; + private StatusManager sm = new BasicStatusManager(); + // TODO propertyMap should be observable so that we can be notified + // when it changes so that a new instance of propertyMap can be + // serialized. For the time being, we ignore this shortcoming. + Map propertyMap = new HashMap(); + Map objectMap = new HashMap(); + + LogbackLock configurationLock = new LogbackLock(); + + private volatile ExecutorService executorService; + private LifeCycleManager lifeCycleManager; + private boolean started; + + public ContextBase() { + initCollisionMaps(); + } + + public StatusManager getStatusManager() { + return sm; + } + + /** + * Set the {@link StatusManager} for this context. Note that by default this + * context is initialized with a {@link BasicStatusManager}. A null value for + * the 'statusManager' argument is not allowed. + *

+ *

A malicious attacker can set the status manager to a dummy instance, + * disabling internal error reporting. + * + * @param statusManager the new status manager + */ + public void setStatusManager(StatusManager statusManager) { + // this method was added in response to http://jira.qos.ch/browse/LBCORE-35 + if (statusManager == null) { + throw new IllegalArgumentException("null StatusManager not allowed"); + } + this.sm = statusManager; + } + + public Map getCopyOfPropertyMap() { + return new HashMap(propertyMap); + } + + public void putProperty(String key, String val) { + this.propertyMap.put(key, val); + } + + protected void initCollisionMaps() { + putObject(FA_FILENAME_COLLISION_MAP, new HashMap()); + putObject(RFA_FILENAME_PATTERN_COLLISION_MAP, new HashMap()); + } + + /** + * Given a key, return the corresponding property value. If invoked with + * the special key "CONTEXT_NAME", the name of the context is returned. + * + * @param key + * @return + */ + public String getProperty(String key) { + if (CONTEXT_NAME_KEY.equals(key)) + return getName(); + + return (String) this.propertyMap.get(key); + } + + public Object getObject(String key) { + return objectMap.get(key); + } + + public void putObject(String key, Object value) { + objectMap.put(key, value); + } + + public void removeObject(String key) { + objectMap.remove(key); + } + + public String getName() { + return name; + } + + public void start() { + // We'd like to create the executor service here, but we can't; + // ContextBase has not always implemented LifeCycle and there are *many* + // uses (mostly in tests) that would need to be modified. + started = true; + } + + public void stop() { + // We don't check "started" here, because the executor service uses + // lazy initialization, rather than being created in the start method + stopExecutorService(); + started = false; + } + + public boolean isStarted() { + return started; + } + + /** + * Clear the internal objectMap and all properties. Removes registered + * shutdown hook + */ + public void reset() { + removeShutdownHook(); + getLifeCycleManager().reset(); + propertyMap.clear(); + objectMap.clear(); + } + + /** + * The context name can be set only if it is not already set, or if the + * current name is the default context name, namely "default", or if the + * current name and the old name are the same. + * + * @throws IllegalStateException if the context already has a name, other than "default". + */ + public void setName(String name) throws IllegalStateException { + if (name != null && name.equals(this.name)) { + return; // idempotent naming + } + if (this.name == null || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) { + this.name = name; + } else { + throw new IllegalStateException("Context has been already given a name"); + } + } + + public long getBirthTime() { + return birthTime; + } + + public Object getConfigurationLock() { + return configurationLock; + } + + public ExecutorService getExecutorService() { if (executorService == null) { - executorService = ExecutorServiceUtil.newExecutorService(); + synchronized (this) { + if (executorService == null) { + executorService = ExecutorServiceUtil.newExecutorService(); + } + } } - } - } - return executorService; - } - - private synchronized void stopExecutorService() { - if (executorService != null) { - ExecutorServiceUtil.shutdown(executorService); - executorService = null; - } - } - - private void removeShutdownHook() { - Thread hook = (Thread)getObject(CoreConstants.SHUTDOWN_HOOK_THREAD); - if(hook != null) { - removeObject(CoreConstants.SHUTDOWN_HOOK_THREAD); - try { - Runtime.getRuntime().removeShutdownHook(hook); - } catch(IllegalStateException e) { - //if JVM is already shutting down, ISE is thrown - //no need to do anything else - } - } - } - - public void register(LifeCycle component) { - getLifeCycleManager().register(component); - } - - /** - * Gets the life cycle manager for this context. - *

- * The default implementation lazily initializes an instance of - * {@link LifeCycleManager}. Subclasses may override to provide a custom - * manager implementation, but must take care to return the same manager - * object for each call to this method. - *

- * This is exposed primarily to support instrumentation for unit testing. - * - * @return manager object - */ - synchronized LifeCycleManager getLifeCycleManager() { - if (lifeCycleManager == null) { - lifeCycleManager = new LifeCycleManager(); - } - return lifeCycleManager; - } - - @Override - public String toString() { - return name; - } + return executorService; + } + + private synchronized void stopExecutorService() { + if (executorService != null) { + ExecutorServiceUtil.shutdown(executorService); + executorService = null; + } + } + + private void removeShutdownHook() { + Thread hook = (Thread) getObject(CoreConstants.SHUTDOWN_HOOK_THREAD); + if (hook != null) { + removeObject(CoreConstants.SHUTDOWN_HOOK_THREAD); + try { + Runtime.getRuntime().removeShutdownHook(hook); + } catch (IllegalStateException e) { + // if JVM is already shutting down, ISE is thrown + // no need to do anything else + } + } + } + + public void register(LifeCycle component) { + getLifeCycleManager().register(component); + } + + /** + * Gets the life cycle manager for this context. + *

+ * The default implementation lazily initializes an instance of + * {@link LifeCycleManager}. Subclasses may override to provide a custom + * manager implementation, but must take care to return the same manager + * object for each call to this method. + *

+ * This is exposed primarily to support instrumentation for unit testing. + * + * @return manager object + */ + synchronized LifeCycleManager getLifeCycleManager() { + if (lifeCycleManager == null) { + lifeCycleManager = new LifeCycleManager(); + } + return lifeCycleManager; + } + + @Override + public String toString() { + return name; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/CoreConstants.java b/logback-core/src/main/java/ch/qos/logback/core/CoreConstants.java index ddf623fff8d6488cf9c66736e35247848d01bc4c..bc3a2f877c101ed734a2e01e20863a3a946fbb75 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/CoreConstants.java +++ b/logback-core/src/main/java/ch/qos/logback/core/CoreConstants.java @@ -17,185 +17,175 @@ import ch.qos.logback.core.util.EnvUtil; public class CoreConstants { - final public static String STATUS_LISTENER_CLASS = "logback.statusListenerClass"; - final public static String SYSOUT = "SYSOUT"; - - /** - * Number of idle threads to retain in a context's executor service. - */ - // CORE_POOL_SIZE must be 1 for JDK 1.5. For JDK 1.6 or higher it's set to 0 - // so that there are no idle threads - public static final int CORE_POOL_SIZE = EnvUtil.isJDK5() ? 1 : 0; - - /** - * Maximum number of threads to allow in a context's executor service. - */ - // if you need a different MAX_POOL_SIZE, please file create a jira issue - // asking to make MAX_POOL_SIZE a parameter. - public static final int MAX_POOL_SIZE = 32; - - // Note that the line.separator property can be looked up even by - // applets. - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final int LINE_SEPARATOR_LEN = LINE_SEPARATOR.length(); - - - public static final String CODES_URL = "http://logback.qos.ch/codes.html"; - public static final String MORE_INFO_PREFIX = "For more information, please visit "; - - /** - * The default context name. - */ - public static final String DEFAULT_CONTEXT_NAME = "default"; - /** - * Customized pattern conversion rules are stored under this key in the - * {@link Context} object store. - */ - public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY"; - - public static final String ISO8601_STR = "ISO8601"; - public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; - public static final String DAILY_DATE_PATTERN = "yyyy-MM-dd"; - - /** - * Time format used in Common Log Format - */ - public static final String CLF_DATE_PATTERN = "dd/MMM/yyyy:HH:mm:ss Z"; - - /** - * The key used in locating the evaluator map in context's object map. - */ - public static final String EVALUATOR_MAP = "EVALUATOR_MAP"; - - - /** - * Key used to locate a collision map for FileAppender instances in context's object map. - * - * The collision map consists of enties of the type (appender name, File option) - */ - public static final String FA_FILENAME_COLLISION_MAP = "RFA_FILENAME_COLLISION_MAP"; - - /** - * Key used to locate a collision map for RollingFileAppender instances in context's object map. - * - * The collision map consists of entities of the type (appender name, FileNamePattern option) - */ - public static final String RFA_FILENAME_PATTERN_COLLISION_MAP = "RFA_FILENAME_PATTERN_COLLISION_MAP"; - - /** - * By convention, we assume that the static method named "valueOf" taking - * a string argument can restore a given object from its string - * representation. - */ - public static final String VALUE_OF = "valueOf"; - - /** - * An empty string. - */ - public static final String EMPTY_STRING = ""; - - /** - * An empty string array. - */ - public static final String[] EMPTY_STRING_ARRAY = new String[]{}; - - /** - * An empty Class array. - */ - public static final Class[] EMPTY_CLASS_ARRAY = new Class[]{}; - public static final String CAUSED_BY = "Caused by: "; - public static final String SUPPRESSED = "Suppressed: "; - public static final String WRAPPED_BY = "Wrapped by: "; - - public static final char PERCENT_CHAR = '%'; - public static final char LEFT_PARENTHESIS_CHAR = '('; - public static final char RIGHT_PARENTHESIS_CHAR = ')'; - - public static final char ESCAPE_CHAR = '\\'; - public static final char CURLY_LEFT = '{'; - public static final char CURLY_RIGHT = '}'; - public static final char COMMA_CHAR = ','; - public static final char DOUBLE_QUOTE_CHAR = '"'; - public static final char SINGLE_QUOTE_CHAR = '\''; - public static final char COLON_CHAR = ':'; - public static final char DASH_CHAR = '-'; - public static final String DEFAULT_VALUE_SEPARATOR = ":-"; - - - /** - * Number of rows before in an HTML table before, - * we close the table and create a new one - */ - public static final int TABLE_ROW_LIMIT = 10000; - - - // reset the ObjectOutputStream every OOS_RESET_FREQUENCY calls - // this avoid serious memory leaks - public static final int OOS_RESET_FREQUENCY = 70; - - /** - * The reference bogo instructions per second on - * Ceki's machine (Orion) - */ - public static long REFERENCE_BIPS = 9000; - - - // the max number of times an error should be reported - public static final int MAX_ERROR_COUNT = 4; - - - public static final char DOT = '.'; - public static final char TAB = '\t'; - public static final char DOLLAR = '$'; - - public static final String SEE_FNP_NOT_SET = "See also http://logback.qos.ch/codes.html#tbr_fnp_not_set"; - public static final String SEE_MISSING_INTEGER_TOKEN = "See also http://logback.qos.ch/codes.html#sat_missing_integer_token"; - - public static final String CONFIGURATION_WATCH_LIST = "CONFIGURATION_WATCH_LIST"; - public static final String CONFIGURATION_WATCH_LIST_RESET = "CONFIGURATION_WATCH_LIST_RESET"; - - public static final String SAFE_JORAN_CONFIGURATION = "SAFE_JORAN_CONFIGURATION"; - public static final String XML_PARSING = "XML_PARSING"; - - // Context Object name for the shutdown hook - public static final String SHUTDOWN_HOOK_THREAD = "SHUTDOWN_HOOK"; - - - - /** - * The key under which the local host name is registered in the logger - * context. - */ - public static final String HOSTNAME_KEY = "HOSTNAME"; - - /** - * The key under which the current context name is registered in the logger - * context. - */ - public static final String CONTEXT_NAME_KEY = "CONTEXT_NAME"; - - - public static final int BYTES_PER_INT = 4; - public static final long MILLIS_IN_ONE_SECOND = 1000; - public static final long MILLIS_IN_ONE_MINUTE = MILLIS_IN_ONE_SECOND*60; - public static final long MILLIS_IN_ONE_HOUR = MILLIS_IN_ONE_MINUTE*60; - public static final long MILLIS_IN_ONE_DAY = MILLIS_IN_ONE_HOUR*24; - public static final long MILLIS_IN_ONE_WEEK = MILLIS_IN_ONE_DAY*7; - - /** - * The number of seconds to wait for compression jobs to finish. - */ - public static final int SECONDS_TO_WAIT_FOR_COMPRESSION_JOBS = 30; - - public static final String CONTEXT_SCOPE_VALUE = "context"; - - public static final String RESET_MSG_PREFIX = "Will reset and reconfigure context "; - - - public static final String JNDI_COMP_PREFIX = "java:comp/env"; - - public static final String UNDEFINED_PROPERTY_SUFFIX = "_IS_UNDEFINED"; - - public static final String LEFT_ACCOLADE = new String(new char[] {CURLY_LEFT}); - public static final String RIGHT_ACCOLADE = new String(new char[] {CURLY_RIGHT}); + final public static String STATUS_LISTENER_CLASS = "logback.statusListenerClass"; + final public static String SYSOUT = "SYSOUT"; + + /** + * Number of idle threads to retain in a context's executor service. + */ + // CORE_POOL_SIZE must be 1 for JDK 1.5. For JDK 1.6 or higher it's set to 0 + // so that there are no idle threads + public static final int CORE_POOL_SIZE = EnvUtil.isJDK5() ? 1 : 0; + + /** + * Maximum number of threads to allow in a context's executor service. + */ + // if you need a different MAX_POOL_SIZE, please file create a jira issue + // asking to make MAX_POOL_SIZE a parameter. + public static final int MAX_POOL_SIZE = 32; + + // Note that the line.separator property can be looked up even by + // applets. + public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + public static final int LINE_SEPARATOR_LEN = LINE_SEPARATOR.length(); + + public static final String CODES_URL = "http://logback.qos.ch/codes.html"; + public static final String MORE_INFO_PREFIX = "For more information, please visit "; + + /** + * The default context name. + */ + public static final String DEFAULT_CONTEXT_NAME = "default"; + /** + * Customized pattern conversion rules are stored under this key in the + * {@link Context} object store. + */ + public static final String PATTERN_RULE_REGISTRY = "PATTERN_RULE_REGISTRY"; + + public static final String ISO8601_STR = "ISO8601"; + public static final String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; + public static final String DAILY_DATE_PATTERN = "yyyy-MM-dd"; + + /** + * Time format used in Common Log Format + */ + public static final String CLF_DATE_PATTERN = "dd/MMM/yyyy:HH:mm:ss Z"; + + /** + * The key used in locating the evaluator map in context's object map. + */ + public static final String EVALUATOR_MAP = "EVALUATOR_MAP"; + + /** + * Key used to locate a collision map for FileAppender instances in context's object map. + * + * The collision map consists of enties of the type (appender name, File option) + */ + public static final String FA_FILENAME_COLLISION_MAP = "RFA_FILENAME_COLLISION_MAP"; + + /** + * Key used to locate a collision map for RollingFileAppender instances in context's object map. + * + * The collision map consists of entities of the type (appender name, FileNamePattern option) + */ + public static final String RFA_FILENAME_PATTERN_COLLISION_MAP = "RFA_FILENAME_PATTERN_COLLISION_MAP"; + + /** + * By convention, we assume that the static method named "valueOf" taking + * a string argument can restore a given object from its string + * representation. + */ + public static final String VALUE_OF = "valueOf"; + + /** + * An empty string. + */ + public static final String EMPTY_STRING = ""; + + /** + * An empty string array. + */ + public static final String[] EMPTY_STRING_ARRAY = new String[] {}; + + /** + * An empty Class array. + */ + public static final Class[] EMPTY_CLASS_ARRAY = new Class[] {}; + public static final String CAUSED_BY = "Caused by: "; + public static final String SUPPRESSED = "Suppressed: "; + public static final String WRAPPED_BY = "Wrapped by: "; + + public static final char PERCENT_CHAR = '%'; + public static final char LEFT_PARENTHESIS_CHAR = '('; + public static final char RIGHT_PARENTHESIS_CHAR = ')'; + + public static final char ESCAPE_CHAR = '\\'; + public static final char CURLY_LEFT = '{'; + public static final char CURLY_RIGHT = '}'; + public static final char COMMA_CHAR = ','; + public static final char DOUBLE_QUOTE_CHAR = '"'; + public static final char SINGLE_QUOTE_CHAR = '\''; + public static final char COLON_CHAR = ':'; + public static final char DASH_CHAR = '-'; + public static final String DEFAULT_VALUE_SEPARATOR = ":-"; + + /** + * Number of rows before in an HTML table before, + * we close the table and create a new one + */ + public static final int TABLE_ROW_LIMIT = 10000; + + // reset the ObjectOutputStream every OOS_RESET_FREQUENCY calls + // this avoid serious memory leaks + public static final int OOS_RESET_FREQUENCY = 70; + + /** + * The reference bogo instructions per second on + * Ceki's machine (Orion) + */ + public static long REFERENCE_BIPS = 9000; + + // the max number of times an error should be reported + public static final int MAX_ERROR_COUNT = 4; + + public static final char DOT = '.'; + public static final char TAB = '\t'; + public static final char DOLLAR = '$'; + + public static final String SEE_FNP_NOT_SET = "See also http://logback.qos.ch/codes.html#tbr_fnp_not_set"; + public static final String SEE_MISSING_INTEGER_TOKEN = "See also http://logback.qos.ch/codes.html#sat_missing_integer_token"; + + public static final String CONFIGURATION_WATCH_LIST = "CONFIGURATION_WATCH_LIST"; + public static final String CONFIGURATION_WATCH_LIST_RESET = "CONFIGURATION_WATCH_LIST_RESET"; + + public static final String SAFE_JORAN_CONFIGURATION = "SAFE_JORAN_CONFIGURATION"; + public static final String XML_PARSING = "XML_PARSING"; + + // Context Object name for the shutdown hook + public static final String SHUTDOWN_HOOK_THREAD = "SHUTDOWN_HOOK"; + + /** + * The key under which the local host name is registered in the logger + * context. + */ + public static final String HOSTNAME_KEY = "HOSTNAME"; + + /** + * The key under which the current context name is registered in the logger + * context. + */ + public static final String CONTEXT_NAME_KEY = "CONTEXT_NAME"; + + public static final int BYTES_PER_INT = 4; + public static final long MILLIS_IN_ONE_SECOND = 1000; + public static final long MILLIS_IN_ONE_MINUTE = MILLIS_IN_ONE_SECOND * 60; + public static final long MILLIS_IN_ONE_HOUR = MILLIS_IN_ONE_MINUTE * 60; + public static final long MILLIS_IN_ONE_DAY = MILLIS_IN_ONE_HOUR * 24; + public static final long MILLIS_IN_ONE_WEEK = MILLIS_IN_ONE_DAY * 7; + + /** + * The number of seconds to wait for compression jobs to finish. + */ + public static final int SECONDS_TO_WAIT_FOR_COMPRESSION_JOBS = 30; + + public static final String CONTEXT_SCOPE_VALUE = "context"; + + public static final String RESET_MSG_PREFIX = "Will reset and reconfigure context "; + + public static final String JNDI_COMP_PREFIX = "java:comp/env"; + + public static final String UNDEFINED_PROPERTY_SUFFIX = "_IS_UNDEFINED"; + + public static final String LEFT_ACCOLADE = new String(new char[] { CURLY_LEFT }); + public static final String RIGHT_ACCOLADE = new String(new char[] { CURLY_RIGHT }); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/FileAppender.java b/logback-core/src/main/java/ch/qos/logback/core/FileAppender.java index 93b50589bc81dc83aede4b164ae5183048c91a9d..9ce08350d4a7ab5761ce7804422f9c3a619bdfa4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/FileAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/FileAppender.java @@ -36,227 +36,224 @@ import ch.qos.logback.core.util.FileUtil; */ public class FileAppender extends OutputStreamAppender { - static protected String COLLISION_WITH_EARLIER_APPENDER_URL = CODES_URL + "#earlier_fa_collision"; - - /** - * Append to or truncate the file? The default value for this variable is - * true, meaning that by default a FileAppender will - * append to an existing file and not truncate it. - */ - protected boolean append = true; + static protected String COLLISION_WITH_EARLIER_APPENDER_URL = CODES_URL + "#earlier_fa_collision"; - /** - * The name of the active log file. - */ - protected String fileName = null; + /** + * Append to or truncate the file? The default value for this variable is + * true, meaning that by default a FileAppender will + * append to an existing file and not truncate it. + */ + protected boolean append = true; - private boolean prudent = false; + /** + * The name of the active log file. + */ + protected String fileName = null; - /** - * The File property takes a string value which should be the name of - * the file to append to. - */ - public void setFile(String file) { - if (file == null) { - fileName = file; - } else { - // Trim spaces from both ends. The users probably does not want - // trailing spaces in file names. - fileName = file.trim(); + private boolean prudent = false; + + /** + * The File property takes a string value which should be the name of + * the file to append to. + */ + public void setFile(String file) { + if (file == null) { + fileName = file; + } else { + // Trim spaces from both ends. The users probably does not want + // trailing spaces in file names. + fileName = file.trim(); + } } - } - /** - * Returns the value of the Append property. - */ - public boolean isAppend() { - return append; - } + /** + * Returns the value of the Append property. + */ + public boolean isAppend() { + return append; + } - /** - * This method is used by derived classes to obtain the raw file property. - * Regular users should not be calling this method. - * - * @return the value of the file property - */ - final public String rawFileProperty() { - return fileName; - } + /** + * This method is used by derived classes to obtain the raw file property. + * Regular users should not be calling this method. + * + * @return the value of the file property + */ + final public String rawFileProperty() { + return fileName; + } - /** - * Returns the value of the File property. - * - *

- * This method may be overridden by derived classes. - * - */ - public String getFile() { - return fileName; - } + /** + * Returns the value of the File property. + * + *

+ * This method may be overridden by derived classes. + * + */ + public String getFile() { + return fileName; + } - /** - * If the value of File is not null, then - * {@link #openFile} is called with the values of File and - * Append properties. - */ - public void start() { - int errors = 0; - if (getFile() != null) { - addInfo("File property is set to [" + fileName + "]"); - - if(checkForFileCollisionInPreviousFileAppenders()) { - addError("Collisions detected with FileAppender/RollingAppender instances defined earlier. Aborting."); - addError(MORE_INFO_PREFIX+COLLISION_WITH_EARLIER_APPENDER_URL); - errors++; - } - - if (prudent) { - if (!isAppend()) { - setAppend(true); - addWarn("Setting \"Append\" property to true on account of \"Prudent\" mode"); - } - } + /** + * If the value of File is not null, then + * {@link #openFile} is called with the values of File and + * Append properties. + */ + public void start() { + int errors = 0; + if (getFile() != null) { + addInfo("File property is set to [" + fileName + "]"); - try { - openFile(getFile()); - } catch (java.io.IOException e) { - errors++; - addError("openFile(" + fileName + "," + append + ") call failed.", e); - } - } else { - errors++; - addError("\"File\" property not set for appender named [" + name + "]."); - } - if (errors == 0) { - super.start(); - } - } - - protected boolean checkForFileCollisionInPreviousFileAppenders() { - boolean collisionsDetected = false; - if (fileName == null) { - return false; - } - @SuppressWarnings("unchecked") - Map map = (Map) context.getObject(CoreConstants.RFA_FILENAME_PATTERN_COLLISION_MAP); - if (map == null) { - return collisionsDetected; - } - for (Entry entry : map.entrySet()) { - if (fileName.equals(entry.getValue())) { - addErrorForCollision("File", entry.getValue(), entry.getKey()); - collisionsDetected = true; - } - } - if (name != null) { - map.put(getName(), fileName); - } - return collisionsDetected; - } + if (checkForFileCollisionInPreviousFileAppenders()) { + addError("Collisions detected with FileAppender/RollingAppender instances defined earlier. Aborting."); + addError(MORE_INFO_PREFIX + COLLISION_WITH_EARLIER_APPENDER_URL); + errors++; + } - protected void addErrorForCollision(String optionName, String optionValue, String appenderName) { - addError("'"+optionName+"' option has the same value \""+optionValue+"\" as that given for appender [" + appenderName+"] defined earlier."); - } + if (prudent) { + if (!isAppend()) { + setAppend(true); + addWarn("Setting \"Append\" property to true on account of \"Prudent\" mode"); + } + } - /** - *

- * Sets and opens the file where the log output will go. The specified - * file must be writable. - * - *

- * If there was already an opened file, then the previous file is closed - * first. - * - *

- * Do not use this method directly. To configure a FileAppender or one of - * its subclasses, set its properties one by one and then call start(). - * - * @param file_name - * The path to the log file. - */ - public void openFile(String file_name) throws IOException { - lock.lock(); - try { - File file = new File(file_name); - boolean result = FileUtil.createMissingParentDirectories(file); - if (!result) { - addError("Failed to create parent directories for [" - + file.getAbsolutePath() + "]"); - } + try { + openFile(getFile()); + } catch (java.io.IOException e) { + errors++; + addError("openFile(" + fileName + "," + append + ") call failed.", e); + } + } else { + errors++; + addError("\"File\" property not set for appender named [" + name + "]."); + } + if (errors == 0) { + super.start(); + } + } - ResilientFileOutputStream resilientFos = new ResilientFileOutputStream( - file, append); - resilientFos.setContext(context); - setOutputStream(resilientFos); - } finally { - lock.unlock(); + protected boolean checkForFileCollisionInPreviousFileAppenders() { + boolean collisionsDetected = false; + if (fileName == null) { + return false; + } + @SuppressWarnings("unchecked") + Map map = (Map) context.getObject(CoreConstants.RFA_FILENAME_PATTERN_COLLISION_MAP); + if (map == null) { + return collisionsDetected; + } + for (Entry entry : map.entrySet()) { + if (fileName.equals(entry.getValue())) { + addErrorForCollision("File", entry.getValue(), entry.getKey()); + collisionsDetected = true; + } + } + if (name != null) { + map.put(getName(), fileName); + } + return collisionsDetected; } - } - /** - * @see #setPrudent(boolean) - * - * @return true if in prudent mode - */ - public boolean isPrudent() { - return prudent; - } + protected void addErrorForCollision(String optionName, String optionValue, String appenderName) { + addError("'" + optionName + "' option has the same value \"" + optionValue + "\" as that given for appender [" + appenderName + "] defined earlier."); + } - /** - * When prudent is set to true, file appenders from multiple JVMs can safely - * write to the same file. - * - * @param prudent - */ - public void setPrudent(boolean prudent) { - this.prudent = prudent; - } + /** + *

+ * Sets and opens the file where the log output will go. The specified + * file must be writable. + * + *

+ * If there was already an opened file, then the previous file is closed + * first. + * + *

+ * Do not use this method directly. To configure a FileAppender or one of + * its subclasses, set its properties one by one and then call start(). + * + * @param file_name + * The path to the log file. + */ + public void openFile(String file_name) throws IOException { + lock.lock(); + try { + File file = new File(file_name); + boolean result = FileUtil.createMissingParentDirectories(file); + if (!result) { + addError("Failed to create parent directories for [" + file.getAbsolutePath() + "]"); + } - public void setAppend(boolean append) { - this.append = append; - } + ResilientFileOutputStream resilientFos = new ResilientFileOutputStream(file, append); + resilientFos.setContext(context); + setOutputStream(resilientFos); + } finally { + lock.unlock(); + } + } - private void safeWrite(E event) throws IOException { - ResilientFileOutputStream resilientFOS = (ResilientFileOutputStream) getOutputStream(); - FileChannel fileChannel = resilientFOS.getChannel(); - if (fileChannel == null) { - return; + /** + * @see #setPrudent(boolean) + * + * @return true if in prudent mode + */ + public boolean isPrudent() { + return prudent; } - // Clear any current interrupt (see LOGBACK-875) - boolean interrupted = Thread.interrupted(); + /** + * When prudent is set to true, file appenders from multiple JVMs can safely + * write to the same file. + * + * @param prudent + */ + public void setPrudent(boolean prudent) { + this.prudent = prudent; + } - FileLock fileLock = null; - try { - fileLock = fileChannel.lock(); - long position = fileChannel.position(); - long size = fileChannel.size(); - if (size != position) { - fileChannel.position(size); - } - super.writeOut(event); - } catch (IOException e) { - // Mainly to catch FileLockInterruptionExceptions (see LOGBACK-875) - resilientFOS.postIOFailure(e); + public void setAppend(boolean append) { + this.append = append; } - finally { - if (fileLock != null && fileLock.isValid()) { - fileLock.release(); - } - // Re-interrupt if we started in an interrupted state (see LOGBACK-875) - if (interrupted) { - Thread.currentThread().interrupt(); - } + private void safeWrite(E event) throws IOException { + ResilientFileOutputStream resilientFOS = (ResilientFileOutputStream) getOutputStream(); + FileChannel fileChannel = resilientFOS.getChannel(); + if (fileChannel == null) { + return; + } + + // Clear any current interrupt (see LOGBACK-875) + boolean interrupted = Thread.interrupted(); + + FileLock fileLock = null; + try { + fileLock = fileChannel.lock(); + long position = fileChannel.position(); + long size = fileChannel.size(); + if (size != position) { + fileChannel.position(size); + } + super.writeOut(event); + } catch (IOException e) { + // Mainly to catch FileLockInterruptionExceptions (see LOGBACK-875) + resilientFOS.postIOFailure(e); + } finally { + if (fileLock != null && fileLock.isValid()) { + fileLock.release(); + } + + // Re-interrupt if we started in an interrupted state (see LOGBACK-875) + if (interrupted) { + Thread.currentThread().interrupt(); + } + } } - } - @Override - protected void writeOut(E event) throws IOException { - if (prudent) { - safeWrite(event); - } else { - super.writeOut(event); + @Override + protected void writeOut(E event) throws IOException { + if (prudent) { + safeWrite(event); + } else { + super.writeOut(event); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/Layout.java b/logback-core/src/main/java/ch/qos/logback/core/Layout.java index 476fab54752302b5a47b7014f37246e436cefc26..20be04048f0f48207c63b002ddf0a0e3059c0009 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/Layout.java +++ b/logback-core/src/main/java/ch/qos/logback/core/Layout.java @@ -17,54 +17,54 @@ import ch.qos.logback.core.spi.ContextAware; import ch.qos.logback.core.spi.LifeCycle; public interface Layout extends ContextAware, LifeCycle { - - /** - * Transform an event (of type Object) and return it as a String after - * appropriate formatting. - * - *

Taking in an object and returning a String is the least sophisticated - * way of formatting events. However, it is remarkably CPU-effective. - *

- * - * @param event The event to format - * @return the event formatted as a String - */ - String doLayout(E event); - - /** - * Return the file header for this layout. The returned value may be null. - * @return The header. - */ - String getFileHeader(); - /** - * Return the header of the logging event formatting. The returned value - * may be null. - * - * @return The header. - */ - String getPresentationHeader(); + /** + * Transform an event (of type Object) and return it as a String after + * appropriate formatting. + * + *

Taking in an object and returning a String is the least sophisticated + * way of formatting events. However, it is remarkably CPU-effective. + *

+ * + * @param event The event to format + * @return the event formatted as a String + */ + String doLayout(E event); + + /** + * Return the file header for this layout. The returned value may be null. + * @return The header. + */ + String getFileHeader(); + + /** + * Return the header of the logging event formatting. The returned value + * may be null. + * + * @return The header. + */ + String getPresentationHeader(); + + /** + * Return the footer of the logging event formatting. The returned value + * may be null. + * + * @return The footer. + */ + + String getPresentationFooter(); + + /** + * Return the file footer for this layout. The returned value may be null. + * @return The footer. + */ + String getFileFooter(); + + /** + * Returns the content type as appropriate for the implementation. + * + * @return + */ + String getContentType(); - /** - * Return the footer of the logging event formatting. The returned value - * may be null. - * - * @return The footer. - */ - - String getPresentationFooter(); - - /** - * Return the file footer for this layout. The returned value may be null. - * @return The footer. - */ - String getFileFooter(); - - /** - * Returns the content type as appropriate for the implementation. - * - * @return - */ - String getContentType(); - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/LayoutBase.java b/logback-core/src/main/java/ch/qos/logback/core/LayoutBase.java index bfc95e4c355d30ceb84976fcbce4d55bdde83816..2a344b9f62b75efba1c8b7ddc040be6b0a1662b4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/LayoutBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/LayoutBase.java @@ -15,68 +15,68 @@ package ch.qos.logback.core; import ch.qos.logback.core.spi.ContextAwareBase; -abstract public class LayoutBase extends ContextAwareBase implements Layout { - - protected boolean started; - - String fileHeader; - String fileFooter; - String presentationHeader; - String presentationFooter; - - public void setContext(Context context) { - this.context = context; - } - - public Context getContext() { - return this.context; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - } - - public boolean isStarted() { - return started; - } - - public String getFileHeader() { - return fileHeader; - } - - public String getPresentationHeader() { - return presentationHeader; - } - - public String getPresentationFooter() { - return presentationFooter; - } - - public String getFileFooter() { - return fileFooter; - } - - public String getContentType() { - return "text/plain"; - } - - public void setFileHeader(String header) { - this.fileHeader = header; - } - - public void setFileFooter(String footer) { - this.fileFooter = footer; - } - - public void setPresentationHeader(String header) { - this.presentationHeader = header; - } - - public void setPresentationFooter(String footer) { - this.presentationFooter = footer; - } +abstract public class LayoutBase extends ContextAwareBase implements Layout { + + protected boolean started; + + String fileHeader; + String fileFooter; + String presentationHeader; + String presentationFooter; + + public void setContext(Context context) { + this.context = context; + } + + public Context getContext() { + return this.context; + } + + public void start() { + started = true; + } + + public void stop() { + started = false; + } + + public boolean isStarted() { + return started; + } + + public String getFileHeader() { + return fileHeader; + } + + public String getPresentationHeader() { + return presentationHeader; + } + + public String getPresentationFooter() { + return presentationFooter; + } + + public String getFileFooter() { + return fileFooter; + } + + public String getContentType() { + return "text/plain"; + } + + public void setFileHeader(String header) { + this.fileHeader = header; + } + + public void setFileFooter(String footer) { + this.fileFooter = footer; + } + + public void setPresentationHeader(String header) { + this.presentationHeader = header; + } + + public void setPresentationFooter(String footer) { + this.presentationFooter = footer; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/LifeCycleManager.java b/logback-core/src/main/java/ch/qos/logback/core/LifeCycleManager.java index 33c3c4255ad2b3cfd8f46ce63a7bd51b600a160d..340103a0098677b3616a1de91e4e5766702d06d5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/LifeCycleManager.java +++ b/logback-core/src/main/java/ch/qos/logback/core/LifeCycleManager.java @@ -27,29 +27,29 @@ import ch.qos.logback.core.spi.LifeCycle; */ public class LifeCycleManager { - private final Set components = new HashSet(); - - /** - * Registers a component with this manager. - *

- * @param component the component whose life cycle is to be managed - */ - public void register(LifeCycle component) { - components.add(component); - } - - /** - * Resets this manager. - *

- * All registered components are stopped and removed from the manager. - */ - public void reset() { - for (LifeCycle component : components) { - if (component.isStarted()) { - component.stop(); - } + private final Set components = new HashSet(); + + /** + * Registers a component with this manager. + *

+ * @param component the component whose life cycle is to be managed + */ + public void register(LifeCycle component) { + components.add(component); + } + + /** + * Resets this manager. + *

+ * All registered components are stopped and removed from the manager. + */ + public void reset() { + for (LifeCycle component : components) { + if (component.isStarted()) { + component.stop(); + } + } + components.clear(); } - components.clear(); - } - + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/LogbackException.java b/logback-core/src/main/java/ch/qos/logback/core/LogbackException.java index be84515c50c3d050ef013eebe56ecd1ee632ea93..97ba937c7ed08d79d02447006289db53e7f650eb 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/LogbackException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/LogbackException.java @@ -15,15 +15,14 @@ package ch.qos.logback.core; public class LogbackException extends RuntimeException { - private static final long serialVersionUID = -799956346239073266L; + private static final long serialVersionUID = -799956346239073266L; + + public LogbackException(String msg) { + super(msg); + } + + public LogbackException(String msg, Throwable nested) { + super(msg, nested); + } - public LogbackException(String msg) { - super(msg); - } - - - public LogbackException(String msg, Throwable nested) { - super(msg, nested); - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/OutputStreamAppender.java b/logback-core/src/main/java/ch/qos/logback/core/OutputStreamAppender.java index 5f886092568749bd10d11c41ac42c8d8dab77150..0fb695c1dbadd997ab2560719f9ec8196268d84d 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/OutputStreamAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/OutputStreamAppender.java @@ -35,205 +35,198 @@ import ch.qos.logback.core.status.ErrorStatus; */ public class OutputStreamAppender extends UnsynchronizedAppenderBase { - - /** - * It is the encoder which is ultimately responsible for writing the event to - * an {@link OutputStream}. - */ - protected Encoder encoder; - - /** - * All synchronization in this class is done via the lock object. - */ - protected final ReentrantLock lock = new ReentrantLock(true); - - /** - * This is the {@link OutputStream outputStream} where output will be written. - */ - private OutputStream outputStream; - - /** - * The underlying output stream used by this appender. - * - * @return - */ - public OutputStream getOutputStream() { - return outputStream; - } - - /** - * Checks that requires parameters are set and if everything is in order, - * activates this appender. - */ - public void start() { - int errors = 0; - if (this.encoder == null) { - addStatus(new ErrorStatus("No encoder set for the appender named \"" - + name + "\".", this)); - errors++; + /** + * It is the encoder which is ultimately responsible for writing the event to + * an {@link OutputStream}. + */ + protected Encoder encoder; + + /** + * All synchronization in this class is done via the lock object. + */ + protected final ReentrantLock lock = new ReentrantLock(true); + + /** + * This is the {@link OutputStream outputStream} where output will be written. + */ + private OutputStream outputStream; + + /** + * The underlying output stream used by this appender. + * + * @return + */ + public OutputStream getOutputStream() { + return outputStream; } - if (this.outputStream == null) { - addStatus(new ErrorStatus( - "No output stream set for the appender named \"" + name + "\".", this)); - errors++; + /** + * Checks that requires parameters are set and if everything is in order, + * activates this appender. + */ + public void start() { + int errors = 0; + if (this.encoder == null) { + addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this)); + errors++; + } + + if (this.outputStream == null) { + addStatus(new ErrorStatus("No output stream set for the appender named \"" + name + "\".", this)); + errors++; + } + // only error free appenders should be activated + if (errors == 0) { + super.start(); + } } - // only error free appenders should be activated - if (errors == 0) { - super.start(); + + public void setLayout(Layout layout) { + addWarn("This appender no longer admits a layout as a sub-component, set an encoder instead."); + addWarn("To ensure compatibility, wrapping your layout in LayoutWrappingEncoder."); + addWarn("See also " + CODES_URL + "#layoutInsteadOfEncoder for details"); + LayoutWrappingEncoder lwe = new LayoutWrappingEncoder(); + lwe.setLayout(layout); + lwe.setContext(context); + this.encoder = lwe; + } + + @Override + protected void append(E eventObject) { + if (!isStarted()) { + return; + } + + subAppend(eventObject); } - } - - public void setLayout(Layout layout) { - addWarn("This appender no longer admits a layout as a sub-component, set an encoder instead."); - addWarn("To ensure compatibility, wrapping your layout in LayoutWrappingEncoder."); - addWarn("See also "+CODES_URL+"#layoutInsteadOfEncoder for details"); - LayoutWrappingEncoder lwe = new LayoutWrappingEncoder(); - lwe.setLayout(layout); - lwe.setContext(context); - this.encoder = lwe; - } - - @Override - protected void append(E eventObject) { - if (!isStarted()) { - return; + + /** + * Stop this appender instance. The underlying stream or writer is also + * closed. + * + *

+ * Stopped appenders cannot be reused. + */ + public void stop() { + lock.lock(); + try { + closeOutputStream(); + super.stop(); + } finally { + lock.unlock(); + } } - subAppend(eventObject); - } - - /** - * Stop this appender instance. The underlying stream or writer is also - * closed. - * - *

- * Stopped appenders cannot be reused. - */ - public void stop() { - lock.lock(); - try { - closeOutputStream(); - super.stop(); - } finally { - lock.unlock(); + /** + * Close the underlying {@link OutputStream}. + */ + protected void closeOutputStream() { + if (this.outputStream != null) { + try { + // before closing we have to output out layout's footer + encoderClose(); + this.outputStream.close(); + this.outputStream = null; + } catch (IOException e) { + addStatus(new ErrorStatus("Could not close output stream for OutputStreamAppender.", this, e)); + } + } } - } - - /** - * Close the underlying {@link OutputStream}. - */ - protected void closeOutputStream() { - if (this.outputStream != null) { - try { - // before closing we have to output out layout's footer - encoderClose(); - this.outputStream.close(); - this.outputStream = null; - } catch (IOException e) { - addStatus(new ErrorStatus( - "Could not close output stream for OutputStreamAppender.", this, e)); - } + + void encoderInit() { + if (encoder != null && this.outputStream != null) { + try { + encoder.init(outputStream); + } catch (IOException ioe) { + this.started = false; + addStatus(new ErrorStatus("Failed to initialize encoder for appender named [" + name + "].", this, ioe)); + } + } } - } - - void encoderInit() { - if (encoder != null && this.outputStream != null) { - try { - encoder.init(outputStream); - } catch (IOException ioe) { - this.started = false; - addStatus(new ErrorStatus( - "Failed to initialize encoder for appender named [" + name + "].", - this, ioe)); - } + + void encoderClose() { + if (encoder != null && this.outputStream != null) { + try { + encoder.close(); + } catch (IOException ioe) { + this.started = false; + addStatus(new ErrorStatus("Failed to write footer for appender named [" + name + "].", this, ioe)); + } + } } - } - - void encoderClose() { - if (encoder != null && this.outputStream != null) { - try { - encoder.close(); - } catch (IOException ioe) { - this.started = false; - addStatus(new ErrorStatus("Failed to write footer for appender named [" - + name + "].", this, ioe)); - } + + /** + *

+ * Sets the @link OutputStream} where the log output will go. The specified + * OutputStream must be opened by the user and be writable. The + * OutputStream will be closed when the appender instance is + * closed. + * + * @param outputStream + * An already opened OutputStream. + */ + public void setOutputStream(OutputStream outputStream) { + lock.lock(); + try { + // close any previously opened output stream + closeOutputStream(); + + this.outputStream = outputStream; + if (encoder == null) { + addWarn("Encoder has not been set. Cannot invoke its init method."); + return; + } + + encoderInit(); + } finally { + lock.unlock(); + } } - } - - /** - *

- * Sets the @link OutputStream} where the log output will go. The specified - * OutputStream must be opened by the user and be writable. The - * OutputStream will be closed when the appender instance is - * closed. - * - * @param outputStream - * An already opened OutputStream. - */ - public void setOutputStream(OutputStream outputStream) { - lock.lock(); - try { - // close any previously opened output stream - closeOutputStream(); - - this.outputStream = outputStream; - if (encoder == null) { - addWarn("Encoder has not been set. Cannot invoke its init method."); - return; - } - - encoderInit(); - } finally { - lock.unlock(); + + protected void writeOut(E event) throws IOException { + this.encoder.doEncode(event); } - } - - protected void writeOut(E event) throws IOException { - this.encoder.doEncode(event); - } - - /** - * Actual writing occurs here. - *

- * Most subclasses of WriterAppender will need to override this - * method. - * - * @since 0.9.0 - */ - protected void subAppend(E event) { - if (!isStarted()) { - return; + + /** + * Actual writing occurs here. + *

+ * Most subclasses of WriterAppender will need to override this + * method. + * + * @since 0.9.0 + */ + protected void subAppend(E event) { + if (!isStarted()) { + return; + } + try { + // this step avoids LBCLASSIC-139 + if (event instanceof DeferredProcessingAware) { + ((DeferredProcessingAware) event).prepareForDeferredProcessing(); + } + // the synchronization prevents the OutputStream from being closed while we + // are writing. It also prevents multiple threads from entering the same + // converter. Converters assume that they are in a synchronized block. + lock.lock(); + try { + writeOut(event); + } finally { + lock.unlock(); + } + } catch (IOException ioe) { + // as soon as an exception occurs, move to non-started state + // and add a single ErrorStatus to the SM. + this.started = false; + addStatus(new ErrorStatus("IO failure in appender", this, ioe)); + } } - try { - // this step avoids LBCLASSIC-139 - if (event instanceof DeferredProcessingAware) { - ((DeferredProcessingAware) event).prepareForDeferredProcessing(); - } - // the synchronization prevents the OutputStream from being closed while we - // are writing. It also prevents multiple threads from entering the same - // converter. Converters assume that they are in a synchronized block. - lock.lock(); - try { - writeOut(event); - } finally { - lock.unlock(); - } - } catch (IOException ioe) { - // as soon as an exception occurs, move to non-started state - // and add a single ErrorStatus to the SM. - this.started = false; - addStatus(new ErrorStatus("IO failure in appender", this, ioe)); + + public Encoder getEncoder() { + return encoder; } - } - public Encoder getEncoder() { - return encoder; - } + public void setEncoder(Encoder encoder) { + this.encoder = encoder; + } - public void setEncoder(Encoder encoder) { - this.encoder = encoder; - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/PropertyDefinerBase.java b/logback-core/src/main/java/ch/qos/logback/core/PropertyDefinerBase.java index 5f42dd4e55597353b9a2055f2358d5f037442476..50bed62086c6f9ed9031d9162b2e7aff7b841a53 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/PropertyDefinerBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/PropertyDefinerBase.java @@ -23,8 +23,8 @@ import ch.qos.logback.core.spi.PropertyDefiner; */ public abstract class PropertyDefinerBase extends ContextAwareBase implements PropertyDefiner { - static protected String booleanAsStr(boolean bool) { - return bool ? Boolean.TRUE.toString() : Boolean.FALSE.toString(); - } + static protected String booleanAsStr(boolean bool) { + return bool ? Boolean.TRUE.toString() : Boolean.FALSE.toString(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/UnsynchronizedAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/UnsynchronizedAppenderBase.java index 869ef33b4546837200a7944d51d6674d511a9e76..0b5d28b91f8149d841db05cef2470ac037adf706 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/UnsynchronizedAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/UnsynchronizedAppenderBase.java @@ -28,112 +28,108 @@ import ch.qos.logback.core.status.WarnStatus; * @author Ceki Gülcü * @author Ralph Goers */ -abstract public class UnsynchronizedAppenderBase extends ContextAwareBase implements - Appender { +abstract public class UnsynchronizedAppenderBase extends ContextAwareBase implements Appender { - protected boolean started = false; + protected boolean started = false; - // using a ThreadLocal instead of a boolean add 75 nanoseconds per - // doAppend invocation. This is tolerable as doAppend takes at least a few microseconds - // on a real appender - /** - * The guard prevents an appender from repeatedly calling its own doAppend - * method. - */ - private ThreadLocal guard = new ThreadLocal(); + // using a ThreadLocal instead of a boolean add 75 nanoseconds per + // doAppend invocation. This is tolerable as doAppend takes at least a few microseconds + // on a real appender + /** + * The guard prevents an appender from repeatedly calling its own doAppend + * method. + */ + private ThreadLocal guard = new ThreadLocal(); + /** + * Appenders are named. + */ + protected String name; - /** - * Appenders are named. - */ - protected String name; + private FilterAttachableImpl fai = new FilterAttachableImpl(); - private FilterAttachableImpl fai = new FilterAttachableImpl(); - - public String getName() { - return name; - } + public String getName() { + return name; + } - private int statusRepeatCount = 0; - private int exceptionCount = 0; + private int statusRepeatCount = 0; + private int exceptionCount = 0; - static final int ALLOWED_REPEATS = 3; + static final int ALLOWED_REPEATS = 3; - public void doAppend(E eventObject) { - // WARNING: The guard check MUST be the first statement in the - // doAppend() method. - - // prevent re-entry. - if (Boolean.TRUE.equals(guard.get())) { - return; - } + public void doAppend(E eventObject) { + // WARNING: The guard check MUST be the first statement in the + // doAppend() method. - try { - guard.set(Boolean.TRUE); + // prevent re-entry. + if (Boolean.TRUE.equals(guard.get())) { + return; + } - if (!this.started) { - if (statusRepeatCount++ < ALLOWED_REPEATS) { - addStatus(new WarnStatus( - "Attempted to append to non started appender [" + name + "].", - this)); + try { + guard.set(Boolean.TRUE); + + if (!this.started) { + if (statusRepeatCount++ < ALLOWED_REPEATS) { + addStatus(new WarnStatus("Attempted to append to non started appender [" + name + "].", this)); + } + return; + } + + if (getFilterChainDecision(eventObject) == FilterReply.DENY) { + return; + } + + // ok, we now invoke derived class' implementation of append + this.append(eventObject); + + } catch (Exception e) { + if (exceptionCount++ < ALLOWED_REPEATS) { + addError("Appender [" + name + "] failed to append.", e); + } + } finally { + guard.set(Boolean.FALSE); } - return; - } - - if (getFilterChainDecision(eventObject) == FilterReply.DENY) { - return; - } - - // ok, we now invoke derived class' implementation of append - this.append(eventObject); - - } catch (Exception e) { - if (exceptionCount++ < ALLOWED_REPEATS) { - addError("Appender [" + name + "] failed to append.", e); - } - } finally { - guard.set(Boolean.FALSE); } - } - abstract protected void append(E eventObject); + abstract protected void append(E eventObject); - /** - * Set the name of this appender. - */ - public void setName(String name) { - this.name = name; - } + /** + * Set the name of this appender. + */ + public void setName(String name) { + this.name = name; + } - public void start() { - started = true; - } + public void start() { + started = true; + } - public void stop() { - started = false; - } + public void stop() { + started = false; + } - public boolean isStarted() { - return started; - } + public boolean isStarted() { + return started; + } - public String toString() { - return this.getClass().getName() + "[" + name + "]"; - } + public String toString() { + return this.getClass().getName() + "[" + name + "]"; + } - public void addFilter(Filter newFilter) { - fai.addFilter(newFilter); - } + public void addFilter(Filter newFilter) { + fai.addFilter(newFilter); + } - public void clearAllFilters() { - fai.clearAllFilters(); - } + public void clearAllFilters() { + fai.clearAllFilters(); + } - public List> getCopyOfAttachedFiltersList() { - return fai.getCopyOfAttachedFiltersList(); - } + public List> getCopyOfAttachedFiltersList() { + return fai.getCopyOfAttachedFiltersList(); + } - public FilterReply getFilterChainDecision(E event) { - return fai.getFilterChainDecision(event); - } + public FilterReply getFilterChainDecision(E event) { + return fai.getFilterChainDecision(event); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/boolex/EvaluationException.java b/logback-core/src/main/java/ch/qos/logback/core/boolex/EvaluationException.java index 4434d51efa6e0d95d80ef01f7db2f226c4b27548..f142b89cba3fd86ae839bd5cc197474b3d41c196 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/boolex/EvaluationException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/boolex/EvaluationException.java @@ -20,18 +20,18 @@ package ch.qos.logback.core.boolex; */ public class EvaluationException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public EvaluationException(String msg) { - super(msg); - } + public EvaluationException(String msg) { + super(msg); + } - public EvaluationException(String msg, Throwable cause) { - super(msg, cause); - } + public EvaluationException(String msg, Throwable cause) { + super(msg, cause); + } - public EvaluationException(Throwable cause) { - super(cause); - } + public EvaluationException(Throwable cause) { + super(cause); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluator.java b/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluator.java index ed7cf1f0b04c55ca78ab3a11ed47e5957b6587cf..6d92f1a0eda25af96ad3670c20f46009484f03e6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluator.java @@ -28,33 +28,33 @@ import ch.qos.logback.core.spi.LifeCycle; public interface EventEvaluator extends ContextAware, LifeCycle { - /** - * Evaluates whether the event passed as parameter matches some user-specified - * criteria. - * - *

- * The Evaluator is free to evaluate the event as it pleases. In - * particular, the evaluation results may depend on previous events. - * - * @param event - * The event to evaluate - * @return true if there is a match, false otherwise. - * @throws NullPointerException - * can be thrown in presence of null values - * @throws EvaluationException - * may be thrown during faulty evaluation - */ - boolean evaluate(E event) throws NullPointerException, EvaluationException; + /** + * Evaluates whether the event passed as parameter matches some user-specified + * criteria. + * + *

+ * The Evaluator is free to evaluate the event as it pleases. In + * particular, the evaluation results may depend on previous events. + * + * @param event + * The event to evaluate + * @return true if there is a match, false otherwise. + * @throws NullPointerException + * can be thrown in presence of null values + * @throws EvaluationException + * may be thrown during faulty evaluation + */ + boolean evaluate(E event) throws NullPointerException, EvaluationException; - /** - * Evaluators are named entities. - * - * @return The name of this evaluator. - */ - String getName(); + /** + * Evaluators are named entities. + * + * @return The name of this evaluator. + */ + String getName(); - /** - * Evaluators are named entities. - */ - void setName(String name); + /** + * Evaluators are named entities. + */ + void setName(String name); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluatorBase.java b/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluatorBase.java index 70c0673022ec387d232058212b635d43cc0740a4..7c7a0dcc01f8a57b6f52dd9bfffd74df56768676 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluatorBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/boolex/EventEvaluatorBase.java @@ -15,33 +15,32 @@ package ch.qos.logback.core.boolex; import ch.qos.logback.core.spi.ContextAwareBase; -abstract public class EventEvaluatorBase extends ContextAwareBase implements - EventEvaluator { +abstract public class EventEvaluatorBase extends ContextAwareBase implements EventEvaluator { - String name; - boolean started; + String name; + boolean started; - public String getName() { - return name; - } + public String getName() { + return name; + } + + public void setName(String name) { + if (this.name != null) { + throw new IllegalStateException("name has been already set"); + } + this.name = name; + } + + public boolean isStarted() { + return started; + } + + public void start() { + started = true; + } - public void setName(String name) { - if (this.name != null) { - throw new IllegalStateException("name has been already set"); + public void stop() { + started = false; } - this.name = name; - } - - public boolean isStarted() { - return started; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/boolex/JaninoEventEvaluatorBase.java b/logback-core/src/main/java/ch/qos/logback/core/boolex/JaninoEventEvaluatorBase.java index f3cb20e5d18c9a5f68c674f95d2bcba573555458..8d8964b43e11a0c348b4ab34cb71448b4044316c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/boolex/JaninoEventEvaluatorBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/boolex/JaninoEventEvaluatorBase.java @@ -27,73 +27,69 @@ import org.codehaus.janino.ScriptEvaluator; */ abstract public class JaninoEventEvaluatorBase extends EventEvaluatorBase { - static Class EXPRESSION_TYPE = boolean.class; - static Class[] THROWN_EXCEPTIONS = new Class[1]; + static Class EXPRESSION_TYPE = boolean.class; + static Class[] THROWN_EXCEPTIONS = new Class[1]; - static public final int ERROR_THRESHOLD = 4; - static { - THROWN_EXCEPTIONS[0] = EvaluationException.class; - } + static public final int ERROR_THRESHOLD = 4; + static { + THROWN_EXCEPTIONS[0] = EvaluationException.class; + } - private String expression; + private String expression; - ScriptEvaluator scriptEvaluator; - private int errorCount = 0; + ScriptEvaluator scriptEvaluator; + private int errorCount = 0; - abstract protected String getDecoratedExpression(); + abstract protected String getDecoratedExpression(); - abstract protected String[] getParameterNames(); + abstract protected String[] getParameterNames(); - abstract protected Class[] getParameterTypes(); + abstract protected Class[] getParameterTypes(); - abstract protected Object[] getParameterValues(E event); + abstract protected Object[] getParameterValues(E event); - protected List matcherList = new ArrayList(); + protected List matcherList = new ArrayList(); - @Override - public void start() { - try { - assert context != null; - scriptEvaluator = new ScriptEvaluator(getDecoratedExpression(), EXPRESSION_TYPE, - getParameterNames(), getParameterTypes(), THROWN_EXCEPTIONS); - super.start(); - } catch (Exception e) { - addError( - "Could not start evaluator with expression [" + expression + "]", e); + @Override + public void start() { + try { + assert context != null; + scriptEvaluator = new ScriptEvaluator(getDecoratedExpression(), EXPRESSION_TYPE, getParameterNames(), getParameterTypes(), THROWN_EXCEPTIONS); + super.start(); + } catch (Exception e) { + addError("Could not start evaluator with expression [" + expression + "]", e); + } } - } - public boolean evaluate(E event) throws EvaluationException { - if (!isStarted()) { - throw new IllegalStateException("Evaluator [" + name - + "] was called in stopped state"); - } - try { - Boolean result = (Boolean) scriptEvaluator.evaluate(getParameterValues(event)); - return result.booleanValue(); - } catch (Exception ex) { - errorCount++; - if (errorCount >= ERROR_THRESHOLD) { - stop(); - } - throw new EvaluationException("Evaluator [" + name - + "] caused an exception", ex); + public boolean evaluate(E event) throws EvaluationException { + if (!isStarted()) { + throw new IllegalStateException("Evaluator [" + name + "] was called in stopped state"); + } + try { + Boolean result = (Boolean) scriptEvaluator.evaluate(getParameterValues(event)); + return result.booleanValue(); + } catch (Exception ex) { + errorCount++; + if (errorCount >= ERROR_THRESHOLD) { + stop(); + } + throw new EvaluationException("Evaluator [" + name + "] caused an exception", ex); + } } - } - public String getExpression() { - return expression; - } + public String getExpression() { + return expression; + } - public void setExpression(String expression) { - this.expression = expression; - } + public void setExpression(String expression) { + this.expression = expression; + } - public void addMatcher(Matcher matcher) { - matcherList.add(matcher); - } + public void addMatcher(Matcher matcher) { + matcherList.add(matcher); + } - public List getMatcherList() { - return matcherList; - } + public List getMatcherList() { + return matcherList; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/boolex/Matcher.java b/logback-core/src/main/java/ch/qos/logback/core/boolex/Matcher.java index efaadaf827de25dc508d68569593eeb766881fe2..9510617d535a42c00c0916a899d78f515854be7f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/boolex/Matcher.java +++ b/logback-core/src/main/java/ch/qos/logback/core/boolex/Matcher.java @@ -21,105 +21,105 @@ import ch.qos.logback.core.spi.LifeCycle; public class Matcher extends ContextAwareBase implements LifeCycle { - private String regex; - private String name; - private boolean caseSensitive = true; - private boolean canonEq = false; - private boolean unicodeCase = false; - - private boolean start = false; - private Pattern pattern; - - public String getRegex() { - return regex; - } - - public void setRegex(String regex) { - this.regex = regex; - } - - public void start() { - if(name == null) { - addError("All Matcher objects must be named"); - return; + private String regex; + private String name; + private boolean caseSensitive = true; + private boolean canonEq = false; + private boolean unicodeCase = false; + + private boolean start = false; + private Pattern pattern; + + public String getRegex() { + return regex; } - try { - int code = 0; - if(!caseSensitive) { - code |= Pattern.CASE_INSENSITIVE; - } - if(canonEq) { - code |= Pattern.CANON_EQ; - } - if(unicodeCase) { - code |= Pattern.UNICODE_CASE; - } - - //code |= Pattern.DOTALL; - - pattern = Pattern.compile(regex, code); - start = true; - } catch (PatternSyntaxException pse) { - addError("Failed to compile regex [" + regex + "]", pse); + + public void setRegex(String regex) { + this.regex = regex; + } + + public void start() { + if (name == null) { + addError("All Matcher objects must be named"); + return; + } + try { + int code = 0; + if (!caseSensitive) { + code |= Pattern.CASE_INSENSITIVE; + } + if (canonEq) { + code |= Pattern.CANON_EQ; + } + if (unicodeCase) { + code |= Pattern.UNICODE_CASE; + } + + // code |= Pattern.DOTALL; + + pattern = Pattern.compile(regex, code); + start = true; + } catch (PatternSyntaxException pse) { + addError("Failed to compile regex [" + regex + "]", pse); + } + } + + public void stop() { + start = false; + } + + public boolean isStarted() { + return start; } - } - - public void stop() { - start = false; - } - - public boolean isStarted() { - return start; - } - - //However, this method does - //not require that the entire region (of the input) be matched. - - /** - * Checks whether the input matches the regular expression. - * - * @param input - * @return - * @throws EvaluationException - */ - public boolean matches(String input) throws EvaluationException { - if(start) { - java.util.regex.Matcher matcher = pattern.matcher(input); - return matcher.find(); - } else { - throw new EvaluationException("Matcher ["+regex+"] not started"); + + // However, this method does + // not require that the entire region (of the input) be matched. + + /** + * Checks whether the input matches the regular expression. + * + * @param input + * @return + * @throws EvaluationException + */ + public boolean matches(String input) throws EvaluationException { + if (start) { + java.util.regex.Matcher matcher = pattern.matcher(input); + return matcher.find(); + } else { + throw new EvaluationException("Matcher [" + regex + "] not started"); + } } - } - public boolean isCanonEq() { - return canonEq; - } + public boolean isCanonEq() { + return canonEq; + } - public void setCanonEq(boolean canonEq) { - this.canonEq = canonEq; - } + public void setCanonEq(boolean canonEq) { + this.canonEq = canonEq; + } - public boolean isCaseSensitive() { - return caseSensitive; - } + public boolean isCaseSensitive() { + return caseSensitive; + } - public void setCaseSensitive(boolean caseSensitive) { - this.caseSensitive = caseSensitive; - } + public void setCaseSensitive(boolean caseSensitive) { + this.caseSensitive = caseSensitive; + } - public boolean isUnicodeCase() { - return unicodeCase; - } + public boolean isUnicodeCase() { + return unicodeCase; + } - public void setUnicodeCase(boolean unicodeCase) { - this.unicodeCase = unicodeCase; - } + public void setUnicodeCase(boolean unicodeCase) { + this.unicodeCase = unicodeCase; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/BindDataSourceToJNDIAction.java b/logback-core/src/main/java/ch/qos/logback/core/db/BindDataSourceToJNDIAction.java index 5db8b9683d24683f0d86f509ca5a065653cca33d..2a50a1ec573bffb2b26cad6a66fd9335bf37c681 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/BindDataSourceToJNDIAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/BindDataSourceToJNDIAction.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.db; - import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; @@ -31,59 +30,56 @@ import ch.qos.logback.core.util.OptionHelper; * */ public class BindDataSourceToJNDIAction extends Action { - - static final String DATA_SOURCE_CLASS = "dataSourceClass"; - static final String URL = "url"; - static final String USER = "user"; - static final String PASSWORD = "password"; - - /** - * Instantiates an a data source and bind it to JNDI - * Most of the required parameters are placed in the ec.substitutionProperties - */ - public void begin( - InterpretationContext ec, String localName, Attributes attributes) { - String dsClassName = ec.getProperty(DATA_SOURCE_CLASS); - - if (OptionHelper.isEmpty(dsClassName)) { - addWarn("dsClassName is a required parameter"); - ec.addError("dsClassName is a required parameter"); - - return; - } - - String urlStr = ec.getProperty(URL); - String userStr = ec.getProperty(USER); - String passwordStr = ec.getProperty(PASSWORD); - - try { - DataSource ds = - (DataSource) OptionHelper.instantiateByClassName(dsClassName, DataSource.class, context); - - PropertySetter setter = new PropertySetter(ds); - setter.setContext(context); - if (!OptionHelper.isEmpty(urlStr)) { - setter.setProperty("url", urlStr); - } - - if (!OptionHelper.isEmpty(userStr)) { - setter.setProperty("user", userStr); - } - - if (!OptionHelper.isEmpty(passwordStr)) { - setter.setProperty("password", passwordStr); - } - - Context ctx = new InitialContext(); - ctx.rebind("dataSource", ds); - } catch (Exception oops) { - addError( - "Could not bind datasource. Reported error follows.", oops); - ec.addError("Could not not bind datasource of type [" + dsClassName + "]."); + static final String DATA_SOURCE_CLASS = "dataSourceClass"; + static final String URL = "url"; + static final String USER = "user"; + static final String PASSWORD = "password"; + + /** + * Instantiates an a data source and bind it to JNDI + * Most of the required parameters are placed in the ec.substitutionProperties + */ + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + String dsClassName = ec.getProperty(DATA_SOURCE_CLASS); + + if (OptionHelper.isEmpty(dsClassName)) { + addWarn("dsClassName is a required parameter"); + ec.addError("dsClassName is a required parameter"); + + return; + } + + String urlStr = ec.getProperty(URL); + String userStr = ec.getProperty(USER); + String passwordStr = ec.getProperty(PASSWORD); + + try { + DataSource ds = (DataSource) OptionHelper.instantiateByClassName(dsClassName, DataSource.class, context); + + PropertySetter setter = new PropertySetter(ds); + setter.setContext(context); + + if (!OptionHelper.isEmpty(urlStr)) { + setter.setProperty("url", urlStr); + } + + if (!OptionHelper.isEmpty(userStr)) { + setter.setProperty("user", userStr); + } + + if (!OptionHelper.isEmpty(passwordStr)) { + setter.setProperty("password", passwordStr); + } + + Context ctx = new InitialContext(); + ctx.rebind("dataSource", ds); + } catch (Exception oops) { + addError("Could not bind datasource. Reported error follows.", oops); + ec.addError("Could not not bind datasource of type [" + dsClassName + "]."); + } } - } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSource.java b/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSource.java index 3818be155baba3a841138607d87f90536add2574..0d81891cb976f5b75a09398e4bdc28089be0a6d6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSource.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSource.java @@ -12,13 +12,13 @@ * as published by the Free Software Foundation. */ package ch.qos.logback.core.db; + import java.sql.Connection; import java.sql.SQLException; import ch.qos.logback.core.db.dialect.SQLDialectCode; import ch.qos.logback.core.spi.LifeCycle; - /** * The ConnectionSource interface provides a pluggable means of * transparently obtaining JDBC {@link java.sql.Connection}s for logback classes @@ -31,31 +31,31 @@ import ch.qos.logback.core.spi.LifeCycle; */ public interface ConnectionSource extends LifeCycle { - /** - * Obtain a {@link java.sql.Connection} for use. The client is - * responsible for closing the {@link java.sql.Connection} when it is no - * longer required. - * - * @throws SQLException if a {@link java.sql.Connection} could not be - * obtained - */ - Connection getConnection() throws SQLException; + /** + * Obtain a {@link java.sql.Connection} for use. The client is + * responsible for closing the {@link java.sql.Connection} when it is no + * longer required. + * + * @throws SQLException if a {@link java.sql.Connection} could not be + * obtained + */ + Connection getConnection() throws SQLException; + + /** + * Get the SQL dialect that should be used for this connection. Note that the + * dialect is not needed if the JDBC driver supports the getGeneratedKeys + * method. + */ + SQLDialectCode getSQLDialectCode(); + + /** + * If the connection supports the JDBC 3.0 getGeneratedKeys method, then + * we do not need any specific dialect support. + */ + boolean supportsGetGeneratedKeys(); - /** - * Get the SQL dialect that should be used for this connection. Note that the - * dialect is not needed if the JDBC driver supports the getGeneratedKeys - * method. - */ - SQLDialectCode getSQLDialectCode(); - - /** - * If the connection supports the JDBC 3.0 getGeneratedKeys method, then - * we do not need any specific dialect support. - */ - boolean supportsGetGeneratedKeys(); - - /** - * If the connection does not support batch updates, we will avoid using them. - */ - boolean supportsBatchUpdates(); + /** + * If the connection does not support batch updates, we will avoid using them. + */ + boolean supportsBatchUpdates(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSourceBase.java b/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSourceBase.java index d4d1fea93fb50e746f56685724088110ec9275f3..ccf1e4cb9d9bd3579cf94993d89b08b395af3f16 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSourceBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/ConnectionSourceBase.java @@ -21,111 +21,108 @@ import ch.qos.logback.core.db.dialect.DBUtil; import ch.qos.logback.core.db.dialect.SQLDialectCode; import ch.qos.logback.core.spi.ContextAwareBase; - /** * @author Ceki Gülcü */ public abstract class ConnectionSourceBase extends ContextAwareBase implements ConnectionSource { - - private boolean started; - - private String user = null; - private String password = null; - - // initially we have an unknown dialect - private SQLDialectCode dialectCode = SQLDialectCode.UNKNOWN_DIALECT; - private boolean supportsGetGeneratedKeys = false; - private boolean supportsBatchUpdates = false; - - - /** - * Learn relevant information about this connection source. - * - */ - public void discoverConnectionProperties() { - Connection connection = null; - try { - connection = getConnection(); - if (connection == null) { - addWarn("Could not get a connection"); - return; - } - DatabaseMetaData meta = connection.getMetaData(); - DBUtil util = new DBUtil(); - util.setContext(getContext()); - supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta); - supportsBatchUpdates = util.supportsBatchUpdates(meta); - dialectCode = DBUtil.discoverSQLDialect(meta); - addInfo("Driver name="+meta.getDriverName()); - addInfo("Driver version="+meta.getDriverVersion()); - addInfo("supportsGetGeneratedKeys="+supportsGetGeneratedKeys); - - } catch (SQLException se) { - addWarn("Could not discover the dialect to use.", se); - } finally { - DBHelper.closeConnection(connection); + + private boolean started; + + private String user = null; + private String password = null; + + // initially we have an unknown dialect + private SQLDialectCode dialectCode = SQLDialectCode.UNKNOWN_DIALECT; + private boolean supportsGetGeneratedKeys = false; + private boolean supportsBatchUpdates = false; + + /** + * Learn relevant information about this connection source. + * + */ + public void discoverConnectionProperties() { + Connection connection = null; + try { + connection = getConnection(); + if (connection == null) { + addWarn("Could not get a connection"); + return; + } + DatabaseMetaData meta = connection.getMetaData(); + DBUtil util = new DBUtil(); + util.setContext(getContext()); + supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta); + supportsBatchUpdates = util.supportsBatchUpdates(meta); + dialectCode = DBUtil.discoverSQLDialect(meta); + addInfo("Driver name=" + meta.getDriverName()); + addInfo("Driver version=" + meta.getDriverVersion()); + addInfo("supportsGetGeneratedKeys=" + supportsGetGeneratedKeys); + + } catch (SQLException se) { + addWarn("Could not discover the dialect to use.", se); + } finally { + DBHelper.closeConnection(connection); + } + } + + /** + * Does this connection support the JDBC Connection.getGeneratedKeys method? + */ + public final boolean supportsGetGeneratedKeys() { + return supportsGetGeneratedKeys; + } + + public final SQLDialectCode getSQLDialectCode() { + return dialectCode; + } + + /** + * Get the password for this connection source. + */ + public final String getPassword() { + return password; + } + + /** + * Sets the password. + * @param password The password to set + */ + public final void setPassword(final String password) { + this.password = password; + } + + /** + * Get the user for this connection source. + */ + public final String getUser() { + return user; } - } - - /** - * Does this connection support the JDBC Connection.getGeneratedKeys method? - */ - public final boolean supportsGetGeneratedKeys() { - return supportsGetGeneratedKeys; - } - - public final SQLDialectCode getSQLDialectCode() { - return dialectCode; - } - - /** - * Get the password for this connection source. - */ - public final String getPassword() { - return password; - } - - /** - * Sets the password. - * @param password The password to set - */ - public final void setPassword(final String password) { - this.password = password; - } - - /** - * Get the user for this connection source. - */ - public final String getUser() { - return user; - } - - /** - * Sets the username. - * @param username The username to set - */ - public final void setUser(final String username) { - this.user = username; - } - - /** - * Does this connection support batch updates? - */ - public final boolean supportsBatchUpdates() { - return supportsBatchUpdates; - } - - public boolean isStarted() { - return started; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - } - - + + /** + * Sets the username. + * @param username The username to set + */ + public final void setUser(final String username) { + this.user = username; + } + + /** + * Does this connection support batch updates? + */ + public final boolean supportsBatchUpdates() { + return supportsBatchUpdates; + } + + public boolean isStarted() { + return started; + } + + public void start() { + started = true; + } + + public void stop() { + started = false; + } + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/DBAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/db/DBAppenderBase.java index 4fc94e22b2d8370390d115e3bd0c4464ed910ebc..9b4c37d8ab87571bd4bbdd7c5fa924ad7b2cbeb0 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/DBAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/DBAppenderBase.java @@ -33,147 +33,138 @@ import ch.qos.logback.core.db.dialect.SQLDialectCode; */ public abstract class DBAppenderBase extends UnsynchronizedAppenderBase { - protected ConnectionSource connectionSource; - protected boolean cnxSupportsGetGeneratedKeys = false; - protected boolean cnxSupportsBatchUpdates = false; - protected SQLDialect sqlDialect; + protected ConnectionSource connectionSource; + protected boolean cnxSupportsGetGeneratedKeys = false; + protected boolean cnxSupportsBatchUpdates = false; + protected SQLDialect sqlDialect; - protected abstract Method getGeneratedKeysMethod(); + protected abstract Method getGeneratedKeysMethod(); - protected abstract String getInsertSQL(); + protected abstract String getInsertSQL(); - @Override - public void start() { + @Override + public void start() { - if (connectionSource == null) { - throw new IllegalStateException( - "DBAppender cannot function without a connection source"); + if (connectionSource == null) { + throw new IllegalStateException("DBAppender cannot function without a connection source"); + } + + sqlDialect = DBUtil.getDialectFromCode(connectionSource.getSQLDialectCode()); + if (getGeneratedKeysMethod() != null) { + cnxSupportsGetGeneratedKeys = connectionSource.supportsGetGeneratedKeys(); + } else { + cnxSupportsGetGeneratedKeys = false; + } + cnxSupportsBatchUpdates = connectionSource.supportsBatchUpdates(); + if (!cnxSupportsGetGeneratedKeys && (sqlDialect == null)) { + throw new IllegalStateException( + "DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method *and* without a specific SQL dialect"); + } + + // all nice and dandy on the eastern front + super.start(); } - sqlDialect = DBUtil - .getDialectFromCode(connectionSource.getSQLDialectCode()); - if (getGeneratedKeysMethod() != null) { - cnxSupportsGetGeneratedKeys = connectionSource.supportsGetGeneratedKeys(); - } else { - cnxSupportsGetGeneratedKeys = false; + /** + * @return Returns the connectionSource. + */ + public ConnectionSource getConnectionSource() { + return connectionSource; } - cnxSupportsBatchUpdates = connectionSource.supportsBatchUpdates(); - if (!cnxSupportsGetGeneratedKeys && (sqlDialect == null)) { - throw new IllegalStateException( - "DBAppender cannot function if the JDBC driver does not support getGeneratedKeys method *and* without a specific SQL dialect"); + + /** + * @param connectionSource + * The connectionSource to set. + */ + public void setConnectionSource(ConnectionSource connectionSource) { + this.connectionSource = connectionSource; } - // all nice and dandy on the eastern front - super.start(); - } - - /** - * @return Returns the connectionSource. - */ - public ConnectionSource getConnectionSource() { - return connectionSource; - } - - /** - * @param connectionSource - * The connectionSource to set. - */ - public void setConnectionSource(ConnectionSource connectionSource) { - this.connectionSource = connectionSource; - } - - @Override - public void append(E eventObject) { - Connection connection = null; - PreparedStatement insertStatement = null; - try { - connection = connectionSource.getConnection(); - connection.setAutoCommit(false); - - if (cnxSupportsGetGeneratedKeys) { - String EVENT_ID_COL_NAME = "EVENT_ID"; - // see - if (connectionSource.getSQLDialectCode() == SQLDialectCode.POSTGRES_DIALECT) { - EVENT_ID_COL_NAME = EVENT_ID_COL_NAME.toLowerCase(); + @Override + public void append(E eventObject) { + Connection connection = null; + PreparedStatement insertStatement = null; + try { + connection = connectionSource.getConnection(); + connection.setAutoCommit(false); + + if (cnxSupportsGetGeneratedKeys) { + String EVENT_ID_COL_NAME = "EVENT_ID"; + // see + if (connectionSource.getSQLDialectCode() == SQLDialectCode.POSTGRES_DIALECT) { + EVENT_ID_COL_NAME = EVENT_ID_COL_NAME.toLowerCase(); + } + insertStatement = connection.prepareStatement(getInsertSQL(), new String[] { EVENT_ID_COL_NAME }); + } else { + insertStatement = connection.prepareStatement(getInsertSQL()); + } + + long eventId; + // inserting an event and getting the result must be exclusive + synchronized (this) { + subAppend(eventObject, connection, insertStatement); + eventId = selectEventId(insertStatement, connection); + } + secondarySubAppend(eventObject, connection, eventId); + + connection.commit(); + } catch (Throwable sqle) { + addError("problem appending event", sqle); + } finally { + DBHelper.closeStatement(insertStatement); + DBHelper.closeConnection(connection); } - insertStatement = connection.prepareStatement(getInsertSQL(), - new String[] { EVENT_ID_COL_NAME }); - } else { - insertStatement = connection.prepareStatement(getInsertSQL()); - } - - long eventId; - // inserting an event and getting the result must be exclusive - synchronized (this) { - subAppend(eventObject, connection, insertStatement); - eventId = selectEventId(insertStatement, connection); - } - secondarySubAppend(eventObject, connection, eventId); - - connection.commit(); - } catch (Throwable sqle) { - addError("problem appending event", sqle); - } finally { - DBHelper.closeStatement(insertStatement); - DBHelper.closeConnection(connection); } - } - protected abstract void subAppend(E eventObject, Connection connection, - PreparedStatement statement) throws Throwable; + protected abstract void subAppend(E eventObject, Connection connection, PreparedStatement statement) throws Throwable; - protected abstract void secondarySubAppend(E eventObject, Connection connection, - long eventId) throws Throwable; + protected abstract void secondarySubAppend(E eventObject, Connection connection, long eventId) throws Throwable; - protected long selectEventId(PreparedStatement insertStatement, - Connection connection) throws SQLException, InvocationTargetException { - ResultSet rs = null; - Statement idStatement = null; - try { - boolean gotGeneratedKeys = false; - if (cnxSupportsGetGeneratedKeys) { + protected long selectEventId(PreparedStatement insertStatement, Connection connection) throws SQLException, InvocationTargetException { + ResultSet rs = null; + Statement idStatement = null; try { - rs = (ResultSet) getGeneratedKeysMethod().invoke(insertStatement, - (Object[]) null); - gotGeneratedKeys = true; - } catch (InvocationTargetException ex) { - Throwable target = ex.getTargetException(); - if (target instanceof SQLException) { - throw (SQLException) target; - } - throw ex; - } catch (IllegalAccessException ex) { - addWarn( - "IllegalAccessException invoking PreparedStatement.getGeneratedKeys", - ex); + boolean gotGeneratedKeys = false; + if (cnxSupportsGetGeneratedKeys) { + try { + rs = (ResultSet) getGeneratedKeysMethod().invoke(insertStatement, (Object[]) null); + gotGeneratedKeys = true; + } catch (InvocationTargetException ex) { + Throwable target = ex.getTargetException(); + if (target instanceof SQLException) { + throw (SQLException) target; + } + throw ex; + } catch (IllegalAccessException ex) { + addWarn("IllegalAccessException invoking PreparedStatement.getGeneratedKeys", ex); + } + } + + if (!gotGeneratedKeys) { + idStatement = connection.createStatement(); + idStatement.setMaxRows(1); + String selectInsertIdStr = sqlDialect.getSelectInsertId(); + rs = idStatement.executeQuery(selectInsertIdStr); + } + + // A ResultSet cursor is initially positioned before the first row; + // the first call to the method next makes the first row the current row + rs.next(); + long eventId = rs.getLong(1); + return eventId; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + DBHelper.closeStatement(idStatement); } - } - - if (!gotGeneratedKeys) { - idStatement = connection.createStatement(); - idStatement.setMaxRows(1); - String selectInsertIdStr = sqlDialect.getSelectInsertId(); - rs = idStatement.executeQuery(selectInsertIdStr); - } - - // A ResultSet cursor is initially positioned before the first row; - // the first call to the method next makes the first row the current row - rs.next(); - long eventId = rs.getLong(1); - return eventId; - } finally { - if (rs!=null) { - try { - rs.close(); - } catch (SQLException e) { - } - } - DBHelper.closeStatement(idStatement); } - } - @Override - public void stop() { - super.stop(); - } + @Override + public void stop() { + super.stop(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/DBHelper.java b/logback-core/src/main/java/ch/qos/logback/core/db/DBHelper.java index e26ee8d896df2b6ec2a2f2e4049cc5b693e56370..61a16e962a0344bf5f4d9ad8d823d3770545919e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/DBHelper.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/DBHelper.java @@ -23,23 +23,23 @@ import java.sql.Statement; */ public class DBHelper { - static public void closeConnection(Connection connection) { - if (connection != null) { - try { - connection.close(); - } catch (SQLException sqle) { - // static utility classes should not log without an explicit repository - // reference - } + static public void closeConnection(Connection connection) { + if (connection != null) { + try { + connection.close(); + } catch (SQLException sqle) { + // static utility classes should not log without an explicit repository + // reference + } + } } - } - public static void closeStatement(Statement statement) { - if (statement != null) { - try { - statement.close(); - } catch (SQLException sqle) { - } + public static void closeStatement(Statement statement) { + if (statement != null) { + try { + statement.close(); + } catch (SQLException sqle) { + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/DataSourceConnectionSource.java b/logback-core/src/main/java/ch/qos/logback/core/db/DataSourceConnectionSource.java index 8faf799859717d1565cdb81b245b6df763b8a91c..9e05cd40fdbd2b1a26388ef5ef7a51eaf1dfeca8 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/DataSourceConnectionSource.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/DataSourceConnectionSource.java @@ -34,43 +34,42 @@ import ch.qos.logback.core.db.dialect.SQLDialectCode; */ public class DataSourceConnectionSource extends ConnectionSourceBase { - private DataSource dataSource; + private DataSource dataSource; - @Override - public void start() { - if (dataSource == null) { - addWarn("WARNING: No data source specified"); - } else { - discoverConnectionProperties(); - if (!supportsGetGeneratedKeys() - && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) { - addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect."); - } + @Override + public void start() { + if (dataSource == null) { + addWarn("WARNING: No data source specified"); + } else { + discoverConnectionProperties(); + if (!supportsGetGeneratedKeys() && getSQLDialectCode() == SQLDialectCode.UNKNOWN_DIALECT) { + addWarn("Connection does not support GetGeneratedKey method and could not discover the dialect."); + } + } + super.start(); } - super.start(); - } - /** - * @see ch.qos.logback.core.db.ConnectionSource#getConnection() - */ - public Connection getConnection() throws SQLException { - if (dataSource == null) { - addError("WARNING: No data source specified"); - return null; - } + /** + * @see ch.qos.logback.core.db.ConnectionSource#getConnection() + */ + public Connection getConnection() throws SQLException { + if (dataSource == null) { + addError("WARNING: No data source specified"); + return null; + } - if (getUser() == null) { - return dataSource.getConnection(); - } else { - return dataSource.getConnection(getUser(), getPassword()); + if (getUser() == null) { + return dataSource.getConnection(); + } else { + return dataSource.getConnection(getUser(), getPassword()); + } } - } - public DataSource getDataSource() { - return dataSource; - } + public DataSource getDataSource() { + return dataSource; + } - public void setDataSource(DataSource dataSource) { - this.dataSource = dataSource; - } + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/DriverManagerConnectionSource.java b/logback-core/src/main/java/ch/qos/logback/core/db/DriverManagerConnectionSource.java index 2c658a5b9aac6b41c54f2d5a2e32354cb372b9c1..43733d6d6688b187f7d66a78ba4c11083206ccdd 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/DriverManagerConnectionSource.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/DriverManagerConnectionSource.java @@ -28,68 +28,68 @@ import java.sql.SQLException; * @author Ray DeCampo */ public class DriverManagerConnectionSource extends ConnectionSourceBase { - private String driverClass = null; - private String url = null; + private String driverClass = null; + private String url = null; - public void start() { - try { - if (driverClass != null) { - Class.forName(driverClass); - discoverConnectionProperties(); - } else { - addError("WARNING: No JDBC driver specified for logback DriverManagerConnectionSource."); - } - } catch (final ClassNotFoundException cnfe) { - addError("Could not load JDBC driver class: " + driverClass, cnfe); + public void start() { + try { + if (driverClass != null) { + Class.forName(driverClass); + discoverConnectionProperties(); + } else { + addError("WARNING: No JDBC driver specified for logback DriverManagerConnectionSource."); + } + } catch (final ClassNotFoundException cnfe) { + addError("Could not load JDBC driver class: " + driverClass, cnfe); + } } - } - /** - * @see ch.qos.logback.core.db.ConnectionSource#getConnection() - */ - public Connection getConnection() throws SQLException { - if (getUser() == null) { - return DriverManager.getConnection(url); - } else { - return DriverManager.getConnection(url, getUser(), getPassword()); + /** + * @see ch.qos.logback.core.db.ConnectionSource#getConnection() + */ + public Connection getConnection() throws SQLException { + if (getUser() == null) { + return DriverManager.getConnection(url); + } else { + return DriverManager.getConnection(url, getUser(), getPassword()); + } } - } - /** - * Returns the url. - * - * @return String - */ - public String getUrl() { - return url; - } + /** + * Returns the url. + * + * @return String + */ + public String getUrl() { + return url; + } - /** - * Sets the url. - * - * @param url - * The url to set - */ - public void setUrl(String url) { - this.url = url; - } + /** + * Sets the url. + * + * @param url + * The url to set + */ + public void setUrl(String url) { + this.url = url; + } - /** - * Returns the name of the driver class. - * - * @return String - */ - public String getDriverClass() { - return driverClass; - } + /** + * Returns the name of the driver class. + * + * @return String + */ + public String getDriverClass() { + return driverClass; + } - /** - * Sets the driver class. - * - * @param driverClass - * The driver class to set - */ - public void setDriverClass(String driverClass) { - this.driverClass = driverClass; - } + /** + * Sets the driver class. + * + * @param driverClass + * The driver class to set + */ + public void setDriverClass(String driverClass) { + this.driverClass = driverClass; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/JNDIConnectionSource.java b/logback-core/src/main/java/ch/qos/logback/core/db/JNDIConnectionSource.java index 3f532ebeeef6ed594aee1fd7fb560205d87111df..d3a30a75ef3a941ad9e8af75c558adc521d6222e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/JNDIConnectionSource.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/JNDIConnectionSource.java @@ -40,74 +40,70 @@ import javax.sql.DataSource; * @author Ray DeCampo */ public class JNDIConnectionSource extends ConnectionSourceBase { - private String jndiLocation = null; - private DataSource dataSource = null; + private String jndiLocation = null; + private DataSource dataSource = null; - public void start() { - if (jndiLocation == null) { - addError("No JNDI location specified for JNDIConnectionSource."); + public void start() { + if (jndiLocation == null) { + addError("No JNDI location specified for JNDIConnectionSource."); + } + discoverConnectionProperties(); } - discoverConnectionProperties(); - } + public Connection getConnection() throws SQLException { + Connection conn = null; + try { + if (dataSource == null) { + dataSource = lookupDataSource(); + } + if (getUser() != null) { + addWarn("Ignoring property [user] with value [" + getUser() + "] for obtaining a connection from a DataSource."); + } + conn = dataSource.getConnection(); + } catch (final NamingException ne) { + addError("Error while getting data source", ne); + throw new SQLException("NamingException while looking up DataSource: " + ne.getMessage()); + } catch (final ClassCastException cce) { + addError("ClassCastException while looking up DataSource.", cce); + throw new SQLException("ClassCastException while looking up DataSource: " + cce.getMessage()); + } - public Connection getConnection() throws SQLException { - Connection conn = null; - try { - if (dataSource == null) { - dataSource = lookupDataSource(); - } - if(getUser() != null) { - addWarn("Ignoring property [user] with value ["+getUser()+"] for obtaining a connection from a DataSource."); - } - conn = dataSource.getConnection(); - } catch (final NamingException ne) { - addError("Error while getting data source", ne); - throw new SQLException("NamingException while looking up DataSource: " - + ne.getMessage()); - } catch (final ClassCastException cce) { - addError("ClassCastException while looking up DataSource.", cce); - throw new SQLException("ClassCastException while looking up DataSource: " - + cce.getMessage()); + return conn; } - return conn; - } - - /** - * Returns the jndiLocation. - * - * @return String - */ - public String getJndiLocation() { - return jndiLocation; - } + /** + * Returns the jndiLocation. + * + * @return String + */ + public String getJndiLocation() { + return jndiLocation; + } - /** - * Sets the jndiLocation. - * - * @param jndiLocation - * The jndiLocation to set - */ - public void setJndiLocation(String jndiLocation) { - this.jndiLocation = jndiLocation; - } + /** + * Sets the jndiLocation. + * + * @param jndiLocation + * The jndiLocation to set + */ + public void setJndiLocation(String jndiLocation) { + this.jndiLocation = jndiLocation; + } - private DataSource lookupDataSource() throws NamingException, SQLException { - addInfo("Looking up ["+jndiLocation+"] in JNDI"); - DataSource ds; - Context initialContext = new InitialContext(); - Object obj = initialContext.lookup(jndiLocation); + private DataSource lookupDataSource() throws NamingException, SQLException { + addInfo("Looking up [" + jndiLocation + "] in JNDI"); + DataSource ds; + Context initialContext = new InitialContext(); + Object obj = initialContext.lookup(jndiLocation); - // PortableRemoteObject was introduced in JDK 1.3. We won't use it. - // ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class); - ds = (DataSource) obj; + // PortableRemoteObject was introduced in JDK 1.3. We won't use it. + // ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class); + ds = (DataSource) obj; - if (ds == null) { - throw new SQLException("Failed to obtain data source from JNDI location " - + jndiLocation); - } else { - return ds; + if (ds == null) { + throw new SQLException("Failed to obtain data source from JNDI location " + jndiLocation); + } else { + return ds; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/DBUtil.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/DBUtil.java index 00d97431a4f0d9f1c2c7a4b224cb7a3de7d7c59e..b3b0724d0261431a23d01f935879ae0048288cec 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/DBUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/DBUtil.java @@ -24,118 +24,116 @@ import ch.qos.logback.core.spi.ContextAwareBase; * */ public class DBUtil extends ContextAwareBase { - private static final String POSTGRES_PART = "postgresql"; - private static final String MYSQL_PART = "mysql"; - private static final String ORACLE_PART = "oracle"; - // private static final String MSSQL_PART = "mssqlserver4"; - private static final String MSSQL_PART = "microsoft"; - private static final String HSQL_PART = "hsql"; - private static final String H2_PART = "h2"; - private static final String SYBASE_SQLANY_PART = "sql anywhere"; - private static final String SQLITE_PART = "sqlite"; - - public static SQLDialectCode discoverSQLDialect(DatabaseMetaData meta) { - SQLDialectCode dialectCode = SQLDialectCode.UNKNOWN_DIALECT; - - try { - - String dbName = meta.getDatabaseProductName().toLowerCase(); - - if (dbName.indexOf(POSTGRES_PART) != -1) { - return SQLDialectCode.POSTGRES_DIALECT; - } else if (dbName.indexOf(MYSQL_PART) != -1) { - return SQLDialectCode.MYSQL_DIALECT; - } else if (dbName.indexOf(ORACLE_PART) != -1) { - return SQLDialectCode.ORACLE_DIALECT; - } else if (dbName.indexOf(MSSQL_PART) != -1) { - return SQLDialectCode.MSSQL_DIALECT; - } else if (dbName.indexOf(HSQL_PART) != -1) { - return SQLDialectCode.HSQL_DIALECT; - } else if (dbName.indexOf(H2_PART) != -1) { - return SQLDialectCode.H2_DIALECT; - } else if (dbName.indexOf(SYBASE_SQLANY_PART) != -1) { - return SQLDialectCode.SYBASE_SQLANYWHERE_DIALECT; - } else if (dbName.indexOf(SQLITE_PART) != -1) { - return SQLDialectCode.SQLITE_DIALECT; - } else { - return SQLDialectCode.UNKNOWN_DIALECT; - } - } catch (SQLException sqle) { - // we can't do much here + private static final String POSTGRES_PART = "postgresql"; + private static final String MYSQL_PART = "mysql"; + private static final String ORACLE_PART = "oracle"; + // private static final String MSSQL_PART = "mssqlserver4"; + private static final String MSSQL_PART = "microsoft"; + private static final String HSQL_PART = "hsql"; + private static final String H2_PART = "h2"; + private static final String SYBASE_SQLANY_PART = "sql anywhere"; + private static final String SQLITE_PART = "sqlite"; + + public static SQLDialectCode discoverSQLDialect(DatabaseMetaData meta) { + SQLDialectCode dialectCode = SQLDialectCode.UNKNOWN_DIALECT; + + try { + + String dbName = meta.getDatabaseProductName().toLowerCase(); + + if (dbName.indexOf(POSTGRES_PART) != -1) { + return SQLDialectCode.POSTGRES_DIALECT; + } else if (dbName.indexOf(MYSQL_PART) != -1) { + return SQLDialectCode.MYSQL_DIALECT; + } else if (dbName.indexOf(ORACLE_PART) != -1) { + return SQLDialectCode.ORACLE_DIALECT; + } else if (dbName.indexOf(MSSQL_PART) != -1) { + return SQLDialectCode.MSSQL_DIALECT; + } else if (dbName.indexOf(HSQL_PART) != -1) { + return SQLDialectCode.HSQL_DIALECT; + } else if (dbName.indexOf(H2_PART) != -1) { + return SQLDialectCode.H2_DIALECT; + } else if (dbName.indexOf(SYBASE_SQLANY_PART) != -1) { + return SQLDialectCode.SYBASE_SQLANYWHERE_DIALECT; + } else if (dbName.indexOf(SQLITE_PART) != -1) { + return SQLDialectCode.SQLITE_DIALECT; + } else { + return SQLDialectCode.UNKNOWN_DIALECT; + } + } catch (SQLException sqle) { + // we can't do much here + } + + return dialectCode; } - return dialectCode; - } - - public static SQLDialect getDialectFromCode(SQLDialectCode sqlDialectType) { - SQLDialect sqlDialect = null; - - switch (sqlDialectType) { - case POSTGRES_DIALECT: - sqlDialect = new PostgreSQLDialect(); - break; - - case MYSQL_DIALECT: - sqlDialect = new MySQLDialect(); - break; - - case ORACLE_DIALECT: - sqlDialect = new OracleDialect(); - break; - - case MSSQL_DIALECT: - sqlDialect = new MsSQLDialect(); - break; - - case HSQL_DIALECT: - sqlDialect = new HSQLDBDialect(); - break; - - case H2_DIALECT: - sqlDialect = new H2Dialect(); - break; - - case SYBASE_SQLANYWHERE_DIALECT: - sqlDialect = new SybaseSqlAnywhereDialect(); - break; - - case SQLITE_DIALECT: - sqlDialect = new SQLiteDialect(); - break; + public static SQLDialect getDialectFromCode(SQLDialectCode sqlDialectType) { + SQLDialect sqlDialect = null; + + switch (sqlDialectType) { + case POSTGRES_DIALECT: + sqlDialect = new PostgreSQLDialect(); + break; + + case MYSQL_DIALECT: + sqlDialect = new MySQLDialect(); + break; + + case ORACLE_DIALECT: + sqlDialect = new OracleDialect(); + break; + + case MSSQL_DIALECT: + sqlDialect = new MsSQLDialect(); + break; + + case HSQL_DIALECT: + sqlDialect = new HSQLDBDialect(); + break; + + case H2_DIALECT: + sqlDialect = new H2Dialect(); + break; + + case SYBASE_SQLANYWHERE_DIALECT: + sqlDialect = new SybaseSqlAnywhereDialect(); + break; + + case SQLITE_DIALECT: + sqlDialect = new SQLiteDialect(); + break; + } + return sqlDialect; } - return sqlDialect; - } - - /** - * This method handles cases where the - * {@link DatabaseMetaData#supportsGetGeneratedKeys} method is missing in the - * JDBC driver implementation. - */ - public boolean supportsGetGeneratedKeys(DatabaseMetaData meta) { - try { - // - // invoking JDBC 1.4 method by reflection - // - return ((Boolean) DatabaseMetaData.class.getMethod( - "supportsGetGeneratedKeys", (Class[]) null).invoke(meta, - (Object[]) null)).booleanValue(); - } catch (Throwable e) { - addInfo("Could not call supportsGetGeneratedKeys method. This may be recoverable"); - return false; + + /** + * This method handles cases where the + * {@link DatabaseMetaData#supportsGetGeneratedKeys} method is missing in the + * JDBC driver implementation. + */ + public boolean supportsGetGeneratedKeys(DatabaseMetaData meta) { + try { + // + // invoking JDBC 1.4 method by reflection + // + return ((Boolean) DatabaseMetaData.class.getMethod("supportsGetGeneratedKeys", (Class[]) null).invoke(meta, (Object[]) null)).booleanValue(); + } catch (Throwable e) { + addInfo("Could not call supportsGetGeneratedKeys method. This may be recoverable"); + return false; + } } - } - - /** - * This method handles cases where the - * {@link DatabaseMetaData#supportsBatchUpdates} method is missing in the JDBC - * driver implementation. - */ - public boolean supportsBatchUpdates(DatabaseMetaData meta) { - try { - return meta.supportsBatchUpdates(); - } catch (Throwable e) { - addInfo("Missing DatabaseMetaData.supportsBatchUpdates method."); - return false; + + /** + * This method handles cases where the + * {@link DatabaseMetaData#supportsBatchUpdates} method is missing in the JDBC + * driver implementation. + */ + public boolean supportsBatchUpdates(DatabaseMetaData meta) { + try { + return meta.supportsBatchUpdates(); + } catch (Throwable e) { + addInfo("Missing DatabaseMetaData.supportsBatchUpdates method."); + return false; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/H2Dialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/H2Dialect.java index cb7b07fbd6f84eb40031a152533e30ed206f1cd8..3365736e41964afb366d84682ce076e45de9e895 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/H2Dialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/H2Dialect.java @@ -19,10 +19,10 @@ package ch.qos.logback.core.db.dialect; * @author Ceki Gülcü */ public class H2Dialect implements SQLDialect { - public static final String SELECT_CURRVAL = "CALL IDENTITY()"; + public static final String SELECT_CURRVAL = "CALL IDENTITY()"; + + public String getSelectInsertId() { + return SELECT_CURRVAL; + } - public String getSelectInsertId() { - return SELECT_CURRVAL; - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/HSQLDBDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/HSQLDBDialect.java index a1a001000200bbd1f7648da88ffb92713c50cee9..f91803131985f7d473cc6cc2ce3aeea1f1efa417 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/HSQLDBDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/HSQLDBDialect.java @@ -19,10 +19,10 @@ package ch.qos.logback.core.db.dialect; * @author Ceki Gülcü */ public class HSQLDBDialect implements SQLDialect { - public static final String SELECT_CURRVAL = "CALL IDENTITY()"; + public static final String SELECT_CURRVAL = "CALL IDENTITY()"; + + public String getSelectInsertId() { + return SELECT_CURRVAL; + } - public String getSelectInsertId() { - return SELECT_CURRVAL; - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MsSQLDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MsSQLDialect.java index 5522c2a8adf38b5c0835cc4afc0e488788d8db45..c5b2934ea71711e17556f2da40b5212e4b045a00 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MsSQLDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MsSQLDialect.java @@ -11,7 +11,7 @@ * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ -package ch.qos.logback.core.db.dialect; +package ch.qos.logback.core.db.dialect; /** * The MS SQL Server dialect is untested. @@ -20,11 +20,11 @@ package ch.qos.logback.core.db.dialect; * the getGeneratedKeys method introduced in JDBC 3.0 specification. * * @author James Stauffer -*/ -public class MsSQLDialect implements SQLDialect { - public static final String SELECT_CURRVAL = "SELECT @@identity id"; +*/ +public class MsSQLDialect implements SQLDialect { + public static final String SELECT_CURRVAL = "SELECT @@identity id"; - public String getSelectInsertId() { - return SELECT_CURRVAL; - } + public String getSelectInsertId() { + return SELECT_CURRVAL; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MySQLDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MySQLDialect.java index 20b0ae85004a97c7f893e5286f26c8b3a7bc9cc7..12b475a041346c7196bbf9d2562d1953f9e810d3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MySQLDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/MySQLDialect.java @@ -20,9 +20,9 @@ package ch.qos.logback.core.db.dialect; * */ public class MySQLDialect implements SQLDialect { - public static final String SELECT_LAST_INSERT_ID = "SELECT LAST_INSERT_ID()"; - - public String getSelectInsertId() { - return SELECT_LAST_INSERT_ID; - } + public static final String SELECT_LAST_INSERT_ID = "SELECT LAST_INSERT_ID()"; + + public String getSelectInsertId() { + return SELECT_LAST_INSERT_ID; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/OracleDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/OracleDialect.java index 096bf46aa3bb5c983c6c701ae779603b37ee34d3..813e478621291609861d3d42c4e66f719b424dbb 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/OracleDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/OracleDialect.java @@ -20,10 +20,10 @@ package ch.qos.logback.core.db.dialect; * @author Ceki Gülcü */ public class OracleDialect implements SQLDialect { - public static final String SELECT_CURRVAL = "SELECT logging_event_id_seq.currval from dual"; + public static final String SELECT_CURRVAL = "SELECT logging_event_id_seq.currval from dual"; - public String getSelectInsertId() { - return SELECT_CURRVAL; - } + public String getSelectInsertId() { + return SELECT_CURRVAL; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/PostgreSQLDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/PostgreSQLDialect.java index 134491bb0579f92bff6145dce9f8f6ea85656f0c..a5bb181478a6acd6c8df79625a3f73190c4ff658 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/PostgreSQLDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/PostgreSQLDialect.java @@ -13,17 +13,15 @@ */ package ch.qos.logback.core.db.dialect; - /** * * @author ceki * */ -public class PostgreSQLDialect - implements SQLDialect { - public static final String SELECT_CURRVAL = "SELECT currval('logging_event_id_seq')"; +public class PostgreSQLDialect implements SQLDialect { + public static final String SELECT_CURRVAL = "SELECT currval('logging_event_id_seq')"; - public String getSelectInsertId() { - return SELECT_CURRVAL; - } + public String getSelectInsertId() { + return SELECT_CURRVAL; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialect.java index fa5e81127dc5d7140571a4df796dc824725088b5..a427749f8122f7013c36340abc3c8162436826b3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialect.java @@ -18,5 +18,5 @@ package ch.qos.logback.core.db.dialect; * */ public interface SQLDialect { - String getSelectInsertId(); + String getSelectInsertId(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialectCode.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialectCode.java index f08159ebd7538b1044de1d70ac92c979efa497b1..dde41edeac8cf2eb7a4092f9a105246a341f69e0 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialectCode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLDialectCode.java @@ -14,13 +14,5 @@ package ch.qos.logback.core.db.dialect; public enum SQLDialectCode { - UNKNOWN_DIALECT, - POSTGRES_DIALECT, - MYSQL_DIALECT, - ORACLE_DIALECT, - MSSQL_DIALECT, - HSQL_DIALECT, - H2_DIALECT, - SYBASE_SQLANYWHERE_DIALECT, - SQLITE_DIALECT; + UNKNOWN_DIALECT, POSTGRES_DIALECT, MYSQL_DIALECT, ORACLE_DIALECT, MSSQL_DIALECT, HSQL_DIALECT, H2_DIALECT, SYBASE_SQLANYWHERE_DIALECT, SQLITE_DIALECT; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLiteDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLiteDialect.java index 658adba0a3b3ca84d57b6bc7836d83ab97ad4b94..6b6a9a59e55e535096606f7bfcd271709f7e6c78 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLiteDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SQLiteDialect.java @@ -22,10 +22,9 @@ package ch.qos.logback.core.db.dialect; * @author Anthony Trinh */ public class SQLiteDialect implements SQLDialect { - public static final String SELECT_CURRVAL = "SELECT last_insert_rowid();"; + public static final String SELECT_CURRVAL = "SELECT last_insert_rowid();"; - public String getSelectInsertId() { - return SELECT_CURRVAL; - } + public String getSelectInsertId() { + return SELECT_CURRVAL; + } } - diff --git a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SybaseSqlAnywhereDialect.java b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SybaseSqlAnywhereDialect.java index 319244ef86c46f281e4e510b8598c1924dcb1926..1d68740c9cfe0072b127c0735bea69ea8630dd6b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SybaseSqlAnywhereDialect.java +++ b/logback-core/src/main/java/ch/qos/logback/core/db/dialect/SybaseSqlAnywhereDialect.java @@ -15,19 +15,19 @@ package ch.qos.logback.core.db.dialect; public class SybaseSqlAnywhereDialect implements SQLDialect { - /** - * The Sybase SQLAnywhere Dialect - * - * Note that the dialect is not needed if your JDBC driver supports - * the getGeneratedKeys method introduced in JDBC 3.0 specification. - * - * @author Michael Lynch - */ + /** + * The Sybase SQLAnywhere Dialect + * + * Note that the dialect is not needed if your JDBC driver supports + * the getGeneratedKeys method introduced in JDBC 3.0 specification. + * + * @author Michael Lynch + */ - public static final String SELECT_CURRVAL = "SELECT @@identity id"; + public static final String SELECT_CURRVAL = "SELECT @@identity id"; - public String getSelectInsertId() { - return SELECT_CURRVAL; - } + public String getSelectInsertId() { + return SELECT_CURRVAL; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/ByteArrayUtil.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/ByteArrayUtil.java index dadd57302206a4ddc31ba224872250f21804f795..5c6660d81100f4b2d14568f6c67a2383f2088d12 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/ByteArrayUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/ByteArrayUtil.java @@ -17,53 +17,53 @@ import java.io.ByteArrayOutputStream; public class ByteArrayUtil { - // big-endian - static void writeInt(byte[] byteArray, int offset, int i) { - for (int j = 0; j < 4; j++) { - int shift = 24 - j * 8; - byteArray[offset + j] = (byte) (i >>> shift); + // big-endian + static void writeInt(byte[] byteArray, int offset, int i) { + for (int j = 0; j < 4; j++) { + int shift = 24 - j * 8; + byteArray[offset + j] = (byte) (i >>> shift); + } } - } - static void writeInt(ByteArrayOutputStream baos, int i) { - for (int j = 0; j < 4; j++) { - int shift = 24 - j * 8; - baos.write((byte) (i >>> shift)); + static void writeInt(ByteArrayOutputStream baos, int i) { + for (int j = 0; j < 4; j++) { + int shift = 24 - j * 8; + baos.write((byte) (i >>> shift)); + } } - } - - // big-endian - static int readInt(byte[] byteArray, int offset) { - int i = 0; - for (int j = 0; j < 4; j++) { - int shift = 24 - j * 8; - i += (byteArray[offset + j] & 0xFF) << shift; + + // big-endian + static int readInt(byte[] byteArray, int offset) { + int i = 0; + for (int j = 0; j < 4; j++) { + int shift = 24 - j * 8; + i += (byteArray[offset + j] & 0xFF) << shift; + } + return i; } - return i; - } - - static public String toHexString(byte[] ba) { - StringBuilder sbuf = new StringBuilder(); - for(byte b: ba) { - String s = Integer.toHexString( (int)(b & 0xff)); - if(s.length() == 1) { - sbuf.append('0'); - } - sbuf.append(s); + + static public String toHexString(byte[] ba) { + StringBuilder sbuf = new StringBuilder(); + for (byte b : ba) { + String s = Integer.toHexString((int) (b & 0xff)); + if (s.length() == 1) { + sbuf.append('0'); + } + sbuf.append(s); + } + return sbuf.toString(); } - return sbuf.toString(); - } - static public byte[] hexStringToByteArray(String s) { - int len = s.length(); - byte[] ba = new byte[len/2]; + static public byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] ba = new byte[len / 2]; - for(int i = 0; i < ba.length; i++) { - int j = i*2; - int t = Integer.parseInt(s.substring(j, j+2), 16); - byte b = (byte) (t & 0xFF); - ba[i] = b; + for (int i = 0; i < ba.length; i++) { + int j = i * 2; + int t = Integer.parseInt(s.substring(j, j + 2), 16); + byte b = (byte) (t & 0xFF); + ba[i] = b; + } + return ba; } - return ba; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/EchoEncoder.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/EchoEncoder.java index 9ef4d53057d86f81b5bbaa9ad7f7ebede5e82f5b..f83787563d9a94d0cc01cf666f4870dd332b818e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/EchoEncoder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/EchoEncoder.java @@ -20,28 +20,28 @@ import ch.qos.logback.core.CoreConstants; public class EchoEncoder extends EncoderBase { - String fileHeader; - String fileFooter; + String fileHeader; + String fileFooter; - public void doEncode(E event) throws IOException { - String val = event + CoreConstants.LINE_SEPARATOR; - outputStream.write(val.getBytes()); - // necessary if ResilientFileOutputStream is buffered - outputStream.flush(); - } + public void doEncode(E event) throws IOException { + String val = event + CoreConstants.LINE_SEPARATOR; + outputStream.write(val.getBytes()); + // necessary if ResilientFileOutputStream is buffered + outputStream.flush(); + } - public void close() throws IOException { - if (fileFooter == null) { - return; + public void close() throws IOException { + if (fileFooter == null) { + return; + } + outputStream.write(fileFooter.getBytes()); } - outputStream.write(fileFooter.getBytes()); - } - public void init(OutputStream os) throws IOException { - super.init(os); - if (fileHeader == null) { - return; + public void init(OutputStream os) throws IOException { + super.init(os); + if (fileHeader == null) { + return; + } + outputStream.write(fileHeader.getBytes()); } - outputStream.write(fileHeader.getBytes()); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/Encoder.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/Encoder.java index 8cbfb426a951ecc168c8e5dc7dad53f730a11900..c7b3b84b43c4748e929995a1dbd3bcd2065c4b80 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/Encoder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/Encoder.java @@ -36,33 +36,33 @@ import ch.qos.logback.core.spi.LifeCycle; */ public interface Encoder extends ContextAware, LifeCycle { - /** - * This method is called when the owning appender starts or whenever output - * needs to be directed to a new OutputStream, for instance as a result of a - * rollover. Implementing encoders should at the very least remember the - * OutputStream passed as argument and use it in future operations. - * - * @param os - * @throws IOException - */ - void init(OutputStream os) throws IOException; + /** + * This method is called when the owning appender starts or whenever output + * needs to be directed to a new OutputStream, for instance as a result of a + * rollover. Implementing encoders should at the very least remember the + * OutputStream passed as argument and use it in future operations. + * + * @param os + * @throws IOException + */ + void init(OutputStream os) throws IOException; - /** - * Encode and write an event to the appropriate {@link OutputStream}. - * Implementations are free to differ writing out of the encoded event and - * instead write in batches. - * - * @param event - * @throws IOException - */ - void doEncode(E event) throws IOException; + /** + * Encode and write an event to the appropriate {@link OutputStream}. + * Implementations are free to differ writing out of the encoded event and + * instead write in batches. + * + * @param event + * @throws IOException + */ + void doEncode(E event) throws IOException; - /** - * This method is called prior to the closing of the underling - * {@link OutputStream}. Implementations MUST not close the underlying - * {@link OutputStream} which is the responsibility of the owning appender. - * - * @throws IOException - */ - void close() throws IOException; + /** + * This method is called prior to the closing of the underling + * {@link OutputStream}. Implementations MUST not close the underlying + * {@link OutputStream} which is the responsibility of the owning appender. + * + * @throws IOException + */ + void close() throws IOException; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/EncoderBase.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/EncoderBase.java index ddebfbee0077e3da4efc4c7ce24f61e764e66314..650eecab27ac5455dd07b396cc831d66c5828339 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/EncoderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/EncoderBase.java @@ -20,24 +20,23 @@ import ch.qos.logback.core.spi.ContextAwareBase; abstract public class EncoderBase extends ContextAwareBase implements Encoder { - protected boolean started; - - protected OutputStream outputStream; - - public void init(OutputStream os) throws IOException { - this.outputStream = os; - } - - public boolean isStarted() { - return started; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - } -} + protected boolean started; + protected OutputStream outputStream; + + public void init(OutputStream os) throws IOException { + this.outputStream = os; + } + + public boolean isStarted() { + return started; + } + + public void start() { + started = true; + } + + public void stop() { + started = false; + } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/EventObjectInputStream.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/EventObjectInputStream.java index a7a82652c9d1e7f2543a4f6374e29a25dfb1a786..23d1fc21837a8742aa39dacb0bc51c909f8c0607 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/EventObjectInputStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/EventObjectInputStream.java @@ -32,128 +32,125 @@ import java.util.List; */ public class EventObjectInputStream extends InputStream { - NonClosableInputStream ncis; - List buffer = new ArrayList(); + NonClosableInputStream ncis; + List buffer = new ArrayList(); - int index = 0; + int index = 0; - EventObjectInputStream(InputStream is) throws IOException { - this.ncis = new NonClosableInputStream(is); - } - - @Override - public int read() throws IOException { - throw new UnsupportedOperationException( - "Only the readEvent method is supported."); - } - - /** - * Returns the number of bytes available - */ - public int available() throws IOException { - return ncis.available(); - } - - public E readEvent() throws IOException { - - E event = getFromBuffer(); - if (event != null) { - return event; + EventObjectInputStream(InputStream is) throws IOException { + this.ncis = new NonClosableInputStream(is); } - internalReset(); - int count = readHeader(); - if(count == -1) { - return null; + @Override + public int read() throws IOException { + throw new UnsupportedOperationException("Only the readEvent method is supported."); } - readPayload(count); - readFooter(count); - return getFromBuffer(); - } - - private void internalReset() { - index = 0; - buffer.clear(); - } - - E getFromBuffer() { - if (index >= buffer.size()) { - return null; + + /** + * Returns the number of bytes available + */ + public int available() throws IOException { + return ncis.available(); } - return buffer.get(this.index++); - } - - int readHeader() throws IOException { - byte[] headerBA = new byte[4 * BYTES_PER_INT]; - //System.out.println("available="+ncis.available()); - int bytesRead = ncis.read(headerBA); - if(bytesRead == -1) { - return -1; + + public E readEvent() throws IOException { + + E event = getFromBuffer(); + if (event != null) { + return event; + } + + internalReset(); + int count = readHeader(); + if (count == -1) { + return null; + } + readPayload(count); + readFooter(count); + return getFromBuffer(); } - //System.out.println("**bytesRead="+bytesRead); - - //System.out.println(ByteArrayUtil.toHexString(headerBA)); - - int offset = 0; - int startPebble = ByteArrayUtil.readInt(headerBA, offset); - if (startPebble != START_PEBBLE) { - throw new IllegalStateException( - "Does not look like data created by ObjectStreamEncoder"); + + private void internalReset() { + index = 0; + buffer.clear(); } - offset += BYTES_PER_INT; - int count = ByteArrayUtil.readInt(headerBA, offset); - offset += BYTES_PER_INT; - int endPointer = ByteArrayUtil.readInt(headerBA, offset); - offset += BYTES_PER_INT; - int checksum = ByteArrayUtil.readInt(headerBA, offset); - if (checksum != (START_PEBBLE ^ count)) { - throw new IllegalStateException("Invalid checksum"); + + E getFromBuffer() { + if (index >= buffer.size()) { + return null; + } + return buffer.get(this.index++); } - return count; - } - - @SuppressWarnings("unchecked") - E readEvents(ObjectInputStream ois) throws IOException { - E e = null; - try { - e = (E) ois.readObject(); - buffer.add(e); - } catch (ClassNotFoundException e1) { - // FIXME Auto-generated catch block - e1.printStackTrace(); + + int readHeader() throws IOException { + byte[] headerBA = new byte[4 * BYTES_PER_INT]; + // System.out.println("available="+ncis.available()); + int bytesRead = ncis.read(headerBA); + if (bytesRead == -1) { + return -1; + } + // System.out.println("**bytesRead="+bytesRead); + + // System.out.println(ByteArrayUtil.toHexString(headerBA)); + + int offset = 0; + int startPebble = ByteArrayUtil.readInt(headerBA, offset); + if (startPebble != START_PEBBLE) { + throw new IllegalStateException("Does not look like data created by ObjectStreamEncoder"); + } + offset += BYTES_PER_INT; + int count = ByteArrayUtil.readInt(headerBA, offset); + offset += BYTES_PER_INT; + int endPointer = ByteArrayUtil.readInt(headerBA, offset); + offset += BYTES_PER_INT; + int checksum = ByteArrayUtil.readInt(headerBA, offset); + if (checksum != (START_PEBBLE ^ count)) { + throw new IllegalStateException("Invalid checksum"); + } + return count; } - return e; - } - - void readFooter(int count) throws IOException { - byte[] headerBA = new byte[2 * BYTES_PER_INT]; - ncis.read(headerBA); - - int offset = 0; - int stopPebble = ByteArrayUtil.readInt(headerBA, offset); - if (stopPebble != STOP_PEBBLE) { - throw new IllegalStateException( - "Looks like a corrupt stream"); + + @SuppressWarnings("unchecked") + E readEvents(ObjectInputStream ois) throws IOException { + E e = null; + try { + e = (E) ois.readObject(); + buffer.add(e); + } catch (ClassNotFoundException e1) { + // FIXME Auto-generated catch block + e1.printStackTrace(); + } + return e; } - offset += BYTES_PER_INT; - int checksum = ByteArrayUtil.readInt(headerBA, offset); - if (checksum != (STOP_PEBBLE ^ count)) { - throw new IllegalStateException("Invalid checksum"); + + void readFooter(int count) throws IOException { + byte[] headerBA = new byte[2 * BYTES_PER_INT]; + ncis.read(headerBA); + + int offset = 0; + int stopPebble = ByteArrayUtil.readInt(headerBA, offset); + if (stopPebble != STOP_PEBBLE) { + throw new IllegalStateException("Looks like a corrupt stream"); + } + offset += BYTES_PER_INT; + int checksum = ByteArrayUtil.readInt(headerBA, offset); + if (checksum != (STOP_PEBBLE ^ count)) { + throw new IllegalStateException("Invalid checksum"); + } } - } - - void readPayload(int count) throws IOException { - List eventList = new ArrayList(count); - ObjectInputStream ois = new ObjectInputStream(ncis); - for (int i = 0; i < count; i++) { - E e = (E) readEvents(ois); - eventList.add(e); + + void readPayload(int count) throws IOException { + List eventList = new ArrayList(count); + ObjectInputStream ois = new ObjectInputStream(ncis); + for (int i = 0; i < count; i++) { + E e = (E) readEvents(ois); + eventList.add(e); + } + ois.close(); } - ois.close(); - } - public void close() throws IOException { - ncis.realClose(); - } + public void close() throws IOException { + ncis.realClose(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/LayoutWrappingEncoder.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/LayoutWrappingEncoder.java index 3f61c5194ceb715df812f9ad212354bc938fd2f2..a14b7a7ffa1662359578f23c022121b412bd11f6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/LayoutWrappingEncoder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/LayoutWrappingEncoder.java @@ -23,142 +23,138 @@ import ch.qos.logback.core.Layout; public class LayoutWrappingEncoder extends EncoderBase { - protected Layout layout; - - /** - * The charset to use when converting a String into bytes. - *

- * By default this property has the value - * null which corresponds to - * the system's default charset. - */ - private Charset charset; - - private boolean immediateFlush = true; - - - /** - * Sets the immediateFlush option. The default value for immediateFlush is 'true'. If set to true, - * the doEncode() method will immediately flush the underlying OutputStream. Although immediate flushing - * is safer, it also significantly degrades logging throughput. - * - * @since 1.0.3 - */ - public void setImmediateFlush(boolean immediateFlush) { - this.immediateFlush = immediateFlush; - } - - - public boolean isImmediateFlush() { - return immediateFlush; - } - - - public Layout getLayout() { - return layout; - } - - public void setLayout(Layout layout) { - this.layout = layout; - } - - public Charset getCharset() { - return charset; - } - - /** - * Set the charset to use when converting the string returned by the layout - * into bytes. - *

- * By default this property has the value - * null which corresponds to - * the system's default charset. - * - * @param charset - */ - public void setCharset(Charset charset) { - this.charset = charset; - } - - public void init(OutputStream os) throws IOException { - super.init(os); - writeHeader(); - } - - void writeHeader() throws IOException { - if (layout != null && (outputStream != null)) { - StringBuilder sb = new StringBuilder(); - appendIfNotNull(sb, layout.getFileHeader()); - appendIfNotNull(sb, layout.getPresentationHeader()); - if (sb.length() > 0) { - sb.append(CoreConstants.LINE_SEPARATOR); - // If at least one of file header or presentation header were not - // null, then append a line separator. - // This should be useful in most cases and should not hurt. - outputStream.write(convertToBytes(sb.toString())); - outputStream.flush(); - } - } - } - - public void close() throws IOException { - writeFooter(); - } - - void writeFooter() throws IOException { - if (layout != null && outputStream != null) { - StringBuilder sb = new StringBuilder(); - appendIfNotNull(sb, layout.getPresentationFooter()); - appendIfNotNull(sb, layout.getFileFooter()); - if (sb.length() > 0) { - outputStream.write(convertToBytes(sb.toString())); - outputStream.flush(); - } - } - } - - private byte[] convertToBytes(String s) { - if (charset == null) { - return s.getBytes(); - } else { - try { - return s.getBytes(charset.name()); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException( - "An existing charset cannot possibly be unsupported."); - } - } - } - - public void doEncode(E event) throws IOException { - String txt = layout.doLayout(event); - outputStream.write(convertToBytes(txt)); - if (immediateFlush) - outputStream.flush(); - } - - public boolean isStarted() { - return false; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - if(outputStream != null) { - try { - outputStream.flush(); - } catch (IOException e) { - } - } - } - - private void appendIfNotNull(StringBuilder sb, String s) { - if (s != null) { - sb.append(s); - } - } + protected Layout layout; + + /** + * The charset to use when converting a String into bytes. + *

+ * By default this property has the value + * null which corresponds to + * the system's default charset. + */ + private Charset charset; + + private boolean immediateFlush = true; + + /** + * Sets the immediateFlush option. The default value for immediateFlush is 'true'. If set to true, + * the doEncode() method will immediately flush the underlying OutputStream. Although immediate flushing + * is safer, it also significantly degrades logging throughput. + * + * @since 1.0.3 + */ + public void setImmediateFlush(boolean immediateFlush) { + this.immediateFlush = immediateFlush; + } + + public boolean isImmediateFlush() { + return immediateFlush; + } + + public Layout getLayout() { + return layout; + } + + public void setLayout(Layout layout) { + this.layout = layout; + } + + public Charset getCharset() { + return charset; + } + + /** + * Set the charset to use when converting the string returned by the layout + * into bytes. + *

+ * By default this property has the value + * null which corresponds to + * the system's default charset. + * + * @param charset + */ + public void setCharset(Charset charset) { + this.charset = charset; + } + + public void init(OutputStream os) throws IOException { + super.init(os); + writeHeader(); + } + + void writeHeader() throws IOException { + if (layout != null && (outputStream != null)) { + StringBuilder sb = new StringBuilder(); + appendIfNotNull(sb, layout.getFileHeader()); + appendIfNotNull(sb, layout.getPresentationHeader()); + if (sb.length() > 0) { + sb.append(CoreConstants.LINE_SEPARATOR); + // If at least one of file header or presentation header were not + // null, then append a line separator. + // This should be useful in most cases and should not hurt. + outputStream.write(convertToBytes(sb.toString())); + outputStream.flush(); + } + } + } + + public void close() throws IOException { + writeFooter(); + } + + void writeFooter() throws IOException { + if (layout != null && outputStream != null) { + StringBuilder sb = new StringBuilder(); + appendIfNotNull(sb, layout.getPresentationFooter()); + appendIfNotNull(sb, layout.getFileFooter()); + if (sb.length() > 0) { + outputStream.write(convertToBytes(sb.toString())); + outputStream.flush(); + } + } + } + + private byte[] convertToBytes(String s) { + if (charset == null) { + return s.getBytes(); + } else { + try { + return s.getBytes(charset.name()); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("An existing charset cannot possibly be unsupported."); + } + } + } + + public void doEncode(E event) throws IOException { + String txt = layout.doLayout(event); + outputStream.write(convertToBytes(txt)); + if (immediateFlush) + outputStream.flush(); + } + + public boolean isStarted() { + return false; + } + + public void start() { + started = true; + } + + public void stop() { + started = false; + if (outputStream != null) { + try { + outputStream.flush(); + } catch (IOException e) { + } + } + } + + private void appendIfNotNull(StringBuilder sb, String s) { + if (s != null) { + sb.append(s); + } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/NonClosableInputStream.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/NonClosableInputStream.java index 5ca2289ff90da67ee0b7f7c4639a58e5eee50565..daa94e74c37631c5ab9f509f0515c8b1066fd359 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/NonClosableInputStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/NonClosableInputStream.java @@ -19,20 +19,20 @@ import java.io.InputStream; public class NonClosableInputStream extends FilterInputStream { - NonClosableInputStream(InputStream is) { - super(is); - } + NonClosableInputStream(InputStream is) { + super(is); + } - /** - * The whole point of this input stream is to ignore invocations to close() - */ - @Override - public void close() { + /** + * The whole point of this input stream is to ignore invocations to close() + */ + @Override + public void close() { - } + } - public void realClose() throws IOException { - super.close(); - } + public void realClose() throws IOException { + super.close(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/encoder/ObjectStreamEncoder.java b/logback-core/src/main/java/ch/qos/logback/core/encoder/ObjectStreamEncoder.java index e73685eef781322ba38d5bc8b4f636cf8dee4ec3..905d0cc5c6ae1bfb89ba99d3d20fc2372f19cc5a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/encoder/ObjectStreamEncoder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/encoder/ObjectStreamEncoder.java @@ -31,64 +31,65 @@ import ch.qos.logback.core.CoreConstants; */ public class ObjectStreamEncoder extends EncoderBase { - static public final int START_PEBBLE = 1853421169; - static public final int STOP_PEBBLE = 640373619; + static public final int START_PEBBLE = 1853421169; + static public final int STOP_PEBBLE = 640373619; - private int MAX_BUFFER_SIZE = 100; + private int MAX_BUFFER_SIZE = 100; - List bufferList = new ArrayList(MAX_BUFFER_SIZE); + List bufferList = new ArrayList(MAX_BUFFER_SIZE); - public void doEncode(E event) throws IOException { - bufferList.add(event); - if (bufferList.size() == MAX_BUFFER_SIZE) { - writeBuffer(); + public void doEncode(E event) throws IOException { + bufferList.add(event); + if (bufferList.size() == MAX_BUFFER_SIZE) { + writeBuffer(); + } } - } - - void writeHeader(ByteArrayOutputStream baos, int bufferSize) { - ByteArrayUtil.writeInt(baos, START_PEBBLE); - ByteArrayUtil.writeInt(baos, bufferSize); - ByteArrayUtil.writeInt(baos, 0); - ByteArrayUtil.writeInt(baos, START_PEBBLE^bufferSize); - } - - void writeFooter(ByteArrayOutputStream baos, int bufferSize) { - ByteArrayUtil.writeInt(baos, STOP_PEBBLE); - ByteArrayUtil.writeInt(baos, STOP_PEBBLE ^ bufferSize); - } - void writeBuffer() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(10000); - - int size = bufferList.size(); - writeHeader(baos, size); - ObjectOutputStream oos = new ObjectOutputStream(baos); - for (E e : bufferList) { - oos.writeObject(e); + + void writeHeader(ByteArrayOutputStream baos, int bufferSize) { + ByteArrayUtil.writeInt(baos, START_PEBBLE); + ByteArrayUtil.writeInt(baos, bufferSize); + ByteArrayUtil.writeInt(baos, 0); + ByteArrayUtil.writeInt(baos, START_PEBBLE ^ bufferSize); + } + + void writeFooter(ByteArrayOutputStream baos, int bufferSize) { + ByteArrayUtil.writeInt(baos, STOP_PEBBLE); + ByteArrayUtil.writeInt(baos, STOP_PEBBLE ^ bufferSize); + } + + void writeBuffer() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(10000); + + int size = bufferList.size(); + writeHeader(baos, size); + ObjectOutputStream oos = new ObjectOutputStream(baos); + for (E e : bufferList) { + oos.writeObject(e); + } + bufferList.clear(); + oos.flush(); + + writeFooter(baos, size); + + byte[] byteArray = baos.toByteArray(); + oos.close(); + writeEndPosition(byteArray); + outputStream.write(byteArray); + + } + + void writeEndPosition(byte[] byteArray) { + int offset = 2 * CoreConstants.BYTES_PER_INT; + ByteArrayUtil.writeInt(byteArray, offset, byteArray.length - offset); + } + + @Override + public void init(OutputStream os) throws IOException { + super.init(os); + bufferList.clear(); + } + + public void close() throws IOException { + writeBuffer(); } - bufferList.clear(); - oos.flush(); - - writeFooter(baos, size); - - byte[] byteArray = baos.toByteArray(); - oos.close(); - writeEndPosition(byteArray); - outputStream.write(byteArray); - - } - - void writeEndPosition(byte[] byteArray) { - int offset = 2*CoreConstants.BYTES_PER_INT; - ByteArrayUtil.writeInt(byteArray,offset, byteArray.length-offset); - } - - @Override - public void init(OutputStream os) throws IOException { - super.init(os); - bufferList.clear(); - } - - public void close() throws IOException { - writeBuffer(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/filter/AbstractMatcherFilter.java b/logback-core/src/main/java/ch/qos/logback/core/filter/AbstractMatcherFilter.java index 744f36a7c5c4434b85b3f757f1edfd51535bb204..70e12bb58178dc7501b17b3788ada894e243efc2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/filter/AbstractMatcherFilter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/filter/AbstractMatcherFilter.java @@ -17,22 +17,22 @@ import ch.qos.logback.core.spi.FilterReply; public abstract class AbstractMatcherFilter extends Filter { - protected FilterReply onMatch = FilterReply.NEUTRAL; - protected FilterReply onMismatch = FilterReply.NEUTRAL; - - final public void setOnMatch(FilterReply reply) { - this.onMatch = reply; - } - - final public void setOnMismatch(FilterReply reply) { - this.onMismatch = reply; - } - - final public FilterReply getOnMatch() { - return onMatch; - } - - final public FilterReply getOnMismatch() { - return onMismatch; - } + protected FilterReply onMatch = FilterReply.NEUTRAL; + protected FilterReply onMismatch = FilterReply.NEUTRAL; + + final public void setOnMatch(FilterReply reply) { + this.onMatch = reply; + } + + final public void setOnMismatch(FilterReply reply) { + this.onMismatch = reply; + } + + final public FilterReply getOnMatch() { + return onMatch; + } + + final public FilterReply getOnMismatch() { + return onMismatch; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/filter/EvaluatorFilter.java b/logback-core/src/main/java/ch/qos/logback/core/filter/EvaluatorFilter.java index bc7d883bcff7ff565754fc101da664a8a54f0acb..23be4302036b1a742be61c8be64f81c52e23d850 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/filter/EvaluatorFilter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/filter/EvaluatorFilter.java @@ -36,41 +36,41 @@ import ch.qos.logback.core.spi.FilterReply; */ public class EvaluatorFilter extends AbstractMatcherFilter { - EventEvaluator evaluator; + EventEvaluator evaluator; - @Override - public void start() { - if (evaluator != null) { - super.start(); - } else { - addError("No evaluator set for filter " + this.getName()); + @Override + public void start() { + if (evaluator != null) { + super.start(); + } else { + addError("No evaluator set for filter " + this.getName()); + } } - } - public EventEvaluator getEvaluator() { - return evaluator; - } - - public void setEvaluator(EventEvaluator evaluator) { - this.evaluator = evaluator; - } + public EventEvaluator getEvaluator() { + return evaluator; + } - public FilterReply decide(E event) { - // let us not throw an exception - // see also bug #17. - if (!isStarted() || !evaluator.isStarted()) { - return FilterReply.NEUTRAL; + public void setEvaluator(EventEvaluator evaluator) { + this.evaluator = evaluator; } - try { - if (evaluator.evaluate(event)) { - return onMatch; - } else { - return onMismatch; - } - } catch (EvaluationException e) { - addError("Evaluator " + evaluator.getName() + " threw an exception", e); - return FilterReply.NEUTRAL; + + public FilterReply decide(E event) { + // let us not throw an exception + // see also bug #17. + if (!isStarted() || !evaluator.isStarted()) { + return FilterReply.NEUTRAL; + } + try { + if (evaluator.evaluate(event)) { + return onMatch; + } else { + return onMismatch; + } + } catch (EvaluationException e) { + addError("Evaluator " + evaluator.getName() + " threw an exception", e); + return FilterReply.NEUTRAL; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/filter/Filter.java b/logback-core/src/main/java/ch/qos/logback/core/filter/Filter.java index 10ce7f34ea2c85fa2169420a127cc7cea5ab0302..0303e0d24f1e85b0a8c9c838770b149474fbf0e5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/filter/Filter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/filter/Filter.java @@ -30,39 +30,39 @@ import ch.qos.logback.core.spi.LifeCycle; */ public abstract class Filter extends ContextAwareBase implements LifeCycle { - private String name; + private String name; - boolean start = false; + boolean start = false; - public void start() { - this.start = true; - } + public void start() { + this.start = true; + } - public boolean isStarted() { - return this.start; - } + public boolean isStarted() { + return this.start; + } - public void stop() { - this.start = false; - } + public void stop() { + this.start = false; + } - /** - * If the decision is {@link FilterReply#DENY}, then the event will be - * dropped. If the decision is {@link FilterReply#NEUTRAL}, then the next - * filter, if any, will be invoked. If the decision is - * {@link FilterReply#ACCEPT} then the event will be logged without - * consulting with other filters in the chain. - * - * @param event - * The event to decide upon. - */ - public abstract FilterReply decide(E event); + /** + * If the decision is {@link FilterReply#DENY}, then the event will be + * dropped. If the decision is {@link FilterReply#NEUTRAL}, then the next + * filter, if any, will be invoked. If the decision is + * {@link FilterReply#ACCEPT} then the event will be logged without + * consulting with other filters in the chain. + * + * @param event + * The event to decide upon. + */ + public abstract FilterReply decide(E event); - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/helpers/CyclicBuffer.java b/logback-core/src/main/java/ch/qos/logback/core/helpers/CyclicBuffer.java index b57f07faf2b4ed90ab8d63c8e2d386b724b67f7a..db823588268c77c37384f1370297914b85bf4198 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/helpers/CyclicBuffer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/helpers/CyclicBuffer.java @@ -26,150 +26,148 @@ import java.util.List; */ public class CyclicBuffer { - E[] ea; - int first; - int last; - int numElems; - int maxSize; - - /** - * Instantiate a new CyclicBuffer of at most maxSize events. - * - * The maxSize argument must a positive integer. - * - * @param maxSize - * The maximum number of elements in the buffer. - */ - public CyclicBuffer(int maxSize) throws IllegalArgumentException { - if (maxSize < 1) { - throw new IllegalArgumentException("The maxSize argument (" + maxSize - + ") is not a positive integer."); + E[] ea; + int first; + int last; + int numElems; + int maxSize; + + /** + * Instantiate a new CyclicBuffer of at most maxSize events. + * + * The maxSize argument must a positive integer. + * + * @param maxSize + * The maximum number of elements in the buffer. + */ + public CyclicBuffer(int maxSize) throws IllegalArgumentException { + if (maxSize < 1) { + throw new IllegalArgumentException("The maxSize argument (" + maxSize + ") is not a positive integer."); + } + init(maxSize); } - init(maxSize); - } - - public CyclicBuffer(CyclicBuffer other) { - this.maxSize = other.maxSize; - ea = (E[]) new Object[maxSize]; - System.arraycopy(other.ea, 0, this.ea, 0, maxSize); - this.last = other.last; - this.first = other.first; - this.numElems = other.numElems; - } - - @SuppressWarnings("unchecked") - private void init(int maxSize) { - this.maxSize = maxSize; - ea = (E[]) new Object[maxSize]; - first = 0; - last = 0; - numElems = 0; - } - - /** - * Clears the buffer and resets all attributes. - */ - public void clear() { - init(this.maxSize); - } - - /** - * Add an event as the last event in the buffer. - * - */ - public void add(E event) { - ea[last] = event; - if (++last == maxSize) - last = 0; - - if (numElems < maxSize) - numElems++; - else if (++first == maxSize) - first = 0; - } - - /** - * Get the ith oldest event currently in the buffer. If i - * is outside the range 0 to the number of elements currently in the buffer, - * then null is returned. - */ - public E get(int i) { - if (i < 0 || i >= numElems) - return null; - - return ea[(first + i) % maxSize]; - } - - public int getMaxSize() { - return maxSize; - } - - /** - * Get the oldest (first) element in the buffer. The oldest element is removed - * from the buffer. - */ - public E get() { - E r = null; - if (numElems > 0) { - numElems--; - r = ea[first]; - ea[first] = null; - if (++first == maxSize) + + public CyclicBuffer(CyclicBuffer other) { + this.maxSize = other.maxSize; + ea = (E[]) new Object[maxSize]; + System.arraycopy(other.ea, 0, this.ea, 0, maxSize); + this.last = other.last; + this.first = other.first; + this.numElems = other.numElems; + } + + @SuppressWarnings("unchecked") + private void init(int maxSize) { + this.maxSize = maxSize; + ea = (E[]) new Object[maxSize]; first = 0; + last = 0; + numElems = 0; } - return r; - } - - public List asList() { - List tList = new ArrayList(); - for(int i = 0; i < length(); i++) { - tList.add(get(i)); + + /** + * Clears the buffer and resets all attributes. + */ + public void clear() { + init(this.maxSize); } - return tList; - } - - /** - * Get the number of elements in the buffer. This number is guaranteed to be - * in the range 0 to maxSize (inclusive). - */ - public int length() { - return numElems; - } - - /** - * Resize the cyclic buffer to newSize. - * - * @throws IllegalArgumentException - * if newSize is negative. - */ - @SuppressWarnings("unchecked") - public void resize(int newSize) { - if (newSize < 0) { - throw new IllegalArgumentException("Negative array size [" + newSize - + "] not allowed."); + + /** + * Add an event as the last event in the buffer. + * + */ + public void add(E event) { + ea[last] = event; + if (++last == maxSize) + last = 0; + + if (numElems < maxSize) + numElems++; + else if (++first == maxSize) + first = 0; } - if (newSize == numElems) - return; // nothing to do - // - E[] temp = (E[]) new Object[newSize]; + /** + * Get the ith oldest event currently in the buffer. If i + * is outside the range 0 to the number of elements currently in the buffer, + * then null is returned. + */ + public E get(int i) { + if (i < 0 || i >= numElems) + return null; - int loopLen = newSize < numElems ? newSize : numElems; + return ea[(first + i) % maxSize]; + } - for (int i = 0; i < loopLen; i++) { - temp[i] = ea[first]; - ea[first] = null; - if (++first == numElems) - first = 0; + public int getMaxSize() { + return maxSize; } - ea = temp; - first = 0; - numElems = loopLen; - maxSize = newSize; - if (loopLen == newSize) { - last = 0; - } else { - last = loopLen; + + /** + * Get the oldest (first) element in the buffer. The oldest element is removed + * from the buffer. + */ + public E get() { + E r = null; + if (numElems > 0) { + numElems--; + r = ea[first]; + ea[first] = null; + if (++first == maxSize) + first = 0; + } + return r; + } + + public List asList() { + List tList = new ArrayList(); + for (int i = 0; i < length(); i++) { + tList.add(get(i)); + } + return tList; + } + + /** + * Get the number of elements in the buffer. This number is guaranteed to be + * in the range 0 to maxSize (inclusive). + */ + public int length() { + return numElems; + } + + /** + * Resize the cyclic buffer to newSize. + * + * @throws IllegalArgumentException + * if newSize is negative. + */ + @SuppressWarnings("unchecked") + public void resize(int newSize) { + if (newSize < 0) { + throw new IllegalArgumentException("Negative array size [" + newSize + "] not allowed."); + } + if (newSize == numElems) + return; // nothing to do + + // + E[] temp = (E[]) new Object[newSize]; + + int loopLen = newSize < numElems ? newSize : numElems; + + for (int i = 0; i < loopLen; i++) { + temp[i] = ea[first]; + ea[first] = null; + if (++first == numElems) + first = 0; + } + ea = temp; + first = 0; + numElems = loopLen; + maxSize = newSize; + if (loopLen == newSize) { + last = 0; + } else { + last = loopLen; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/helpers/NOPAppender.java b/logback-core/src/main/java/ch/qos/logback/core/helpers/NOPAppender.java index 838ff955057248a049813a93a3130c47f9d1e76c..7b519ec08930232261e3bf4bf85b6ac2c34d0c12 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/helpers/NOPAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/helpers/NOPAppender.java @@ -17,7 +17,7 @@ import ch.qos.logback.core.AppenderBase; final public class NOPAppender extends AppenderBase { - @Override - protected void append(E eventObject) { - } + @Override + protected void append(E eventObject) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/helpers/ThrowableToStringArray.java b/logback-core/src/main/java/ch/qos/logback/core/helpers/ThrowableToStringArray.java index c05f277a4f93cde05b8bf379f8abc0819962c74d..a7735a7f3f3f78a864cecfa000504ce8956fa0e7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/helpers/ThrowableToStringArray.java +++ b/logback-core/src/main/java/ch/qos/logback/core/helpers/ThrowableToStringArray.java @@ -20,67 +20,64 @@ import ch.qos.logback.core.CoreConstants; public class ThrowableToStringArray { - public static String[] convert(Throwable t) { - List strList = new LinkedList(); - extract(strList, t, null); - return strList.toArray(new String[0]); + public static String[] convert(Throwable t) { + List strList = new LinkedList(); + extract(strList, t, null); + return strList.toArray(new String[0]); - } + } - private static void extract(List strList, Throwable t, - StackTraceElement[] parentSTE) { + private static void extract(List strList, Throwable t, StackTraceElement[] parentSTE) { - StackTraceElement[] ste = t.getStackTrace(); - final int numberOfcommonFrames = findNumberOfCommonFrames(ste, parentSTE); + StackTraceElement[] ste = t.getStackTrace(); + final int numberOfcommonFrames = findNumberOfCommonFrames(ste, parentSTE); - strList.add(formatFirstLine(t, parentSTE)); - for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) { - strList.add("\tat "+ste[i].toString()); - } + strList.add(formatFirstLine(t, parentSTE)); + for (int i = 0; i < (ste.length - numberOfcommonFrames); i++) { + strList.add("\tat " + ste[i].toString()); + } - if (numberOfcommonFrames != 0) { - strList.add("\t... "+numberOfcommonFrames + " common frames omitted"); - } + if (numberOfcommonFrames != 0) { + strList.add("\t... " + numberOfcommonFrames + " common frames omitted"); + } - Throwable cause = t.getCause(); - if (cause != null) { - ThrowableToStringArray.extract(strList, cause, ste); + Throwable cause = t.getCause(); + if (cause != null) { + ThrowableToStringArray.extract(strList, cause, ste); + } } - } - private static String formatFirstLine(Throwable t, - StackTraceElement[] parentSTE) { - String prefix = ""; - if (parentSTE != null) { - prefix = CoreConstants.CAUSED_BY; - } + private static String formatFirstLine(Throwable t, StackTraceElement[] parentSTE) { + String prefix = ""; + if (parentSTE != null) { + prefix = CoreConstants.CAUSED_BY; + } - String result = prefix + t.getClass().getName(); - if (t.getMessage() != null) { - result += ": " + t.getMessage(); + String result = prefix + t.getClass().getName(); + if (t.getMessage() != null) { + result += ": " + t.getMessage(); + } + return result; } - return result; - } - private static int findNumberOfCommonFrames(StackTraceElement[] ste, - StackTraceElement[] parentSTE) { - if (parentSTE == null) { - return 0; - } + private static int findNumberOfCommonFrames(StackTraceElement[] ste, StackTraceElement[] parentSTE) { + if (parentSTE == null) { + return 0; + } - int steIndex = ste.length - 1; - int parentIndex = parentSTE.length - 1; - int count = 0; - while (steIndex >= 0 && parentIndex >= 0) { - if (ste[steIndex].equals(parentSTE[parentIndex])) { - count++; - } else { - break; - } - steIndex--; - parentIndex--; + int steIndex = ste.length - 1; + int parentIndex = parentSTE.length - 1; + int count = 0; + while (steIndex >= 0 && parentIndex >= 0) { + if (ste[steIndex].equals(parentSTE[parentIndex])) { + count++; + } else { + break; + } + steIndex--; + parentIndex--; + } + return count; } - return count; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/helpers/Transform.java b/logback-core/src/main/java/ch/qos/logback/core/helpers/Transform.java index d49ce78f34b2a640f163c0524751a0a6e873d8a8..19b584ad76a8a32b55d9a2cbfd5f2df234ddca7a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/helpers/Transform.java +++ b/logback-core/src/main/java/ch/qos/logback/core/helpers/Transform.java @@ -22,114 +22,110 @@ import java.util.regex.Pattern; * @author Michael A. McAngus */ public class Transform { - private static final String CDATA_START = ""; - private static final String CDATA_PSEUDO_END = "]]>"; - private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END - + CDATA_START; - private static final int CDATA_END_LEN = CDATA_END.length(); - private static final Pattern UNSAFE_XML_CHARS = - Pattern.compile("[\u0000-\u0008\u000b\u000c\u000e-\u001f<>&'\"]"); + private static final String CDATA_START = ""; + private static final String CDATA_PSEUDO_END = "]]>"; + private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END + CDATA_START; + private static final int CDATA_END_LEN = CDATA_END.length(); + private static final Pattern UNSAFE_XML_CHARS = Pattern.compile("[\u0000-\u0008\u000b\u000c\u000e-\u001f<>&'\"]"); - /** - * This method takes a string which may contain HTML tags (ie, <b>, - * <table>, etc) and replaces any '<','>' ... characters with - * respective predefined entity references. - * - * @param input - * The text to be converted. - */ - public static String escapeTags(final String input) { - if (input == null || input.length() == 0 || !UNSAFE_XML_CHARS.matcher(input).find()) { - return input; + /** + * This method takes a string which may contain HTML tags (ie, <b>, + * <table>, etc) and replaces any '<','>' ... characters with + * respective predefined entity references. + * + * @param input + * The text to be converted. + */ + public static String escapeTags(final String input) { + if (input == null || input.length() == 0 || !UNSAFE_XML_CHARS.matcher(input).find()) { + return input; + } + StringBuffer buf = new StringBuffer(input); + return escapeTags(buf); } - StringBuffer buf = new StringBuffer(input); - return escapeTags(buf); - } - - /** - * This method takes a StringBuilder which may contain HTML tags (ie, <b>, - * <table>, etc) and replaces any '<' and '>' characters with - * respective predefined entity references. - * @param buf StringBuffer to transform - * @return - */ - public static String escapeTags(final StringBuffer buf) { - for (int i = 0; i < buf.length(); i++) { - char ch = buf.charAt(i); - switch (ch) { - case '\t': - case '\n': - case '\r': - // These characters are below '\u0020' but are allowed: - break; - case '&': - buf.replace(i, i + 1, "&"); - break; - case '<': - buf.replace(i, i + 1, "<"); - break; - case '>': - buf.replace(i, i + 1, ">"); - break; - case '"': - buf.replace(i, i + 1, """); - break; - case '\'': - buf.replace(i, i + 1, "'"); - break; - default: - if (ch<'\u0020') { - // These characters are not allowed, - // replace them with "Object replacement character": - buf.replace(i, i + 1, "\uFFFD"); - } - break; - } + /** + * This method takes a StringBuilder which may contain HTML tags (ie, <b>, + * <table>, etc) and replaces any '<' and '>' characters with + * respective predefined entity references. + * @param buf StringBuffer to transform + * @return + */ + public static String escapeTags(final StringBuffer buf) { + for (int i = 0; i < buf.length(); i++) { + char ch = buf.charAt(i); + switch (ch) { + case '\t': + case '\n': + case '\r': + // These characters are below '\u0020' but are allowed: + break; + case '&': + buf.replace(i, i + 1, "&"); + break; + case '<': + buf.replace(i, i + 1, "<"); + break; + case '>': + buf.replace(i, i + 1, ">"); + break; + case '"': + buf.replace(i, i + 1, """); + break; + case '\'': + buf.replace(i, i + 1, "'"); + break; + default: + if (ch < '\u0020') { + // These characters are not allowed, + // replace them with "Object replacement character": + buf.replace(i, i + 1, "\uFFFD"); + } + break; + } + } + return buf.toString(); } - return buf.toString(); - } - - /** - * Ensures that embedded CDEnd strings (]]>) are handled properly within - * message, NDC and throwable tag text. - * - * @param output - * Writer. The initial CDSutart () of - * the CDATA section are the responsibility of the calling method. - * - * @param str - * The String that is inserted into an existing CDATA Section. - */ - public static void appendEscapingCDATA(StringBuilder output, String str) { - if (str == null) { - return; - } + /** + * Ensures that embedded CDEnd strings (]]>) are handled properly within + * message, NDC and throwable tag text. + * + * @param output + * Writer. The initial CDSutart () of + * the CDATA section are the responsibility of the calling method. + * + * @param str + * The String that is inserted into an existing CDATA Section. + */ + public static void appendEscapingCDATA(StringBuilder output, String str) { + if (str == null) { + return; + } - int end = str.indexOf(CDATA_END); + int end = str.indexOf(CDATA_END); - if (end < 0) { - output.append(str); + if (end < 0) { + output.append(str); - return; - } + return; + } - int start = 0; + int start = 0; - while (end > -1) { - output.append(str.substring(start, end)); - output.append(CDATA_EMBEDED_END); - start = end + CDATA_END_LEN; + while (end > -1) { + output.append(str.substring(start, end)); + output.append(CDATA_EMBEDED_END); + start = end + CDATA_END_LEN; - if (start < str.length()) { - end = str.indexOf(CDATA_END, start); - } else { - return; - } - } + if (start < str.length()) { + end = str.indexOf(CDATA_END, start); + } else { + return; + } + } - output.append(str.substring(start)); - } + output.append(str.substring(start)); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/hook/DelayingShutdownHook.java b/logback-core/src/main/java/ch/qos/logback/core/hook/DelayingShutdownHook.java index 5b6a6ddcb7246bc5ec82a6b607807f93b9e5d53b..b16b4c6e93d8851e43d59f41c1273acc9524abea 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/hook/DelayingShutdownHook.java +++ b/logback-core/src/main/java/ch/qos/logback/core/hook/DelayingShutdownHook.java @@ -24,37 +24,37 @@ import ch.qos.logback.core.util.Duration; * @author Mike Reinhold */ public class DelayingShutdownHook extends ShutdownHookBase { - /** - * The default is no delay before shutdown. - */ - public static final Duration DEFAULT_DELAY = Duration.buildByMilliseconds(0); - - /** - * The delay in milliseconds before the ShutdownHook stops the logback context - */ - private Duration delay = DEFAULT_DELAY; - - public DelayingShutdownHook() { - } + /** + * The default is no delay before shutdown. + */ + public static final Duration DEFAULT_DELAY = Duration.buildByMilliseconds(0); - public Duration getDelay() { - return delay; - } + /** + * The delay in milliseconds before the ShutdownHook stops the logback context + */ + private Duration delay = DEFAULT_DELAY; - /** - * The duration to wait before shutting down the current logback context. - * - * @param delay - */ - public void setDelay(Duration delay) { - this.delay = delay; - } + public DelayingShutdownHook() { + } + + public Duration getDelay() { + return delay; + } + + /** + * The duration to wait before shutting down the current logback context. + * + * @param delay + */ + public void setDelay(Duration delay) { + this.delay = delay; + } - public void run() { - try { - Thread.sleep(delay.getMilliseconds()); - } catch (InterruptedException e) { + public void run() { + try { + Thread.sleep(delay.getMilliseconds()); + } catch (InterruptedException e) { + } + super.stop(); } - super.stop(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHookBase.java b/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHookBase.java index f599d9249e90bbcf24ab062e796679341d11793c..2802cce81655c5cdfa3b75b9f341ad178554d956 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHookBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHookBase.java @@ -24,19 +24,19 @@ import ch.qos.logback.core.spi.ContextAwareBase; */ public abstract class ShutdownHookBase extends ContextAwareBase implements ShutdownHook { - public ShutdownHookBase() { - } + public ShutdownHookBase() { + } - /** - * Default method for stopping the Logback context - */ - protected void stop() { - addInfo("Logback context being closed via shutdown hook"); + /** + * Default method for stopping the Logback context + */ + protected void stop() { + addInfo("Logback context being closed via shutdown hook"); - Context hookContext = getContext(); - if (hookContext instanceof ContextBase) { - ContextBase context = (ContextBase) hookContext; - context.stop(); + Context hookContext = getContext(); + if (hookContext instanceof ContextBase) { + ContextBase context = (ContextBase) hookContext; + context.stop(); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/html/CssBuilder.java b/logback-core/src/main/java/ch/qos/logback/core/html/CssBuilder.java index e7a8ce44cef2f0f741f1e6ea9f999adaa1485d3c..c4fe36dc2c14e6e79a4bbd5cf1d8893665684342 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/html/CssBuilder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/html/CssBuilder.java @@ -15,6 +15,6 @@ package ch.qos.logback.core.html; public interface CssBuilder { - void addCss(StringBuilder sbuf); - + void addCss(StringBuilder sbuf); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/html/HTMLLayoutBase.java b/logback-core/src/main/java/ch/qos/logback/core/html/HTMLLayoutBase.java index 8958c00b2733b5e06689d41c02fbb7d2c8b23c87..d6631ec1b744878c90a2e0d11d29a8869715c6cb 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/html/HTMLLayoutBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/html/HTMLLayoutBase.java @@ -35,228 +35,225 @@ import ch.qos.logback.core.spi.ScanException; */ public abstract class HTMLLayoutBase extends LayoutBase { - protected String pattern; - - protected Converter head; - - protected String title = "Logback Log Messages"; - - //It is the responsibility of derived classes to set - //this variable in their constructor to a default value. - protected CssBuilder cssBuilder; - - // counter keeping track of the rows output - protected long counter = 0; - - /** - * Set the ConversionPattern option. This is the string which controls - * formatting and consists of a mix of literal content and conversion - * specifiers. - */ - public void setPattern(String conversionPattern) { - pattern = conversionPattern; - } - - /** - * Returns the value of the ConversionPattern option. - */ - public String getPattern() { - return pattern; - } - - public CssBuilder getCssBuilder() { - return cssBuilder; - } - - public void setCssBuilder(CssBuilder cssBuilder) { - this.cssBuilder = cssBuilder; - } - - /** - * Parses the pattern and creates the Converter linked list. - */ - @Override - public void start() { - int errorCount = 0; - - try { - Parser p = new Parser(pattern); - p.setContext(getContext()); - Node t = p.parse(); - this.head = p.compile(t, getEffectiveConverterMap()); - ConverterUtil.startConverters(this.head); - } catch (ScanException ex) { - addError("Incorrect pattern found", ex); - errorCount++; + protected String pattern; + + protected Converter head; + + protected String title = "Logback Log Messages"; + + // It is the responsibility of derived classes to set + // this variable in their constructor to a default value. + protected CssBuilder cssBuilder; + + // counter keeping track of the rows output + protected long counter = 0; + + /** + * Set the ConversionPattern option. This is the string which controls + * formatting and consists of a mix of literal content and conversion + * specifiers. + */ + public void setPattern(String conversionPattern) { + pattern = conversionPattern; } - if (errorCount == 0) { - super.started = true; + /** + * Returns the value of the ConversionPattern option. + */ + public String getPattern() { + return pattern; } - } - - protected abstract Map getDefaultConverterMap(); - - - /** - * Returns a map where the default converter map is merged with the map - * contained in the context. - */ - public Map getEffectiveConverterMap() { - Map effectiveMap = new HashMap(); - - // add the least specific map fist - Map defaultMap = getDefaultConverterMap(); - if (defaultMap != null) { - effectiveMap.putAll(defaultMap); + + public CssBuilder getCssBuilder() { + return cssBuilder; } - // contextMap is more specific than the default map - Context context = getContext(); - if (context != null) { - @SuppressWarnings("unchecked") - Map contextMap = (Map) context - .getObject(CoreConstants.PATTERN_RULE_REGISTRY); - if (contextMap != null) { - effectiveMap.putAll(contextMap); - } + public void setCssBuilder(CssBuilder cssBuilder) { + this.cssBuilder = cssBuilder; } - return effectiveMap; - } - - /** - * The Title option takes a String value. This option sets the - * document title of the generated HTML document. - * - *

- * Defaults to 'Logback Log Messages'. - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Returns the current value of the Title option. - */ - public String getTitle() { - return title; - } - - /** - * Returns the content type output by this layout, i.e "text/html". - */ - @Override - public String getContentType() { - return "text/html"; - } - - /** - * Returns appropriate HTML headers. - */ - @Override - public String getFileHeader() { - StringBuilder sbuf = new StringBuilder(); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - sbuf.append(" "); - sbuf.append(LINE_SEPARATOR); - sbuf.append(" "); - sbuf.append(title); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - - cssBuilder.addCss(sbuf); - - sbuf.append(LINE_SEPARATOR); - sbuf.append(" "); - sbuf.append(LINE_SEPARATOR); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - - return sbuf.toString(); - } - - public String getPresentationHeader() { - StringBuilder sbuf = new StringBuilder(); - sbuf.append("


"); - sbuf.append(LINE_SEPARATOR); - sbuf.append("

Log session start time "); - sbuf.append(new java.util.Date()); - sbuf.append("

"); - sbuf.append(LINE_SEPARATOR); - sbuf.append(LINE_SEPARATOR); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - - buildHeaderRowForTable(sbuf); - - return sbuf.toString(); - } - - - private void buildHeaderRowForTable(StringBuilder sbuf) { - Converter c = head; - String name; - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - while (c != null) { - name = computeConverterName(c); - if (name == null) { - c = c.getNext(); - continue; - } - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - c = c.getNext(); + + /** + * Parses the pattern and creates the Converter linked list. + */ + @Override + public void start() { + int errorCount = 0; + + try { + Parser p = new Parser(pattern); + p.setContext(getContext()); + Node t = p.parse(); + this.head = p.compile(t, getEffectiveConverterMap()); + ConverterUtil.startConverters(this.head); + } catch (ScanException ex) { + addError("Incorrect pattern found", ex); + errorCount++; + } + + if (errorCount == 0) { + super.started = true; + } } - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - } - - public String getPresentationFooter() { - StringBuilder sbuf = new StringBuilder(); - sbuf.append("
"); - sbuf.append(computeConverterName(c)); - sbuf.append("
"); - return sbuf.toString(); - } - - /** - * Returns the appropriate HTML footers. - */ - @Override - public String getFileFooter() { - StringBuilder sbuf = new StringBuilder(); - sbuf.append(LINE_SEPARATOR); - sbuf.append(""); - return sbuf.toString(); - } - - protected void startNewTableIfLimitReached(StringBuilder sbuf) { - if (this.counter >= CoreConstants.TABLE_ROW_LIMIT) { - counter = 0; - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - sbuf.append("

"); - sbuf.append(""); - sbuf.append(LINE_SEPARATOR); - buildHeaderRowForTable(sbuf); + + protected abstract Map getDefaultConverterMap(); + + /** + * Returns a map where the default converter map is merged with the map + * contained in the context. + */ + public Map getEffectiveConverterMap() { + Map effectiveMap = new HashMap(); + + // add the least specific map fist + Map defaultMap = getDefaultConverterMap(); + if (defaultMap != null) { + effectiveMap.putAll(defaultMap); + } + + // contextMap is more specific than the default map + Context context = getContext(); + if (context != null) { + @SuppressWarnings("unchecked") + Map contextMap = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); + if (contextMap != null) { + effectiveMap.putAll(contextMap); + } + } + return effectiveMap; + } + + /** + * The Title option takes a String value. This option sets the + * document title of the generated HTML document. + * + *

+ * Defaults to 'Logback Log Messages'. + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * Returns the current value of the Title option. + */ + public String getTitle() { + return title; + } + + /** + * Returns the content type output by this layout, i.e "text/html". + */ + @Override + public String getContentType() { + return "text/html"; } - } - - protected String computeConverterName(Converter c) { - String className = c.getClass().getSimpleName(); - int index = className.indexOf("Converter"); - if (index == -1) { - return className; - } else { - return className.substring(0, index); + + /** + * Returns appropriate HTML headers. + */ + @Override + public String getFileHeader() { + StringBuilder sbuf = new StringBuilder(); + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + sbuf.append(" "); + sbuf.append(LINE_SEPARATOR); + sbuf.append(" "); + sbuf.append(title); + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + + cssBuilder.addCss(sbuf); + + sbuf.append(LINE_SEPARATOR); + sbuf.append(" "); + sbuf.append(LINE_SEPARATOR); + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + + return sbuf.toString(); + } + + public String getPresentationHeader() { + StringBuilder sbuf = new StringBuilder(); + sbuf.append("


"); + sbuf.append(LINE_SEPARATOR); + sbuf.append("

Log session start time "); + sbuf.append(new java.util.Date()); + sbuf.append("

"); + sbuf.append(LINE_SEPARATOR); + sbuf.append(LINE_SEPARATOR); + sbuf.append("
"); + sbuf.append(LINE_SEPARATOR); + + buildHeaderRowForTable(sbuf); + + return sbuf.toString(); + } + + private void buildHeaderRowForTable(StringBuilder sbuf) { + Converter c = head; + String name; + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + while (c != null) { + name = computeConverterName(c); + if (name == null) { + c = c.getNext(); + continue; + } + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + c = c.getNext(); + } + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + } + + public String getPresentationFooter() { + StringBuilder sbuf = new StringBuilder(); + sbuf.append("
"); + sbuf.append(computeConverterName(c)); + sbuf.append("
"); + return sbuf.toString(); + } + + /** + * Returns the appropriate HTML footers. + */ + @Override + public String getFileFooter() { + StringBuilder sbuf = new StringBuilder(); + sbuf.append(LINE_SEPARATOR); + sbuf.append(""); + return sbuf.toString(); + } + + protected void startNewTableIfLimitReached(StringBuilder sbuf) { + if (this.counter >= CoreConstants.TABLE_ROW_LIMIT) { + counter = 0; + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + sbuf.append("

"); + sbuf.append(""); + sbuf.append(LINE_SEPARATOR); + buildHeaderRowForTable(sbuf); + } + } + + protected String computeConverterName(Converter c) { + String className = c.getClass().getSimpleName(); + int index = className.indexOf("Converter"); + if (index == -1) { + return className; + } else { + return className.substring(0, index); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/html/IThrowableRenderer.java b/logback-core/src/main/java/ch/qos/logback/core/html/IThrowableRenderer.java index b34e3b5958fdb4b9f12e2410364dd061aa82bc45..84dea25550674721fc69344d2f6d92f9d009ac3e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/html/IThrowableRenderer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/html/IThrowableRenderer.java @@ -13,9 +13,8 @@ */ package ch.qos.logback.core.html; - public interface IThrowableRenderer { - - void render(StringBuilder sbuf, E event); - + + void render(StringBuilder sbuf, E event); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/html/NOPThrowableRenderer.java b/logback-core/src/main/java/ch/qos/logback/core/html/NOPThrowableRenderer.java index 085f7005b9a9ddeea1a12a78252c45df3fec60e9..4987e1a911f4da0922db89953d02a52361dc6a36 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/html/NOPThrowableRenderer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/html/NOPThrowableRenderer.java @@ -15,11 +15,10 @@ package ch.qos.logback.core.html; import ch.qos.logback.core.html.IThrowableRenderer; - public class NOPThrowableRenderer implements IThrowableRenderer { - public void render(StringBuilder sbuf, Object event) { - return; - } + public void render(StringBuilder sbuf, Object event) { + return; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/GenericConfigurator.java b/logback-core/src/main/java/ch/qos/logback/core/joran/GenericConfigurator.java index d6c5462a53a8a5474c21e850c2358c02a63077a7..cf58d9627fa0af14e931f1b4a65f7952dc2bc49b 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/GenericConfigurator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/GenericConfigurator.java @@ -35,137 +35,135 @@ import static ch.qos.logback.core.CoreConstants.SAFE_JORAN_CONFIGURATION; public abstract class GenericConfigurator extends ContextAwareBase { - protected Interpreter interpreter; - - public final void doConfigure(URL url) throws JoranException { - InputStream in = null; - try { - informContextOfURLUsedForConfiguration(getContext(), url); - URLConnection urlConnection = url.openConnection(); - // per http://jira.qos.ch/browse/LBCORE-105 - // per http://jira.qos.ch/browse/LBCORE-127 - urlConnection.setUseCaches(false); - - in = urlConnection.getInputStream(); - doConfigure(in); - } catch (IOException ioe) { - String errMsg = "Could not open URL [" + url + "]."; - addError(errMsg, ioe); - throw new JoranException(errMsg, ioe); - } finally { - if (in != null) { + protected Interpreter interpreter; + + public final void doConfigure(URL url) throws JoranException { + InputStream in = null; try { - in.close(); + informContextOfURLUsedForConfiguration(getContext(), url); + URLConnection urlConnection = url.openConnection(); + // per http://jira.qos.ch/browse/LBCORE-105 + // per http://jira.qos.ch/browse/LBCORE-127 + urlConnection.setUseCaches(false); + + in = urlConnection.getInputStream(); + doConfigure(in); } catch (IOException ioe) { - String errMsg = "Could not close input stream"; - addError(errMsg, ioe); - throw new JoranException(errMsg, ioe); + String errMsg = "Could not open URL [" + url + "]."; + addError(errMsg, ioe); + throw new JoranException(errMsg, ioe); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ioe) { + String errMsg = "Could not close input stream"; + addError(errMsg, ioe); + throw new JoranException(errMsg, ioe); + } + } } - } } - } - - public final void doConfigure(String filename) throws JoranException { - doConfigure(new File(filename)); - } - - public final void doConfigure(File file) throws JoranException { - FileInputStream fis = null; - try { - informContextOfURLUsedForConfiguration(getContext(), file.toURI().toURL()); - fis = new FileInputStream(file); - doConfigure(fis); - } catch (IOException ioe) { - String errMsg = "Could not open [" + file.getPath() + "]."; - addError(errMsg, ioe); - throw new JoranException(errMsg, ioe); - } finally { - if (fis != null) { + + public final void doConfigure(String filename) throws JoranException { + doConfigure(new File(filename)); + } + + public final void doConfigure(File file) throws JoranException { + FileInputStream fis = null; try { - fis.close(); - } catch (java.io.IOException ioe) { - String errMsg = "Could not close [" + file.getName() + "]."; - addError(errMsg, ioe); - throw new JoranException(errMsg, ioe); + informContextOfURLUsedForConfiguration(getContext(), file.toURI().toURL()); + fis = new FileInputStream(file); + doConfigure(fis); + } catch (IOException ioe) { + String errMsg = "Could not open [" + file.getPath() + "]."; + addError(errMsg, ioe); + throw new JoranException(errMsg, ioe); + } finally { + if (fis != null) { + try { + fis.close(); + } catch (java.io.IOException ioe) { + String errMsg = "Could not close [" + file.getName() + "]."; + addError(errMsg, ioe); + throw new JoranException(errMsg, ioe); + } + } } - } } - } - public static void informContextOfURLUsedForConfiguration(Context context, URL url) { - ConfigurationWatchListUtil.setMainWatchURL(context, url); - } + public static void informContextOfURLUsedForConfiguration(Context context, URL url) { + ConfigurationWatchListUtil.setMainWatchURL(context, url); + } - public final void doConfigure(InputStream inputStream) throws JoranException { - doConfigure(new InputSource(inputStream)); - } + public final void doConfigure(InputStream inputStream) throws JoranException { + doConfigure(new InputSource(inputStream)); + } - protected abstract void addInstanceRules(RuleStore rs); + protected abstract void addInstanceRules(RuleStore rs); - protected abstract void addImplicitRules(Interpreter interpreter); + protected abstract void addImplicitRules(Interpreter interpreter); - protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + protected void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { - } + } - protected ElementPath initialElementPath() { - return new ElementPath(); - } + protected ElementPath initialElementPath() { + return new ElementPath(); + } - protected void buildInterpreter() { - RuleStore rs = new SimpleRuleStore(context); - addInstanceRules(rs); - this.interpreter = new Interpreter(context, rs, initialElementPath()); - InterpretationContext interpretationContext = interpreter.getInterpretationContext(); - interpretationContext.setContext(context); - addImplicitRules(interpreter); - addDefaultNestedComponentRegistryRules(interpretationContext.getDefaultNestedComponentRegistry()); - } + protected void buildInterpreter() { + RuleStore rs = new SimpleRuleStore(context); + addInstanceRules(rs); + this.interpreter = new Interpreter(context, rs, initialElementPath()); + InterpretationContext interpretationContext = interpreter.getInterpretationContext(); + interpretationContext.setContext(context); + addImplicitRules(interpreter); + addDefaultNestedComponentRegistryRules(interpretationContext.getDefaultNestedComponentRegistry()); + } + + // this is the most inner form of doConfigure whereto other doConfigure + // methods ultimately delegate + public final void doConfigure(final InputSource inputSource) throws JoranException { - // this is the most inner form of doConfigure whereto other doConfigure - // methods ultimately delegate - public final void doConfigure(final InputSource inputSource) - throws JoranException { + long threshold = System.currentTimeMillis(); + if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) { + informContextOfURLUsedForConfiguration(getContext(), null); + } + SaxEventRecorder recorder = new SaxEventRecorder(context); + recorder.recordEvents(inputSource); + doConfigure(recorder.saxEventList); + // no exceptions a this level + StatusUtil statusUtil = new StatusUtil(context); + if (statusUtil.noXMLParsingErrorsOccurred(threshold)) { + addInfo("Registering current configuration as safe fallback point"); + registerSafeConfiguration(); + } + } - long threshold = System.currentTimeMillis(); - if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) { - informContextOfURLUsedForConfiguration(getContext(), null); + public void doConfigure(final List eventList) throws JoranException { + buildInterpreter(); + // disallow simultaneous configurations of the same context + synchronized (context.getConfigurationLock()) { + interpreter.getEventPlayer().play(eventList); + } } - SaxEventRecorder recorder = new SaxEventRecorder(context); - recorder.recordEvents(inputSource); - doConfigure(recorder.saxEventList); - // no exceptions a this level - StatusUtil statusUtil = new StatusUtil(context); - if (statusUtil.noXMLParsingErrorsOccurred(threshold)) { - addInfo("Registering current configuration as safe fallback point"); - registerSafeConfiguration(); + + /** + * Register the current event list in currently in the interpreter as a safe + * configuration point. + * + * @since 0.9.30 + */ + public void registerSafeConfiguration() { + context.putObject(SAFE_JORAN_CONFIGURATION, interpreter.getEventPlayer().getCopyOfPlayerEventList()); } - } - - public void doConfigure(final List eventList) - throws JoranException { - buildInterpreter(); - // disallow simultaneous configurations of the same context - synchronized (context.getConfigurationLock()) { - interpreter.getEventPlayer().play(eventList); + + /** + * Recall the event list previously registered as a safe point. + */ + @SuppressWarnings("unchecked") + public List recallSafeConfiguration() { + return (List) context.getObject(SAFE_JORAN_CONFIGURATION); } - } - - /** - * Register the current event list in currently in the interpreter as a safe - * configuration point. - * - * @since 0.9.30 - */ - public void registerSafeConfiguration() { - context.putObject(SAFE_JORAN_CONFIGURATION, interpreter.getEventPlayer().getCopyOfPlayerEventList()); - } - - /** - * Recall the event list previously registered as a safe point. - */ - @SuppressWarnings("unchecked") - public List recallSafeConfiguration() { - return (List) context.getObject(SAFE_JORAN_CONFIGURATION); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/JoranConfiguratorBase.java b/logback-core/src/main/java/ch/qos/logback/core/joran/JoranConfiguratorBase.java index d515f62a5ca008cc6f18f01e22b935e63987b274..62867e5ef1d88ba729da2e2d7dcf8fe40fde2d5f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/JoranConfiguratorBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/JoranConfiguratorBase.java @@ -51,64 +51,58 @@ import ch.qos.logback.core.joran.spi.RuleStore; */ abstract public class JoranConfiguratorBase extends GenericConfigurator { - public List getErrorList() { - return null; - } - - @Override - protected void addInstanceRules(RuleStore rs) { - - // is "configuration/variable" referenced in the docs? - rs.addRule(new ElementSelector("configuration/variable"), new PropertyAction()); - rs.addRule(new ElementSelector("configuration/property"), new PropertyAction()); - - rs.addRule(new ElementSelector("configuration/substitutionProperty"), - new PropertyAction()); - - rs.addRule(new ElementSelector("configuration/timestamp"), new TimestampAction()); - rs.addRule(new ElementSelector("configuration/shutdownHook"), new ShutdownHookAction()); - rs.addRule(new ElementSelector("configuration/define"), new DefinePropertyAction()); - - // the contextProperty pattern is deprecated. It is undocumented - // and will be dropped in future versions of logback - rs.addRule(new ElementSelector("configuration/contextProperty"), - new ContextPropertyAction()); - - rs.addRule(new ElementSelector("configuration/conversionRule"), - new ConversionRuleAction()); - - rs.addRule(new ElementSelector("configuration/statusListener"), - new StatusListenerAction()); - - rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); - rs.addRule(new ElementSelector("configuration/appender/appender-ref"), - new AppenderRefAction()); - rs.addRule(new ElementSelector("configuration/newRule"), new NewRuleAction()); - rs.addRule(new ElementSelector("*/param"), new ParamAction()); - } - - @Override - protected void addImplicitRules(Interpreter interpreter) { - // The following line adds the capability to parse nested components - NestedComplexPropertyIA nestedComplexPropertyIA = new NestedComplexPropertyIA(); - nestedComplexPropertyIA.setContext(context); - interpreter.addImplicitAction(nestedComplexPropertyIA); - - NestedBasicPropertyIA nestedBasicIA = new NestedBasicPropertyIA(); - nestedBasicIA.setContext(context); - interpreter.addImplicitAction(nestedBasicIA); - } - - @Override - protected void buildInterpreter() { - super.buildInterpreter(); - Map omap = interpreter.getInterpretationContext() - .getObjectMap(); - omap.put(ActionConst.APPENDER_BAG, new HashMap()); - omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); - } - - public InterpretationContext getInterpretationContext() { - return interpreter.getInterpretationContext(); - } + public List getErrorList() { + return null; + } + + @Override + protected void addInstanceRules(RuleStore rs) { + + // is "configuration/variable" referenced in the docs? + rs.addRule(new ElementSelector("configuration/variable"), new PropertyAction()); + rs.addRule(new ElementSelector("configuration/property"), new PropertyAction()); + + rs.addRule(new ElementSelector("configuration/substitutionProperty"), new PropertyAction()); + + rs.addRule(new ElementSelector("configuration/timestamp"), new TimestampAction()); + rs.addRule(new ElementSelector("configuration/shutdownHook"), new ShutdownHookAction()); + rs.addRule(new ElementSelector("configuration/define"), new DefinePropertyAction()); + + // the contextProperty pattern is deprecated. It is undocumented + // and will be dropped in future versions of logback + rs.addRule(new ElementSelector("configuration/contextProperty"), new ContextPropertyAction()); + + rs.addRule(new ElementSelector("configuration/conversionRule"), new ConversionRuleAction()); + + rs.addRule(new ElementSelector("configuration/statusListener"), new StatusListenerAction()); + + rs.addRule(new ElementSelector("configuration/appender"), new AppenderAction()); + rs.addRule(new ElementSelector("configuration/appender/appender-ref"), new AppenderRefAction()); + rs.addRule(new ElementSelector("configuration/newRule"), new NewRuleAction()); + rs.addRule(new ElementSelector("*/param"), new ParamAction()); + } + + @Override + protected void addImplicitRules(Interpreter interpreter) { + // The following line adds the capability to parse nested components + NestedComplexPropertyIA nestedComplexPropertyIA = new NestedComplexPropertyIA(); + nestedComplexPropertyIA.setContext(context); + interpreter.addImplicitAction(nestedComplexPropertyIA); + + NestedBasicPropertyIA nestedBasicIA = new NestedBasicPropertyIA(); + nestedBasicIA.setContext(context); + interpreter.addImplicitAction(nestedBasicIA); + } + + @Override + protected void buildInterpreter() { + super.buildInterpreter(); + Map omap = interpreter.getInterpretationContext().getObjectMap(); + omap.put(ActionConst.APPENDER_BAG, new HashMap()); + omap.put(ActionConst.FILTER_CHAIN_BAG, new HashMap()); + } + + public InterpretationContext getInterpretationContext() { + return interpreter.getInterpretationContext(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AbstractEventEvaluatorAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AbstractEventEvaluatorAction.java index f9f803230e40398a9c5886a1162594e09c6a2107..c4acd006f788b2ef465e24815381bddbffe576f7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AbstractEventEvaluatorAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AbstractEventEvaluatorAction.java @@ -25,98 +25,93 @@ import ch.qos.logback.core.util.OptionHelper; abstract public class AbstractEventEvaluatorAction extends Action { - EventEvaluator evaluator; - boolean inError = false; - - /** - * Instantiates an evaluator of the given class and sets its name. - */ - public void begin(InterpretationContext ec, String name, Attributes attributes) { - // Let us forget about previous errors (in this instance) - inError = false; - evaluator = null; - - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - className = defaultClassName(); - addInfo("Assuming default evaluator class [" + className + "]"); - } + EventEvaluator evaluator; + boolean inError = false; + + /** + * Instantiates an evaluator of the given class and sets its name. + */ + public void begin(InterpretationContext ec, String name, Attributes attributes) { + // Let us forget about previous errors (in this instance) + inError = false; + evaluator = null; + + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + className = defaultClassName(); + addInfo("Assuming default evaluator class [" + className + "]"); + } - if (OptionHelper.isEmpty(className)) { - className = defaultClassName(); - inError = true; - addError("Mandatory \"" + CLASS_ATTRIBUTE - + "\" attribute not set for "); - return; - } + if (OptionHelper.isEmpty(className)) { + className = defaultClassName(); + inError = true; + addError("Mandatory \"" + CLASS_ATTRIBUTE + "\" attribute not set for "); + return; + } - String evaluatorName = attributes.getValue(Action.NAME_ATTRIBUTE); - if (OptionHelper.isEmpty(evaluatorName)) { - inError = true; - addError("Mandatory \"" + NAME_ATTRIBUTE - + "\" attribute not set for "); - return; - } - try { - evaluator = (EventEvaluator) OptionHelper.instantiateByClassName( - className, ch.qos.logback.core.boolex.EventEvaluator.class, context); + String evaluatorName = attributes.getValue(Action.NAME_ATTRIBUTE); + if (OptionHelper.isEmpty(evaluatorName)) { + inError = true; + addError("Mandatory \"" + NAME_ATTRIBUTE + "\" attribute not set for "); + return; + } + try { + evaluator = (EventEvaluator) OptionHelper.instantiateByClassName(className, ch.qos.logback.core.boolex.EventEvaluator.class, context); - evaluator.setContext(this.context); - evaluator.setName(evaluatorName); + evaluator.setContext(this.context); + evaluator.setName(evaluatorName); - ec.pushObject(evaluator); - addInfo("Adding evaluator named [" + evaluatorName - + "] to the object stack"); + ec.pushObject(evaluator); + addInfo("Adding evaluator named [" + evaluatorName + "] to the object stack"); - } catch (Exception oops) { - inError = true; - addError("Could not create evaluator of type " + className + "].", oops); - } - } - - /** - * Returns a default class name in case the class attribute is not specified - * - * @return - */ - abstract protected String defaultClassName(); - - /** - * Once the children elements are also parsed, now is the time to activate the - * evaluator options. - */ - @SuppressWarnings("unchecked") - public void end(InterpretationContext ec, String e) { - if (inError) { - return; + } catch (Exception oops) { + inError = true; + addError("Could not create evaluator of type " + className + "].", oops); + } } - if (evaluator instanceof LifeCycle) { - ((LifeCycle) evaluator).start(); - addInfo("Starting evaluator named [" + evaluator.getName() + "]"); - } + /** + * Returns a default class name in case the class attribute is not specified + * + * @return + */ + abstract protected String defaultClassName(); + + /** + * Once the children elements are also parsed, now is the time to activate the + * evaluator options. + */ + @SuppressWarnings("unchecked") + public void end(InterpretationContext ec, String e) { + if (inError) { + return; + } - Object o = ec.peekObject(); + if (evaluator instanceof LifeCycle) { + ((LifeCycle) evaluator).start(); + addInfo("Starting evaluator named [" + evaluator.getName() + "]"); + } - if (o != evaluator) { - addWarn("The object on the top the of the stack is not the evaluator pushed earlier."); - } else { - ec.popObject(); + Object o = ec.peekObject(); - try { - Map> evaluatorMap = (Map>) context - .getObject(CoreConstants.EVALUATOR_MAP); - if(evaluatorMap == null) { - addError("Could not find EvaluatorMap"); + if (o != evaluator) { + addWarn("The object on the top the of the stack is not the evaluator pushed earlier."); } else { - evaluatorMap.put(evaluator.getName(), evaluator); + ec.popObject(); + + try { + Map> evaluatorMap = (Map>) context.getObject(CoreConstants.EVALUATOR_MAP); + if (evaluatorMap == null) { + addError("Could not find EvaluatorMap"); + } else { + evaluatorMap.put(evaluator.getName(), evaluator); + } + } catch (Exception ex) { + addError("Could not set evaluator named [" + evaluator + "].", ex); + } } - } catch (Exception ex) { - addError("Could not set evaluator named [" + evaluator + "].", ex); - } } - } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/Action.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/Action.java index 693607075884cd3f6f0d3ceda1423ad59b8428c1..a05db9282b5c51628ea8c58064731bc64d6b5cb9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/Action.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/Action.java @@ -37,66 +37,61 @@ import ch.qos.logback.core.spi.ContextAwareBase; */ public abstract class Action extends ContextAwareBase { - public static final String NAME_ATTRIBUTE = "name"; - public static final String KEY_ATTRIBUTE = "key"; - public static final String VALUE_ATTRIBUTE = "value"; - public static final String FILE_ATTRIBUTE = "file"; - public static final String CLASS_ATTRIBUTE = "class"; - public static final String PATTERN_ATTRIBUTE = "pattern"; - public static final String SCOPE_ATTRIBUTE = "scope"; + public static final String NAME_ATTRIBUTE = "name"; + public static final String KEY_ATTRIBUTE = "key"; + public static final String VALUE_ATTRIBUTE = "value"; + public static final String FILE_ATTRIBUTE = "file"; + public static final String CLASS_ATTRIBUTE = "class"; + public static final String PATTERN_ATTRIBUTE = "pattern"; + public static final String SCOPE_ATTRIBUTE = "scope"; + public static final String ACTION_CLASS_ATTRIBUTE = "actionClass"; - public static final String ACTION_CLASS_ATTRIBUTE = "actionClass"; + /** + * Called when the parser encounters an element matching a + * {@link ch.qos.logback.core.joran.spi.ElementSelector Pattern}. + */ + public abstract void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException; - /** - * Called when the parser encounters an element matching a - * {@link ch.qos.logback.core.joran.spi.ElementSelector Pattern}. - */ - public abstract void begin(InterpretationContext ic, String name, - Attributes attributes) throws ActionException; - - /** - * Called to pass the body (as text) contained within an element. - * @param ic - * @param body - * @throws ActionException - */ - public void body(InterpretationContext ic, String body) - throws ActionException { - // NOP - } + /** + * Called to pass the body (as text) contained within an element. + * @param ic + * @param body + * @throws ActionException + */ + public void body(InterpretationContext ic, String body) throws ActionException { + // NOP + } - /* - * Called when the parser encounters an endElement event matching a - * {@link ch.qos.logback.core.joran.spi.Pattern Pattern}. - */ - public abstract void end(InterpretationContext ic, String name) - throws ActionException; + /* + * Called when the parser encounters an endElement event matching a {@link ch.qos.logback.core.joran.spi.Pattern + * Pattern}. + */ + public abstract void end(InterpretationContext ic, String name) throws ActionException; - public String toString() { - return this.getClass().getName(); - } + public String toString() { + return this.getClass().getName(); + } - protected int getColumnNumber(InterpretationContext ic) { - Interpreter ji = ic.getJoranInterpreter(); - Locator locator = ji.getLocator(); - if (locator != null) { - return locator.getColumnNumber(); + protected int getColumnNumber(InterpretationContext ic) { + Interpreter ji = ic.getJoranInterpreter(); + Locator locator = ji.getLocator(); + if (locator != null) { + return locator.getColumnNumber(); + } + return -1; } - return -1; - } - protected int getLineNumber(InterpretationContext ic) { - Interpreter ji = ic.getJoranInterpreter(); - Locator locator = ji.getLocator(); - if (locator != null) { - return locator.getLineNumber(); + protected int getLineNumber(InterpretationContext ic) { + Interpreter ji = ic.getJoranInterpreter(); + Locator locator = ji.getLocator(); + if (locator != null) { + return locator.getLineNumber(); + } + return -1; } - return -1; - } - protected String getLineColStr(InterpretationContext ic) { - return "line: " + getLineNumber(ic) + ", column: " - + getColumnNumber(ic); - } + protected String getLineColStr(InterpretationContext ic) { + return "line: " + getLineNumber(ic) + ", column: " + getColumnNumber(ic); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionConst.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionConst.java index bc67e898b1f773fb873f841e9f6383a2d1b259ee..37934b7780007901c15202883d4129752550f9a3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionConst.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionConst.java @@ -21,21 +21,21 @@ package ch.qos.logback.core.joran.action; * */ public abstract class ActionConst { - - public static final String APPENDER_TAG = "appender"; - public static final String REF_ATTRIBUTE = "ref"; - public static final String ADDITIVITY_ATTRIBUTE = "additivity"; - public static final String LEVEL_ATTRIBUTE = "level"; - public static final String CONVERTER_CLASS_ATTRIBUTE = "converterClass"; - public static final String CONVERSION_WORD_ATTRIBUTE = "conversionWord"; - public static final String PATTERN_ATTRIBUTE = "pattern"; - public static final String VALUE_ATTR = "value"; - public static final String ACTION_CLASS_ATTRIBUTE = "actionClass"; - public static final String INHERITED = "INHERITED"; - public static final String NULL = "NULL"; - static final Class[] ONE_STRING_PARAM = new Class[] { String.class }; + public static final String APPENDER_TAG = "appender"; + public static final String REF_ATTRIBUTE = "ref"; + public static final String ADDITIVITY_ATTRIBUTE = "additivity"; + public static final String LEVEL_ATTRIBUTE = "level"; + public static final String CONVERTER_CLASS_ATTRIBUTE = "converterClass"; + public static final String CONVERSION_WORD_ATTRIBUTE = "conversionWord"; + public static final String PATTERN_ATTRIBUTE = "pattern"; + public static final String VALUE_ATTR = "value"; + public static final String ACTION_CLASS_ATTRIBUTE = "actionClass"; - public static final String APPENDER_BAG = "APPENDER_BAG"; - public static final String FILTER_CHAIN_BAG = "FILTER_CHAIN_BAG"; + public static final String INHERITED = "INHERITED"; + public static final String NULL = "NULL"; + static final Class[] ONE_STRING_PARAM = new Class[] { String.class }; + + public static final String APPENDER_BAG = "APPENDER_BAG"; + public static final String FILTER_CHAIN_BAG = "FILTER_CHAIN_BAG"; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionUtil.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionUtil.java index 4193699d7cdac6477f275f8bf539d7fdd8d66fd1..0616002b0bee8539bf479551cfa6244b1f2a8940 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ActionUtil.java @@ -21,54 +21,53 @@ import ch.qos.logback.core.util.OptionHelper; public class ActionUtil { - public enum Scope { - LOCAL, CONTEXT, SYSTEM - }; + public enum Scope { + LOCAL, CONTEXT, SYSTEM + }; - /** - * Convert a string into a scope. Scole.LOCAL is returned by default. - * @param scopeStr - * @return a scope corresponding to the input string; Scope.LOCAL by default. - */ - static public Scope stringToScope(String scopeStr) { - if(Scope.SYSTEM.toString().equalsIgnoreCase(scopeStr)) - return Scope.SYSTEM; - if(Scope.CONTEXT.toString().equalsIgnoreCase(scopeStr)) - return Scope.CONTEXT; + /** + * Convert a string into a scope. Scole.LOCAL is returned by default. + * @param scopeStr + * @return a scope corresponding to the input string; Scope.LOCAL by default. + */ + static public Scope stringToScope(String scopeStr) { + if (Scope.SYSTEM.toString().equalsIgnoreCase(scopeStr)) + return Scope.SYSTEM; + if (Scope.CONTEXT.toString().equalsIgnoreCase(scopeStr)) + return Scope.CONTEXT; - return Scope.LOCAL; - } + return Scope.LOCAL; + } - static public void setProperty(InterpretationContext ic, String key, String value, Scope scope) { - switch (scope) { - case LOCAL: - ic.addSubstitutionProperty(key, value); - break; - case CONTEXT: - ic.getContext().putProperty(key, value); - break; - case SYSTEM: - OptionHelper.setSystemProperty(ic, key, value); + static public void setProperty(InterpretationContext ic, String key, String value, Scope scope) { + switch (scope) { + case LOCAL: + ic.addSubstitutionProperty(key, value); + break; + case CONTEXT: + ic.getContext().putProperty(key, value); + break; + case SYSTEM: + OptionHelper.setSystemProperty(ic, key, value); + } } - } - /** - * Add all the properties found in the argument named 'props' to an - * InterpretationContext. - */ - static public void setProperties(InterpretationContext ic, Properties props, - Scope scope) { - switch (scope) { - case LOCAL: - ic.addSubstitutionProperties(props); - break; - case CONTEXT: - ContextUtil cu = new ContextUtil(ic.getContext()); - cu.addProperties(props); - break; - case SYSTEM: - OptionHelper.setSystemProperties(ic, props); + /** + * Add all the properties found in the argument named 'props' to an + * InterpretationContext. + */ + static public void setProperties(InterpretationContext ic, Properties props, Scope scope) { + switch (scope) { + case LOCAL: + ic.addSubstitutionProperties(props); + break; + case CONTEXT: + ContextUtil cu = new ContextUtil(ic.getContext()); + cu.addProperties(props); + break; + case SYSTEM: + OptionHelper.setSystemProperties(ic, props); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderAction.java index 67e1587a21a00d29328d6afae716a72c5914059c..df7524943ac930f34ffe7f1307650591af971896 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderAction.java @@ -24,85 +24,78 @@ import ch.qos.logback.core.spi.LifeCycle; import ch.qos.logback.core.util.OptionHelper; public class AppenderAction extends Action { - Appender appender; - private boolean inError = false; - - /** - * Instantiates an appender of the given class and sets its name. - * - * The appender thus generated is placed in the {@link InterpretationContext}'s - * appender bag. - */ - @SuppressWarnings("unchecked") - public void begin(InterpretationContext ec, String localName, - Attributes attributes) throws ActionException { - // We are just beginning, reset variables - appender = null; - inError = false; - - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Missing class name for appender. Near [" + localName - + "] line " + getLineNumber(ec)); - inError = true; - return; + Appender appender; + private boolean inError = false; + + /** + * Instantiates an appender of the given class and sets its name. + * + * The appender thus generated is placed in the {@link InterpretationContext}'s + * appender bag. + */ + @SuppressWarnings("unchecked") + public void begin(InterpretationContext ec, String localName, Attributes attributes) throws ActionException { + // We are just beginning, reset variables + appender = null; + inError = false; + + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Missing class name for appender. Near [" + localName + "] line " + getLineNumber(ec)); + inError = true; + return; + } + + try { + addInfo("About to instantiate appender of type [" + className + "]"); + + appender = (Appender) OptionHelper.instantiateByClassName(className, ch.qos.logback.core.Appender.class, context); + + appender.setContext(context); + + String appenderName = ec.subst(attributes.getValue(NAME_ATTRIBUTE)); + + if (OptionHelper.isEmpty(appenderName)) { + addWarn("No appender name given for appender of type " + className + "]."); + } else { + appender.setName(appenderName); + addInfo("Naming appender as [" + appenderName + "]"); + } + + // The execution context contains a bag which contains the appenders + // created thus far. + HashMap> appenderBag = (HashMap>) ec.getObjectMap().get(ActionConst.APPENDER_BAG); + + // add the appender just created to the appender bag. + appenderBag.put(appenderName, appender); + + ec.pushObject(appender); + } catch (Exception oops) { + inError = true; + addError("Could not create an Appender of type [" + className + "].", oops); + throw new ActionException(oops); + } } - try { - addInfo("About to instantiate appender of type [" + className + "]"); - - appender = (Appender) OptionHelper.instantiateByClassName(className, - ch.qos.logback.core.Appender.class, context); - - appender.setContext(context); - - String appenderName = ec.subst(attributes.getValue(NAME_ATTRIBUTE)); - - if (OptionHelper.isEmpty(appenderName)) { - addWarn("No appender name given for appender of type " + className - + "]."); - } else { - appender.setName(appenderName); - addInfo("Naming appender as [" + appenderName + "]"); - } - - // The execution context contains a bag which contains the appenders - // created thus far. - HashMap> appenderBag = (HashMap>) ec.getObjectMap().get( - ActionConst.APPENDER_BAG); - - // add the appender just created to the appender bag. - appenderBag.put(appenderName, appender); - - ec.pushObject(appender); - } catch (Exception oops) { - inError = true; - addError("Could not create an Appender of type [" + className + "].", - oops); - throw new ActionException(oops); - } - } - - /** - * Once the children elements are also parsed, now is the time to activate the - * appender options. - */ - public void end(InterpretationContext ec, String name) { - if (inError) { - return; - } - - if (appender instanceof LifeCycle) { - ((LifeCycle) appender).start(); - } - - Object o = ec.peekObject(); - - if (o != appender) { - addWarn("The object at the of the stack is not the appender named [" - + appender.getName() + "] pushed earlier."); - } else { - ec.popObject(); + /** + * Once the children elements are also parsed, now is the time to activate the + * appender options. + */ + public void end(InterpretationContext ec, String name) { + if (inError) { + return; + } + + if (appender instanceof LifeCycle) { + ((LifeCycle) appender).start(); + } + + Object o = ec.peekObject(); + + if (o != appender) { + addWarn("The object at the of the stack is not the appender named [" + appender.getName() + "] pushed earlier."); + } else { + ec.popObject(); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderRefAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderRefAction.java index 529ebebe71c85fcfd280acacfb775077c799f7a9..cde4652820811d872c78903ca5cd7b3585d64896 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderRefAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/AppenderRefAction.java @@ -21,62 +21,56 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.spi.AppenderAttachable; import ch.qos.logback.core.util.OptionHelper; - import java.util.HashMap; public class AppenderRefAction extends Action { - boolean inError = false; + boolean inError = false; - @SuppressWarnings("unchecked") - public void begin(InterpretationContext ec, String tagName, Attributes attributes) { - // Let us forget about previous errors (in this object) - inError = false; + @SuppressWarnings("unchecked") + public void begin(InterpretationContext ec, String tagName, Attributes attributes) { + // Let us forget about previous errors (in this object) + inError = false; - // logger.debug("begin called"); + // logger.debug("begin called"); - Object o = ec.peekObject(); + Object o = ec.peekObject(); - if (!(o instanceof AppenderAttachable)) { - String errMsg = "Could not find an AppenderAttachable at the top of execution stack. Near [" - + tagName + "] line " + getLineNumber(ec); - inError = true; - addError(errMsg); - return; - } + if (!(o instanceof AppenderAttachable)) { + String errMsg = "Could not find an AppenderAttachable at the top of execution stack. Near [" + tagName + "] line " + getLineNumber(ec); + inError = true; + addError(errMsg); + return; + } - AppenderAttachable appenderAttachable = (AppenderAttachable) o; + AppenderAttachable appenderAttachable = (AppenderAttachable) o; - String appenderName = ec.subst(attributes.getValue(ActionConst.REF_ATTRIBUTE)); + String appenderName = ec.subst(attributes.getValue(ActionConst.REF_ATTRIBUTE)); - if (OptionHelper.isEmpty(appenderName)) { - // print a meaningful error message and return - String errMsg = "Missing appender ref attribute in tag."; - inError = true; - addError(errMsg); + if (OptionHelper.isEmpty(appenderName)) { + // print a meaningful error message and return + String errMsg = "Missing appender ref attribute in tag."; + inError = true; + addError(errMsg); - return; - } + return; + } - HashMap> appenderBag = (HashMap>) ec.getObjectMap().get( - ActionConst.APPENDER_BAG); - Appender appender = (Appender) appenderBag.get(appenderName); - - if (appender == null) { - String msg = "Could not find an appender named [" + appenderName - + "]. Did you define it below instead of above in the configuration file?"; - inError = true; - addError(msg); - addError("See " + CoreConstants.CODES_URL - + "#appender_order for more details."); - return; - } + HashMap> appenderBag = (HashMap>) ec.getObjectMap().get(ActionConst.APPENDER_BAG); + Appender appender = (Appender) appenderBag.get(appenderName); - addInfo("Attaching appender named [" + appenderName + "] to " - + appenderAttachable); - appenderAttachable.addAppender(appender); - } + if (appender == null) { + String msg = "Could not find an appender named [" + appenderName + "]. Did you define it below instead of above in the configuration file?"; + inError = true; + addError(msg); + addError("See " + CoreConstants.CODES_URL + "#appender_order for more details."); + return; + } - public void end(InterpretationContext ec, String n) { - } + addInfo("Attaching appender named [" + appenderName + "] to " + appenderAttachable); + appenderAttachable.addAppender(appender); + } + + public void end(InterpretationContext ec, String n) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ContextPropertyAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ContextPropertyAction.java index 526c1261e14a7016c2fb5fdf3111c38dcf0c2ce0..c4f8295ddbb3498da0a2df3a8d7503545add9ab3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ContextPropertyAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ContextPropertyAction.java @@ -23,14 +23,13 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; */ public class ContextPropertyAction extends Action { - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - addError("The [contextProperty] element has been removed. Please use [substitutionProperty] element instead"); - } + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + addError("The [contextProperty] element has been removed. Please use [substitutionProperty] element instead"); + } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - } + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ConversionRuleAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ConversionRuleAction.java index ad8f45b3fe393b9baa1452caa8e2618e35e6e574..fba451c830b423aac4e4fd4f4257a34b2eceb05f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ConversionRuleAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ConversionRuleAction.java @@ -16,72 +16,67 @@ package ch.qos.logback.core.joran.action; import java.util.HashMap; import java.util.Map; - import org.xml.sax.Attributes; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.OptionHelper; +public class ConversionRuleAction extends Action { + boolean inError = false; + /** + * Instantiates an layout of the given class and sets its name. + * + */ + @SuppressWarnings("unchecked") + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + // Let us forget about previous errors (in this object) + inError = false; -public class ConversionRuleAction extends Action { - boolean inError = false; - - /** - * Instantiates an layout of the given class and sets its name. - * - */ - @SuppressWarnings("unchecked") - public void begin(InterpretationContext ec, String localName, Attributes attributes) { - // Let us forget about previous errors (in this object) - inError = false; + String errorMsg; + String conversionWord = attributes.getValue(ActionConst.CONVERSION_WORD_ATTRIBUTE); + String converterClass = attributes.getValue(ActionConst.CONVERTER_CLASS_ATTRIBUTE); - String errorMsg; - String conversionWord = - attributes.getValue(ActionConst.CONVERSION_WORD_ATTRIBUTE); - String converterClass = - attributes.getValue(ActionConst.CONVERTER_CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(conversionWord)) { + inError = true; + errorMsg = "No 'conversionWord' attribute in "; + addError(errorMsg); - if (OptionHelper.isEmpty(conversionWord)) { - inError = true; - errorMsg = "No 'conversionWord' attribute in "; - addError(errorMsg); + return; + } - return; - } + if (OptionHelper.isEmpty(converterClass)) { + inError = true; + errorMsg = "No 'converterClass' attribute in "; + ec.addError(errorMsg); - if (OptionHelper.isEmpty(converterClass)) { - inError = true; - errorMsg = "No 'converterClass' attribute in "; - ec.addError(errorMsg); + return; + } - return; + try { + Map ruleRegistry = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); + if (ruleRegistry == null) { + ruleRegistry = new HashMap(); + context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry); + } + // put the new rule into the rule registry + addInfo("registering conversion word " + conversionWord + " with class [" + converterClass + "]"); + ruleRegistry.put(conversionWord, converterClass); + } catch (Exception oops) { + inError = true; + errorMsg = "Could not add conversion rule to PatternLayout."; + addError(errorMsg); + } } - try { - Map ruleRegistry = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); - if(ruleRegistry == null) { - ruleRegistry = new HashMap(); - context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry); - } - // put the new rule into the rule registry - addInfo("registering conversion word "+conversionWord+" with class ["+converterClass+"]"); - ruleRegistry.put(conversionWord, converterClass); - } catch (Exception oops) { - inError = true; - errorMsg = "Could not add conversion rule to PatternLayout."; - addError(errorMsg); + /** + * Once the children elements are also parsed, now is the time to activate + * the appender options. + */ + public void end(InterpretationContext ec, String n) { } - } - - /** - * Once the children elements are also parsed, now is the time to activate - * the appender options. - */ - public void end(InterpretationContext ec, String n) { - } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/DefinePropertyAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/DefinePropertyAction.java index ff78b39d72238cde70920ab72c6722588a1ac268..46c4c375fe8946803aee4a4fc6f66172d6850701 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/DefinePropertyAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/DefinePropertyAction.java @@ -30,85 +30,77 @@ import org.xml.sax.Attributes; */ public class DefinePropertyAction extends Action { - String scopeStr; - Scope scope; - String propertyName; - PropertyDefiner definer; - boolean inError; + String scopeStr; + Scope scope; + String propertyName; + PropertyDefiner definer; + boolean inError; - public void begin(InterpretationContext ec, String localName, - Attributes attributes) throws ActionException { - // reset variables - scopeStr = null; - scope = null; - propertyName = null; - definer = null; - inError = false; - - // read future property name - propertyName = attributes.getValue(NAME_ATTRIBUTE); - scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); - - scope = ActionUtil.stringToScope(scopeStr); - if (OptionHelper.isEmpty(propertyName)) { - addError("Missing property name for property definer. Near [" + localName - + "] line " + getLineNumber(ec)); - inError = true; - return; - } + public void begin(InterpretationContext ec, String localName, Attributes attributes) throws ActionException { + // reset variables + scopeStr = null; + scope = null; + propertyName = null; + definer = null; + inError = false; - // read property definer class name - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Missing class name for property definer. Near [" + localName - + "] line " + getLineNumber(ec)); - inError = true; - return; - } + // read future property name + propertyName = attributes.getValue(NAME_ATTRIBUTE); + scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); - // try to instantiate property definer - try { - addInfo("About to instantiate property definer of type [" + className - + "]"); - definer = (PropertyDefiner) OptionHelper.instantiateByClassName( - className, PropertyDefiner.class, context); - definer.setContext(context); - if(definer instanceof LifeCycle) { - ((LifeCycle) definer).start(); - } - ec.pushObject(definer); - } catch (Exception oops) { - inError = true; - addError("Could not create an PropertyDefiner of type [" + className - + "].", oops); - throw new ActionException(oops); - } - } + scope = ActionUtil.stringToScope(scopeStr); + if (OptionHelper.isEmpty(propertyName)) { + addError("Missing property name for property definer. Near [" + localName + "] line " + getLineNumber(ec)); + inError = true; + return; + } - /** - * Now property definer is initialized by all properties and we can put - * property value to context - */ - public void end(InterpretationContext ec, String name) { - if (inError) { - return; + // read property definer class name + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Missing class name for property definer. Near [" + localName + "] line " + getLineNumber(ec)); + inError = true; + return; + } + + // try to instantiate property definer + try { + addInfo("About to instantiate property definer of type [" + className + "]"); + definer = (PropertyDefiner) OptionHelper.instantiateByClassName(className, PropertyDefiner.class, context); + definer.setContext(context); + if (definer instanceof LifeCycle) { + ((LifeCycle) definer).start(); + } + ec.pushObject(definer); + } catch (Exception oops) { + inError = true; + addError("Could not create an PropertyDefiner of type [" + className + "].", oops); + throw new ActionException(oops); + } } - Object o = ec.peekObject(); + /** + * Now property definer is initialized by all properties and we can put + * property value to context + */ + public void end(InterpretationContext ec, String name) { + if (inError) { + return; + } + + Object o = ec.peekObject(); - if (o != definer) { - addWarn("The object at the of the stack is not the property definer for property named [" - + propertyName + "] pushed earlier."); - } else { - addInfo("Popping property definer for property named [" + propertyName - + "] from the object stack"); - ec.popObject(); - // let's put defined property and value to context but only if it is - // not null - String propertyValue = definer.getPropertyValue(); - if(propertyValue != null) { - ActionUtil.setProperty(ec, propertyName, propertyValue, scope); - } + if (o != definer) { + addWarn("The object at the of the stack is not the property definer for property named [" + propertyName + "] pushed earlier."); + } else { + addInfo("Popping property definer for property named [" + propertyName + "] from the object stack"); + ec.popObject(); + // let's put defined property and value to context but only if it is + // not null + String propertyValue = definer.getPropertyValue(); + if (propertyValue != null) { + ActionUtil.setProperty(ec, propertyName, propertyValue, scope); + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForBasicProperty.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForBasicProperty.java index 4621fb0386a006506f05ecfc52bc9cad12c8ddae..697227c22db3acec58aaad2d6bb71a7b34e219ef 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForBasicProperty.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForBasicProperty.java @@ -22,14 +22,14 @@ import ch.qos.logback.core.util.AggregationType; * @author Ceki Gulcu */ class IADataForBasicProperty { - final PropertySetter parentBean; - final AggregationType aggregationType; - final String propertyName; - boolean inError; + final PropertySetter parentBean; + final AggregationType aggregationType; + final String propertyName; + boolean inError; - IADataForBasicProperty(PropertySetter parentBean, AggregationType aggregationType, String propertyName) { - this.parentBean = parentBean; - this.aggregationType = aggregationType; - this.propertyName = propertyName; - } + IADataForBasicProperty(PropertySetter parentBean, AggregationType aggregationType, String propertyName) { + this.parentBean = parentBean; + this.aggregationType = aggregationType; + this.propertyName = propertyName; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForComplexProperty.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForComplexProperty.java index 9f5420848f5f13af4bedc24196a69ba7fb887e7d..ca346d5c48dd8010dc95d32563d2db3059b3f757 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForComplexProperty.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IADataForComplexProperty.java @@ -22,33 +22,32 @@ import ch.qos.logback.core.util.AggregationType; * @author Ceki */ public class IADataForComplexProperty { - final PropertySetter parentBean; - final AggregationType aggregationType; - final String complexPropertyName; - private Object nestedComplexProperty; - boolean inError; - - public IADataForComplexProperty(PropertySetter parentBean, AggregationType aggregationType, String complexPropertyName) { - this.parentBean = parentBean; - this.aggregationType = aggregationType; - this.complexPropertyName = complexPropertyName; - } - - public AggregationType getAggregationType() { - return aggregationType; - } - - public Object getNestedComplexProperty() { - return nestedComplexProperty; - } - - public String getComplexPropertyName() { - return complexPropertyName; - } - - public void setNestedComplexProperty(Object nestedComplexProperty) { - this.nestedComplexProperty = nestedComplexProperty; - } - - + final PropertySetter parentBean; + final AggregationType aggregationType; + final String complexPropertyName; + private Object nestedComplexProperty; + boolean inError; + + public IADataForComplexProperty(PropertySetter parentBean, AggregationType aggregationType, String complexPropertyName) { + this.parentBean = parentBean; + this.aggregationType = aggregationType; + this.complexPropertyName = complexPropertyName; + } + + public AggregationType getAggregationType() { + return aggregationType; + } + + public Object getNestedComplexProperty() { + return nestedComplexProperty; + } + + public String getComplexPropertyName() { + return complexPropertyName; + } + + public void setNestedComplexProperty(Object nestedComplexProperty) { + this.nestedComplexProperty = nestedComplexProperty; + } + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ImplicitAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ImplicitAction.java index 3233bc55ce1f80014f692a490023a9e7fa78124d..25635cde085113f9c2c634257f05ec5f1fc7b6ab 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ImplicitAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ImplicitAction.java @@ -13,13 +13,11 @@ */ package ch.qos.logback.core.joran.action; - import ch.qos.logback.core.joran.spi.ElementPath; import org.xml.sax.Attributes; import ch.qos.logback.core.joran.spi.InterpretationContext; - /** * ImplcitActions are like normal (explicit) actions except that are applied * by the parser when no other pattern applies. Since there can be many implicit @@ -30,18 +28,16 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; * @author Ceki Gülcü */ public abstract class ImplicitAction extends Action { - - /** - * Check whether this implicit action is appropriate in the current context. - * - * @param currentElementPath This pattern contains the tag name of the current - * element being parsed at the top of the stack. - * @param attributes The attributes of the current element to process. - * @param ec - * @return Whether the implicit action is applicable in the current context - */ - public abstract boolean isApplicable( - ElementPath currentElementPath, Attributes attributes, InterpretationContext ec); - - + + /** + * Check whether this implicit action is appropriate in the current context. + * + * @param currentElementPath This pattern contains the tag name of the current + * element being parsed at the top of the stack. + * @param attributes The attributes of the current element to process. + * @param ec + * @return Whether the implicit action is applicable in the current context + */ + public abstract boolean isApplicable(ElementPath currentElementPath, Attributes attributes, InterpretationContext ec); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IncludeAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IncludeAction.java index 30af56623ca564d540c659e3af22c05661744fae..f43defb1bf0c1e6be398a51cca1d02b956a2ddb2 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/IncludeAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/IncludeAction.java @@ -35,211 +35,208 @@ import ch.qos.logback.core.util.OptionHelper; public class IncludeAction extends Action { - private static final String INCLUDED_TAG = "included"; - private static final String FILE_ATTR = "file"; - private static final String URL_ATTR = "url"; - private static final String RESOURCE_ATTR = "resource"; - private static final String OPTIONAL_ATTR = "optional"; - - private String attributeInUse; - private boolean optional; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - - SaxEventRecorder recorder = new SaxEventRecorder(context); - - this.attributeInUse = null; - this.optional = OptionHelper.toBoolean(attributes.getValue(OPTIONAL_ATTR), false); - - if (!checkAttributes(attributes)) { - return; + private static final String INCLUDED_TAG = "included"; + private static final String FILE_ATTR = "file"; + private static final String URL_ATTR = "url"; + private static final String RESOURCE_ATTR = "resource"; + private static final String OPTIONAL_ATTR = "optional"; + + private String attributeInUse; + private boolean optional; + + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + + SaxEventRecorder recorder = new SaxEventRecorder(context); + + this.attributeInUse = null; + this.optional = OptionHelper.toBoolean(attributes.getValue(OPTIONAL_ATTR), false); + + if (!checkAttributes(attributes)) { + return; + } + + InputStream in = getInputStream(ec, attributes); + + try { + if (in != null) { + parseAndRecord(in, recorder); + // remove the tag from the beginning and from the end + trimHeadAndTail(recorder); + + // offset = 2, because we need to get past this element as well as the end element + ec.getJoranInterpreter().getEventPlayer().addEventsDynamically(recorder.saxEventList, 2); + } + } catch (JoranException e) { + addError("Error while parsing " + attributeInUse, e); + } finally { + close(in); + } + + } + + void close(InputStream in) { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + } + } + } + + private boolean checkAttributes(Attributes attributes) { + String fileAttribute = attributes.getValue(FILE_ATTR); + String urlAttribute = attributes.getValue(URL_ATTR); + String resourceAttribute = attributes.getValue(RESOURCE_ATTR); + + int count = 0; + + if (!OptionHelper.isEmpty(fileAttribute)) { + count++; + } + if (!OptionHelper.isEmpty(urlAttribute)) { + count++; + } + if (!OptionHelper.isEmpty(resourceAttribute)) { + count++; + } + + if (count == 0) { + addError("One of \"path\", \"resource\" or \"url\" attributes must be set."); + return false; + } else if (count > 1) { + addError("Only one of \"file\", \"url\" or \"resource\" attributes should be set."); + return false; + } else if (count == 1) { + return true; + } + throw new IllegalStateException("Count value [" + count + "] is not expected"); } - InputStream in = getInputStream(ec, attributes); - - try { - if (in != null) { - parseAndRecord(in, recorder); - // remove the tag from the beginning and from the end - trimHeadAndTail(recorder); - - // offset = 2, because we need to get past this element as well as the end element - ec.getJoranInterpreter().getEventPlayer().addEventsDynamically(recorder.saxEventList, 2); - } - } catch (JoranException e) { - addError("Error while parsing " + attributeInUse, e); - } finally { - close(in); + private InputStream getInputStreamByFilePath(String pathToFile) { + try { + return new FileInputStream(pathToFile); + } catch (IOException ioe) { + optionalWarning("File [" + pathToFile + "] does not exist."); + return null; + } } - } - - void close(InputStream in) { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - } - } - } - - private boolean checkAttributes(Attributes attributes) { - String fileAttribute = attributes.getValue(FILE_ATTR); - String urlAttribute = attributes.getValue(URL_ATTR); - String resourceAttribute = attributes.getValue(RESOURCE_ATTR); - - int count = 0; - - if (!OptionHelper.isEmpty(fileAttribute)) { - count++; - } - if (!OptionHelper.isEmpty(urlAttribute)) { - count++; - } - if (!OptionHelper.isEmpty(resourceAttribute)) { - count++; + URL attributeToURL(String urlAttribute) { + try { + return new URL(urlAttribute); + } catch (MalformedURLException mue) { + String errMsg = "URL [" + urlAttribute + "] is not well formed."; + addError(errMsg, mue); + return null; + } } - if (count == 0) { - addError("One of \"path\", \"resource\" or \"url\" attributes must be set."); - return false; - } else if (count > 1) { - addError("Only one of \"file\", \"url\" or \"resource\" attributes should be set."); - return false; - } else if (count == 1) { - return true; + private InputStream getInputStreamByUrl(URL url) { + return openURL(url); } - throw new IllegalStateException("Count value [" + count - + "] is not expected"); - } - private InputStream getInputStreamByFilePath(String pathToFile) { - try { - return new FileInputStream(pathToFile); - } catch (IOException ioe) { - optionalWarning("File [" + pathToFile + "] does not exist."); - return null; + InputStream openURL(URL url) { + try { + return url.openStream(); + } catch (IOException e) { + optionalWarning("Failed to open [" + url.toString() + "]"); + return null; + } } - } - URL attributeToURL(String urlAttribute) { - try { - return new URL(urlAttribute); - } catch (MalformedURLException mue) { - String errMsg = "URL [" + urlAttribute + "] is not well formed."; - addError(errMsg, mue); - return null; + URL resourceAsURL(String resourceAttribute) { + URL url = Loader.getResourceBySelfClassLoader(resourceAttribute); + if (url == null) { + optionalWarning("Could not find resource corresponding to [" + resourceAttribute + "]"); + return null; + } else + return url; } - } - - private InputStream getInputStreamByUrl(URL url) { - return openURL(url); - } - InputStream openURL(URL url) { - try { - return url.openStream(); - } catch (IOException e) { - optionalWarning("Failed to open [" + url.toString() + "]"); - return null; + private void optionalWarning(String msg) { + if (!optional) { + addWarn(msg); + } } - } - - URL resourceAsURL(String resourceAttribute) { - URL url = Loader.getResourceBySelfClassLoader(resourceAttribute); - if (url == null) { - optionalWarning("Could not find resource corresponding to [" + resourceAttribute + "]"); - return null; - } else - return url; - } - private void optionalWarning(String msg) { - if (!optional) { - addWarn(msg); + URL filePathAsURL(String path) { + URI uri = new File(path).toURI(); + try { + return uri.toURL(); + } catch (MalformedURLException e) { + // impossible to get here + e.printStackTrace(); + return null; + } } - } - URL filePathAsURL(String path) { - URI uri = new File(path).toURI(); - try { - return uri.toURL(); - } catch (MalformedURLException e) { - // impossible to get here - e.printStackTrace(); - return null; + private InputStream getInputStreamByResource(URL url) { + return openURL(url); } - } - private InputStream getInputStreamByResource(URL url) { - return openURL(url); - } + URL getInputURL(InterpretationContext ec, Attributes attributes) { + String fileAttribute = attributes.getValue(FILE_ATTR); + String urlAttribute = attributes.getValue(URL_ATTR); + String resourceAttribute = attributes.getValue(RESOURCE_ATTR); - URL getInputURL(InterpretationContext ec, Attributes attributes) { - String fileAttribute = attributes.getValue(FILE_ATTR); - String urlAttribute = attributes.getValue(URL_ATTR); - String resourceAttribute = attributes.getValue(RESOURCE_ATTR); + if (!OptionHelper.isEmpty(fileAttribute)) { + this.attributeInUse = ec.subst(fileAttribute); + return filePathAsURL(attributeInUse); + } - if (!OptionHelper.isEmpty(fileAttribute)) { - this.attributeInUse = ec.subst(fileAttribute); - return filePathAsURL(attributeInUse); - } + if (!OptionHelper.isEmpty(urlAttribute)) { + this.attributeInUse = ec.subst(urlAttribute); + return attributeToURL(attributeInUse); + } - if (!OptionHelper.isEmpty(urlAttribute)) { - this.attributeInUse = ec.subst(urlAttribute); - return attributeToURL(attributeInUse); - } + if (!OptionHelper.isEmpty(resourceAttribute)) { + this.attributeInUse = ec.subst(resourceAttribute); + return resourceAsURL(attributeInUse); + } + // given previous checkAttributes() check we cannot reach this line + throw new IllegalStateException("A URL stream should have been returned"); - if (!OptionHelper.isEmpty(resourceAttribute)) { - this.attributeInUse = ec.subst(resourceAttribute); - return resourceAsURL(attributeInUse); } - // given previous checkAttributes() check we cannot reach this line - throw new IllegalStateException("A URL stream should have been returned"); - } + InputStream getInputStream(InterpretationContext ec, Attributes attributes) { + URL inputURL = getInputURL(ec, attributes); + if (inputURL == null) + return null; - InputStream getInputStream(InterpretationContext ec, Attributes attributes) { - URL inputURL = getInputURL(ec, attributes); - if (inputURL == null) - return null; + ConfigurationWatchListUtil.addToWatchList(context, inputURL); + return openURL(inputURL); + } - ConfigurationWatchListUtil.addToWatchList(context, inputURL); - return openURL(inputURL); - } + private void trimHeadAndTail(SaxEventRecorder recorder) { + // Let's remove the two events before + // adding the events to the player. - private void trimHeadAndTail(SaxEventRecorder recorder) { - // Let's remove the two events before - // adding the events to the player. + List saxEventList = recorder.saxEventList; - List saxEventList = recorder.saxEventList; + if (saxEventList.size() == 0) { + return; + } - if (saxEventList.size() == 0) { - return; - } + SaxEvent first = saxEventList.get(0); + if (first != null && first.qName.equalsIgnoreCase(INCLUDED_TAG)) { + saxEventList.remove(0); + } - SaxEvent first = saxEventList.get(0); - if (first != null && first.qName.equalsIgnoreCase(INCLUDED_TAG)) { - saxEventList.remove(0); + SaxEvent last = saxEventList.get(recorder.saxEventList.size() - 1); + if (last != null && last.qName.equalsIgnoreCase(INCLUDED_TAG)) { + saxEventList.remove(recorder.saxEventList.size() - 1); + } } - SaxEvent last = saxEventList.get(recorder.saxEventList.size() - 1); - if (last != null && last.qName.equalsIgnoreCase(INCLUDED_TAG)) { - saxEventList.remove(recorder.saxEventList.size() - 1); + private void parseAndRecord(InputStream inputSource, SaxEventRecorder recorder) throws JoranException { + recorder.setContext(context); + recorder.recordEvents(inputSource); } - } - private void parseAndRecord(InputStream inputSource, SaxEventRecorder recorder) - throws JoranException { - recorder.setContext(context); - recorder.recordEvents(inputSource); - } - - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - // do nothing - } + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + // do nothing + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NOPAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NOPAction.java index 1152929083782f1fb4aa75f657088285e655a1f8..dc6a888f80b2e25fbe32aefbff59b12a812eda10 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NOPAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NOPAction.java @@ -18,7 +18,6 @@ import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - /** * No operation (NOP) action that does strictly nothing. * Setting a rule to this pattern is sometimes useful in order @@ -27,11 +26,10 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; * @author Ceki Gülcü */ public class NOPAction extends Action { - - public void begin(InterpretationContext ec, String name, Attributes attributes) { - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedBasicPropertyIA.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedBasicPropertyIA.java index e187c77cd48d984a0afad86282e7bf2a93b281cf..696bd79ade396c6df2f5cf58ba614ce3d2e500ce 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedBasicPropertyIA.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedBasicPropertyIA.java @@ -31,74 +31,68 @@ import ch.qos.logback.core.util.AggregationType; */ public class NestedBasicPropertyIA extends ImplicitAction { - - // We use a stack of IADataForBasicProperty objects in order to - // support nested elements which are handled by the same NestedBasicPropertyIA instance. - // We push a IADataForBasicProperty instance in the isApplicable method (if the - // action is applicable) and pop it in the end() method. - // The XML well-formedness property will guarantee that a push will eventually - // be followed by the corresponding pop. - Stack actionDataStack = new Stack(); - - public boolean isApplicable(ElementPath elementPath, Attributes attributes, - InterpretationContext ec) { - // System.out.println("in NestedSimplePropertyIA.isApplicable [" + pattern + - // "]"); - String nestedElementTagName = elementPath.peekLast(); - - // no point in attempting if there is no parent object - if (ec.isEmpty()) { - return false; + // We use a stack of IADataForBasicProperty objects in order to + // support nested elements which are handled by the same NestedBasicPropertyIA instance. + // We push a IADataForBasicProperty instance in the isApplicable method (if the + // action is applicable) and pop it in the end() method. + // The XML well-formedness property will guarantee that a push will eventually + // be followed by the corresponding pop. + Stack actionDataStack = new Stack(); + + public boolean isApplicable(ElementPath elementPath, Attributes attributes, InterpretationContext ec) { + // System.out.println("in NestedSimplePropertyIA.isApplicable [" + pattern + + // "]"); + String nestedElementTagName = elementPath.peekLast(); + + // no point in attempting if there is no parent object + if (ec.isEmpty()) { + return false; + } + + Object o = ec.peekObject(); + PropertySetter parentBean = new PropertySetter(o); + parentBean.setContext(context); + + AggregationType aggregationType = parentBean.computeAggregationType(nestedElementTagName); + + switch (aggregationType) { + case NOT_FOUND: + case AS_COMPLEX_PROPERTY: + case AS_COMPLEX_PROPERTY_COLLECTION: + return false; + + case AS_BASIC_PROPERTY: + case AS_BASIC_PROPERTY_COLLECTION: + IADataForBasicProperty ad = new IADataForBasicProperty(parentBean, aggregationType, nestedElementTagName); + actionDataStack.push(ad); + // addInfo("NestedSimplePropertyIA deemed applicable [" + pattern + "]"); + return true; + default: + addError("PropertySetter.canContainComponent returned " + aggregationType); + return false; + } } - Object o = ec.peekObject(); - PropertySetter parentBean = new PropertySetter(o); - parentBean.setContext(context); - - AggregationType aggregationType = parentBean - .computeAggregationType(nestedElementTagName); - - switch (aggregationType) { - case NOT_FOUND: - case AS_COMPLEX_PROPERTY: - case AS_COMPLEX_PROPERTY_COLLECTION: - return false; - - case AS_BASIC_PROPERTY: - case AS_BASIC_PROPERTY_COLLECTION: - IADataForBasicProperty ad = new IADataForBasicProperty(parentBean, - aggregationType, nestedElementTagName); - actionDataStack.push(ad); - // addInfo("NestedSimplePropertyIA deemed applicable [" + pattern + "]"); - return true; - default: - addError("PropertySetter.canContainComponent returned " + aggregationType); - return false; + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + // NOP } - } - - public void begin(InterpretationContext ec, String localName, - Attributes attributes) { - // NOP - } - public void body(InterpretationContext ec, String body) { - - String finalBody = ec.subst(body); - // get the action data object pushed in isApplicable() method call - IADataForBasicProperty actionData = (IADataForBasicProperty) actionDataStack.peek(); - switch (actionData.aggregationType) { - case AS_BASIC_PROPERTY: - actionData.parentBean.setProperty(actionData.propertyName, finalBody); - break; - case AS_BASIC_PROPERTY_COLLECTION: - actionData.parentBean - .addBasicProperty(actionData.propertyName, finalBody); + public void body(InterpretationContext ec, String body) { + + String finalBody = ec.subst(body); + // get the action data object pushed in isApplicable() method call + IADataForBasicProperty actionData = (IADataForBasicProperty) actionDataStack.peek(); + switch (actionData.aggregationType) { + case AS_BASIC_PROPERTY: + actionData.parentBean.setProperty(actionData.propertyName, finalBody); + break; + case AS_BASIC_PROPERTY_COLLECTION: + actionData.parentBean.addBasicProperty(actionData.propertyName, finalBody); + } } - } - public void end(InterpretationContext ec, String tagName) { - // pop the action data object pushed in isApplicable() method call - actionDataStack.pop(); - } + public void end(InterpretationContext ec, String tagName) { + // pop the action data object pushed in isApplicable() method call + actionDataStack.pop(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedComplexPropertyIA.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedComplexPropertyIA.java index 09519cdb4876693992dcffd78129e62554667c86..f10012c186edd1d49b1b64f18710cc5592264e91 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedComplexPropertyIA.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NestedComplexPropertyIA.java @@ -35,158 +35,142 @@ import ch.qos.logback.core.util.OptionHelper; */ public class NestedComplexPropertyIA extends ImplicitAction { - // actionDataStack contains ActionData instances - // We use a stack of ActionData objects in order to support nested - // elements which are handled by the same NestedComplexPropertyIA instance. - // We push a ActionData instance in the isApplicable method (if the - // action is applicable) and pop it in the end() method. - // The XML well-formedness property will guarantee that a push will eventually - // be followed by a corresponding pop. - Stack actionDataStack = new Stack(); - - public boolean isApplicable(ElementPath elementPath, Attributes attributes, - InterpretationContext ic) { - - String nestedElementTagName = elementPath.peekLast(); - - // calling ic.peekObject with an empty stack will throw an exception - if (ic.isEmpty()) { - return false; + // actionDataStack contains ActionData instances + // We use a stack of ActionData objects in order to support nested + // elements which are handled by the same NestedComplexPropertyIA instance. + // We push a ActionData instance in the isApplicable method (if the + // action is applicable) and pop it in the end() method. + // The XML well-formedness property will guarantee that a push will eventually + // be followed by a corresponding pop. + Stack actionDataStack = new Stack(); + + public boolean isApplicable(ElementPath elementPath, Attributes attributes, InterpretationContext ic) { + + String nestedElementTagName = elementPath.peekLast(); + + // calling ic.peekObject with an empty stack will throw an exception + if (ic.isEmpty()) { + return false; + } + + Object o = ic.peekObject(); + PropertySetter parentBean = new PropertySetter(o); + parentBean.setContext(context); + + AggregationType aggregationType = parentBean.computeAggregationType(nestedElementTagName); + + switch (aggregationType) { + case NOT_FOUND: + case AS_BASIC_PROPERTY: + case AS_BASIC_PROPERTY_COLLECTION: + return false; + + // we only push action data if NestComponentIA is applicable + case AS_COMPLEX_PROPERTY_COLLECTION: + case AS_COMPLEX_PROPERTY: + IADataForComplexProperty ad = new IADataForComplexProperty(parentBean, aggregationType, nestedElementTagName); + actionDataStack.push(ad); + + return true; + default: + addError("PropertySetter.computeAggregationType returned " + aggregationType); + return false; + } } - Object o = ic.peekObject(); - PropertySetter parentBean = new PropertySetter(o); - parentBean.setContext(context); - - AggregationType aggregationType = parentBean - .computeAggregationType(nestedElementTagName); - - switch (aggregationType) { - case NOT_FOUND: - case AS_BASIC_PROPERTY: - case AS_BASIC_PROPERTY_COLLECTION: - return false; - - // we only push action data if NestComponentIA is applicable - case AS_COMPLEX_PROPERTY_COLLECTION: - case AS_COMPLEX_PROPERTY: - IADataForComplexProperty ad = new IADataForComplexProperty(parentBean, - aggregationType, nestedElementTagName); - actionDataStack.push(ad); - - return true; - default: - addError("PropertySetter.computeAggregationType returned " - + aggregationType); - return false; - } - } - - public void begin(InterpretationContext ec, String localName, - Attributes attributes) { - // LogLog.debug("in NestComponentIA begin method"); - // get the action data object pushed in isApplicable() method call - IADataForComplexProperty actionData = (IADataForComplexProperty) actionDataStack - .peek(); - - String className = attributes.getValue(CLASS_ATTRIBUTE); - // perform variable name substitution - className = ec.subst(className); - - Class componentClass = null; - try { - - if (!OptionHelper.isEmpty(className)) { - componentClass = Loader.loadClass(className, context); - } else { - // guess class name via implicit rules - PropertySetter parentBean = actionData.parentBean; - componentClass = parentBean.getClassNameViaImplicitRules(actionData - .getComplexPropertyName(), actionData.getAggregationType(), ec - .getDefaultNestedComponentRegistry()); - } - - if (componentClass == null) { - actionData.inError = true; - String errMsg = "Could not find an appropriate class for property [" - + localName + "]"; - addError(errMsg); - return; - } - - if (OptionHelper.isEmpty(className)) { - addInfo("Assuming default type [" + componentClass.getName() - + "] for [" + localName + "] property"); - } - - actionData.setNestedComplexProperty(componentClass.newInstance()); - - // pass along the repository - if (actionData.getNestedComplexProperty() instanceof ContextAware) { - ((ContextAware) actionData.getNestedComplexProperty()) - .setContext(this.context); - } - //addInfo("Pushing component [" + localName - // + "] on top of the object stack."); - ec.pushObject(actionData.getNestedComplexProperty()); - - } catch (Exception oops) { - actionData.inError = true; - String msg = "Could not create component [" + localName + "] of type [" - + className + "]"; - addError(msg, oops); - } - - } - - public void end(InterpretationContext ec, String tagName) { - - // pop the action data object pushed in isApplicable() method call - // we assume that each this begin - IADataForComplexProperty actionData = (IADataForComplexProperty) actionDataStack - .pop(); - - if (actionData.inError) { - return; - } - - PropertySetter nestedBean = new PropertySetter(actionData - .getNestedComplexProperty()); - nestedBean.setContext(context); - - // have the nested element point to its parent if possible - if (nestedBean.computeAggregationType("parent") == AggregationType.AS_COMPLEX_PROPERTY) { - nestedBean.setComplexProperty("parent", actionData.parentBean.getObj()); - } + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + // LogLog.debug("in NestComponentIA begin method"); + // get the action data object pushed in isApplicable() method call + IADataForComplexProperty actionData = (IADataForComplexProperty) actionDataStack.peek(); + + String className = attributes.getValue(CLASS_ATTRIBUTE); + // perform variable name substitution + className = ec.subst(className); + + Class componentClass = null; + try { + + if (!OptionHelper.isEmpty(className)) { + componentClass = Loader.loadClass(className, context); + } else { + // guess class name via implicit rules + PropertySetter parentBean = actionData.parentBean; + componentClass = parentBean.getClassNameViaImplicitRules(actionData.getComplexPropertyName(), actionData.getAggregationType(), + ec.getDefaultNestedComponentRegistry()); + } + + if (componentClass == null) { + actionData.inError = true; + String errMsg = "Could not find an appropriate class for property [" + localName + "]"; + addError(errMsg); + return; + } + + if (OptionHelper.isEmpty(className)) { + addInfo("Assuming default type [" + componentClass.getName() + "] for [" + localName + "] property"); + } + + actionData.setNestedComplexProperty(componentClass.newInstance()); + + // pass along the repository + if (actionData.getNestedComplexProperty() instanceof ContextAware) { + ((ContextAware) actionData.getNestedComplexProperty()).setContext(this.context); + } + // addInfo("Pushing component [" + localName + // + "] on top of the object stack."); + ec.pushObject(actionData.getNestedComplexProperty()); + + } catch (Exception oops) { + actionData.inError = true; + String msg = "Could not create component [" + localName + "] of type [" + className + "]"; + addError(msg, oops); + } - // start the nested complex property if it implements LifeCycle and is not - // marked with a @NoAutoStart annotation - Object nestedComplexProperty = actionData.getNestedComplexProperty(); - if (nestedComplexProperty instanceof LifeCycle - && NoAutoStartUtil.notMarkedWithNoAutoStart(nestedComplexProperty)) { - ((LifeCycle) nestedComplexProperty).start(); } - Object o = ec.peekObject(); - - if (o != actionData.getNestedComplexProperty()) { - addError("The object on the top the of the stack is not the component pushed earlier."); - } else { - ec.popObject(); - // Now let us attach the component - switch (actionData.aggregationType) { - case AS_COMPLEX_PROPERTY: - actionData.parentBean.setComplexProperty(tagName, actionData - .getNestedComplexProperty()); - - break; - case AS_COMPLEX_PROPERTY_COLLECTION: - actionData.parentBean.addComplexProperty(tagName, actionData - .getNestedComplexProperty()); - - break; - } + public void end(InterpretationContext ec, String tagName) { + + // pop the action data object pushed in isApplicable() method call + // we assume that each this begin + IADataForComplexProperty actionData = (IADataForComplexProperty) actionDataStack.pop(); + + if (actionData.inError) { + return; + } + + PropertySetter nestedBean = new PropertySetter(actionData.getNestedComplexProperty()); + nestedBean.setContext(context); + + // have the nested element point to its parent if possible + if (nestedBean.computeAggregationType("parent") == AggregationType.AS_COMPLEX_PROPERTY) { + nestedBean.setComplexProperty("parent", actionData.parentBean.getObj()); + } + + // start the nested complex property if it implements LifeCycle and is not + // marked with a @NoAutoStart annotation + Object nestedComplexProperty = actionData.getNestedComplexProperty(); + if (nestedComplexProperty instanceof LifeCycle && NoAutoStartUtil.notMarkedWithNoAutoStart(nestedComplexProperty)) { + ((LifeCycle) nestedComplexProperty).start(); + } + + Object o = ec.peekObject(); + + if (o != actionData.getNestedComplexProperty()) { + addError("The object on the top the of the stack is not the component pushed earlier."); + } else { + ec.popObject(); + // Now let us attach the component + switch (actionData.aggregationType) { + case AS_COMPLEX_PROPERTY: + actionData.parentBean.setComplexProperty(tagName, actionData.getNestedComplexProperty()); + + break; + case AS_COMPLEX_PROPERTY_COLLECTION: + actionData.parentBean.addComplexProperty(tagName, actionData.getNestedComplexProperty()); + + break; + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NewRuleAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NewRuleAction.java index 7917cb0c7e818383f94841758f0f369bb656cecc..157a5380b12b5e6ae14e640ed95196561f5fa8e0 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/NewRuleAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/NewRuleAction.java @@ -19,54 +19,50 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.joran.spi.ElementSelector; import ch.qos.logback.core.util.OptionHelper; - public class NewRuleAction extends Action { - boolean inError = false; + boolean inError = false; - /** - * Instantiates an layout of the given class and sets its name. - */ - public void begin(InterpretationContext ec, String localName, Attributes attributes) { - // Let us forget about previous errors (in this object) - inError = false; - String errorMsg; - String pattern = attributes.getValue(Action.PATTERN_ATTRIBUTE); - String actionClass = attributes.getValue(Action.ACTION_CLASS_ATTRIBUTE); + /** + * Instantiates an layout of the given class and sets its name. + */ + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + // Let us forget about previous errors (in this object) + inError = false; + String errorMsg; + String pattern = attributes.getValue(Action.PATTERN_ATTRIBUTE); + String actionClass = attributes.getValue(Action.ACTION_CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(pattern)) { - inError = true; - errorMsg = "No 'pattern' attribute in "; - addError(errorMsg); - return; - } + if (OptionHelper.isEmpty(pattern)) { + inError = true; + errorMsg = "No 'pattern' attribute in "; + addError(errorMsg); + return; + } - if (OptionHelper.isEmpty(actionClass)) { - inError = true; - errorMsg = "No 'actionClass' attribute in "; - addError(errorMsg); - return; - } + if (OptionHelper.isEmpty(actionClass)) { + inError = true; + errorMsg = "No 'actionClass' attribute in "; + addError(errorMsg); + return; + } - try { - addInfo("About to add new Joran parsing rule [" + pattern + "," - + actionClass + "]."); - ec.getJoranInterpreter().getRuleStore().addRule(new ElementSelector(pattern), - actionClass); - } catch (Exception oops) { - inError = true; - errorMsg = "Could not add new Joran parsing rule [" + pattern + "," - + actionClass + "]"; - addError(errorMsg); + try { + addInfo("About to add new Joran parsing rule [" + pattern + "," + actionClass + "]."); + ec.getJoranInterpreter().getRuleStore().addRule(new ElementSelector(pattern), actionClass); + } catch (Exception oops) { + inError = true; + errorMsg = "Could not add new Joran parsing rule [" + pattern + "," + actionClass + "]"; + addError(errorMsg); + } } - } - /** - * Once the children elements are also parsed, now is the time to activate the - * appender options. - */ - public void end(InterpretationContext ec, String n) { - } + /** + * Once the children elements are also parsed, now is the time to activate the + * appender options. + */ + public void end(InterpretationContext ec, String n) { + } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ParamAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ParamAction.java index 4b3f626fa2faff0ab3c91a2a29eb7998cb3d1b22..38d1a87f21862abac4fc000cbfc9456e426561d4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ParamAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ParamAction.java @@ -13,55 +13,51 @@ */ package ch.qos.logback.core.joran.action; - import org.xml.sax.Attributes; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.joran.util.PropertySetter; - - public class ParamAction extends Action { - static String NO_NAME = "No name attribute in element"; - static String NO_VALUE = "No name attribute in element"; - boolean inError = false; - - public void begin( - InterpretationContext ec, String localName, Attributes attributes) { - String name = attributes.getValue(NAME_ATTRIBUTE); - String value = attributes.getValue(VALUE_ATTRIBUTE); - - if (name == null) { - inError = true; - addError(NO_NAME); - return; + static String NO_NAME = "No name attribute in element"; + static String NO_VALUE = "No name attribute in element"; + boolean inError = false; + + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + String name = attributes.getValue(NAME_ATTRIBUTE); + String value = attributes.getValue(VALUE_ATTRIBUTE); + + if (name == null) { + inError = true; + addError(NO_NAME); + return; + } + + if (value == null) { + inError = true; + addError(NO_VALUE); + return; + } + + // remove both leading and trailing spaces + value = value.trim(); + + Object o = ec.peekObject(); + PropertySetter propSetter = new PropertySetter(o); + propSetter.setContext(context); + value = ec.subst(value); + + // allow for variable substitution for name as well + name = ec.subst(name); + + // getLogger().debug( + // "In ParamAction setting parameter [{}] to value [{}].", name, value); + propSetter.setProperty(name, value); } - if (value == null) { - inError = true; - addError(NO_VALUE); - return; + public void end(InterpretationContext ec, String localName) { } - // remove both leading and trailing spaces - value = value.trim(); - - Object o = ec.peekObject(); - PropertySetter propSetter = new PropertySetter(o); - propSetter.setContext(context); - value = ec.subst(value); - - // allow for variable substitution for name as well - name = ec.subst(name); - - //getLogger().debug( - // "In ParamAction setting parameter [{}] to value [{}].", name, value); - propSetter.setProperty(name, value); - } - - public void end(InterpretationContext ec, String localName) { - } - - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/PropertyAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/PropertyAction.java index 2d61dce2980eaf012b574e9fa6a3777ad1cd78d8..1b3d0d07191cff9e9eeb727f4cea2c12ee7896e5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/PropertyAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/PropertyAction.java @@ -40,111 +40,102 @@ import ch.qos.logback.core.util.OptionHelper; */ public class PropertyAction extends Action { - static final String RESOURCE_ATTRIBUTE = "resource"; + static final String RESOURCE_ATTRIBUTE = "resource"; + static String INVALID_ATTRIBUTES = "In element, either the \"file\" attribute alone, or " + + "the \"resource\" element alone, or both the \"name\" and \"value\" attributes must be set."; - static String INVALID_ATTRIBUTES = "In element, either the \"file\" attribute alone, or " - + "the \"resource\" element alone, or both the \"name\" and \"value\" attributes must be set."; + /** + * Set a new property for the execution context by name, value pair, or adds + * all the properties found in the given file. + * + */ + public void begin(InterpretationContext ec, String localName, Attributes attributes) { + if ("substitutionProperty".equals(localName)) { + addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead."); + } - /** - * Set a new property for the execution context by name, value pair, or adds - * all the properties found in the given file. - * - */ - public void begin(InterpretationContext ec, String localName, - Attributes attributes) { + String name = attributes.getValue(NAME_ATTRIBUTE); + String value = attributes.getValue(VALUE_ATTRIBUTE); + String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); + + Scope scope = ActionUtil.stringToScope(scopeStr); + + if (checkFileAttributeSanity(attributes)) { + String file = attributes.getValue(FILE_ATTRIBUTE); + file = ec.subst(file); + try { + FileInputStream istream = new FileInputStream(file); + loadAndSetProperties(ec, istream, scope); + } catch (FileNotFoundException e) { + addError("Could not find properties file [" + file + "]."); + } catch (IOException e1) { + addError("Could not read properties file [" + file + "].", e1); + } + } else if (checkResourceAttributeSanity(attributes)) { + String resource = attributes.getValue(RESOURCE_ATTRIBUTE); + resource = ec.subst(resource); + URL resourceURL = Loader.getResourceBySelfClassLoader(resource); + if (resourceURL == null) { + addError("Could not find resource [" + resource + "]."); + } else { + try { + InputStream istream = resourceURL.openStream(); + loadAndSetProperties(ec, istream, scope); + } catch (IOException e) { + addError("Could not read resource file [" + resource + "].", e); + } + } + } else if (checkValueNameAttributesSanity(attributes)) { + value = RegularEscapeUtil.basicEscape(value); + // now remove both leading and trailing spaces + value = value.trim(); + value = ec.subst(value); + ActionUtil.setProperty(ec, name, value, scope); + + } else { + addError(INVALID_ATTRIBUTES); + } + } - if ("substitutionProperty".equals(localName)) { - addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead."); + void loadAndSetProperties(InterpretationContext ec, InputStream istream, Scope scope) throws IOException { + Properties props = new Properties(); + props.load(istream); + istream.close(); + ActionUtil.setProperties(ec, props, scope); } - String name = attributes.getValue(NAME_ATTRIBUTE); - String value = attributes.getValue(VALUE_ATTRIBUTE); - String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); - - Scope scope = ActionUtil.stringToScope(scopeStr); - - if (checkFileAttributeSanity(attributes)) { - String file = attributes.getValue(FILE_ATTRIBUTE); - file = ec.subst(file); - try { - FileInputStream istream = new FileInputStream(file); - loadAndSetProperties(ec, istream, scope); - } catch (FileNotFoundException e) { - addError("Could not find properties file [" + file + "]."); - } catch (IOException e1) { - addError("Could not read properties file [" + file + "].", e1); - } - } else if (checkResourceAttributeSanity(attributes)) { - String resource = attributes.getValue(RESOURCE_ATTRIBUTE); - resource = ec.subst(resource); - URL resourceURL = Loader.getResourceBySelfClassLoader(resource); - if (resourceURL == null) { - addError("Could not find resource [" + resource + "]."); - } else { - try { - InputStream istream = resourceURL.openStream(); - loadAndSetProperties(ec, istream, scope); - } catch (IOException e) { - addError("Could not read resource file [" + resource + "].", e); - } - } - } else if (checkValueNameAttributesSanity(attributes)) { - value = RegularEscapeUtil.basicEscape(value); - // now remove both leading and trailing spaces - value = value.trim(); - value = ec.subst(value); - ActionUtil.setProperty(ec, name, value, scope); - - } else { - addError(INVALID_ATTRIBUTES); + boolean checkFileAttributeSanity(Attributes attributes) { + String file = attributes.getValue(FILE_ATTRIBUTE); + String name = attributes.getValue(NAME_ATTRIBUTE); + String value = attributes.getValue(VALUE_ATTRIBUTE); + String resource = attributes.getValue(RESOURCE_ATTRIBUTE); + + return !(OptionHelper.isEmpty(file)) && (OptionHelper.isEmpty(name) && OptionHelper.isEmpty(value) && OptionHelper.isEmpty(resource)); + } + + boolean checkResourceAttributeSanity(Attributes attributes) { + String file = attributes.getValue(FILE_ATTRIBUTE); + String name = attributes.getValue(NAME_ATTRIBUTE); + String value = attributes.getValue(VALUE_ATTRIBUTE); + String resource = attributes.getValue(RESOURCE_ATTRIBUTE); + + return !(OptionHelper.isEmpty(resource)) && (OptionHelper.isEmpty(name) && OptionHelper.isEmpty(value) && OptionHelper.isEmpty(file)); + } + + boolean checkValueNameAttributesSanity(Attributes attributes) { + String file = attributes.getValue(FILE_ATTRIBUTE); + String name = attributes.getValue(NAME_ATTRIBUTE); + String value = attributes.getValue(VALUE_ATTRIBUTE); + String resource = attributes.getValue(RESOURCE_ATTRIBUTE); + + return (!(OptionHelper.isEmpty(name) || OptionHelper.isEmpty(value)) && (OptionHelper.isEmpty(file) && OptionHelper.isEmpty(resource))); + } + + public void end(InterpretationContext ec, String name) { + } + + public void finish(InterpretationContext ec) { } - } - - void loadAndSetProperties(InterpretationContext ec, InputStream istream, Scope scope) - throws IOException { - Properties props = new Properties(); - props.load(istream); - istream.close(); - ActionUtil.setProperties(ec, props, scope); - } - - boolean checkFileAttributeSanity(Attributes attributes) { - String file = attributes.getValue(FILE_ATTRIBUTE); - String name = attributes.getValue(NAME_ATTRIBUTE); - String value = attributes.getValue(VALUE_ATTRIBUTE); - String resource = attributes.getValue(RESOURCE_ATTRIBUTE); - - return !(OptionHelper.isEmpty(file)) - && (OptionHelper.isEmpty(name) && OptionHelper.isEmpty(value) && OptionHelper - .isEmpty(resource)); - } - - boolean checkResourceAttributeSanity(Attributes attributes) { - String file = attributes.getValue(FILE_ATTRIBUTE); - String name = attributes.getValue(NAME_ATTRIBUTE); - String value = attributes.getValue(VALUE_ATTRIBUTE); - String resource = attributes.getValue(RESOURCE_ATTRIBUTE); - - return !(OptionHelper.isEmpty(resource)) - && (OptionHelper.isEmpty(name) && OptionHelper.isEmpty(value) && OptionHelper - .isEmpty(file)); - } - - boolean checkValueNameAttributesSanity(Attributes attributes) { - String file = attributes.getValue(FILE_ATTRIBUTE); - String name = attributes.getValue(NAME_ATTRIBUTE); - String value = attributes.getValue(VALUE_ATTRIBUTE); - String resource = attributes.getValue(RESOURCE_ATTRIBUTE); - - return (!(OptionHelper.isEmpty(name) || OptionHelper.isEmpty(value)) && (OptionHelper - .isEmpty(file) && OptionHelper.isEmpty(resource))); - } - - public void end(InterpretationContext ec, String name) { - } - - public void finish(InterpretationContext ec) { - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ShutdownHookAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ShutdownHookAction.java index 2f2d828396376d20af89d682d40c7cce682b5b89..3208e6e8533736c80f9e171c4ea21150636a3818 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/ShutdownHookAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/ShutdownHookAction.java @@ -27,64 +27,62 @@ import ch.qos.logback.core.util.OptionHelper; * @author Mike Reinhold */ public class ShutdownHookAction extends Action { - - ShutdownHookBase hook; - private boolean inError; - - /** - * Instantiates a shutdown hook of the given class and sets its name. - * - * The hook thus generated is placed in the {@link InterpretationContext}'s - * shutdown hook bag. - */ - @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { - hook = null; - inError = false; - - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Missing class name for shutdown hook. Near [" + name - + "] line " + getLineNumber(ic)); - inError = true; - return; - } - - try { - addInfo("About to instantiate shutdown hook of type [" + className + "]"); - hook = (ShutdownHookBase) OptionHelper.instantiateByClassName(className, - ShutdownHookBase.class, context); - hook.setContext(context); - - ic.pushObject(hook); - }catch (Exception e) { - inError = true; - addError("Could not create a shutdown hook of type [" + className + "].", e); - throw new ActionException(e); - } - } - - /** - * Once the children elements are also parsed, now is the time to activate the - * shutdown hook options. - */ - @Override - public void end(InterpretationContext ic, String name) throws ActionException { - if (inError) { - return; + ShutdownHookBase hook; + private boolean inError; + + /** + * Instantiates a shutdown hook of the given class and sets its name. + * + * The hook thus generated is placed in the {@link InterpretationContext}'s + * shutdown hook bag. + */ + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { + hook = null; + inError = false; + + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Missing class name for shutdown hook. Near [" + name + "] line " + getLineNumber(ic)); + inError = true; + return; + } + + try { + addInfo("About to instantiate shutdown hook of type [" + className + "]"); + + hook = (ShutdownHookBase) OptionHelper.instantiateByClassName(className, ShutdownHookBase.class, context); + hook.setContext(context); + + ic.pushObject(hook); + } catch (Exception e) { + inError = true; + addError("Could not create a shutdown hook of type [" + className + "].", e); + throw new ActionException(e); + } } - - Object o = ic.peekObject(); - if (o != hook) { - addWarn("The object at the of the stack is not the hook pushed earlier."); - } else { - ic.popObject(); - - Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]"); - - context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread); - Runtime.getRuntime().addShutdownHook(hookThread); + + /** + * Once the children elements are also parsed, now is the time to activate the + * shutdown hook options. + */ + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + if (inError) { + return; + } + + Object o = ic.peekObject(); + if (o != hook) { + addWarn("The object at the of the stack is not the hook pushed earlier."); + } else { + ic.popObject(); + + Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]"); + + context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread); + Runtime.getRuntime().addShutdownHook(hookThread); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/StatusListenerAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/StatusListenerAction.java index b3f207539f70e7e038de8cfb836335b96cb14e14..d55c6ef5d2c76fed412528bc5c2f56ad07ab9165 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/StatusListenerAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/StatusListenerAction.java @@ -22,64 +22,59 @@ import ch.qos.logback.core.spi.LifeCycle; import ch.qos.logback.core.status.StatusListener; import ch.qos.logback.core.util.OptionHelper; - public class StatusListenerAction extends Action { + boolean inError = false; + Boolean effectivelyAdded = null; + StatusListener statusListener = null; - boolean inError = false; - Boolean effectivelyAdded = null; - StatusListener statusListener = null; + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + inError = false; + effectivelyAdded = null; + String className = attributes.getValue(CLASS_ATTRIBUTE); + if (OptionHelper.isEmpty(className)) { + addError("Missing class name for statusListener. Near [" + name + "] line " + getLineNumber(ec)); + inError = true; + return; + } - public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - inError = false; - effectivelyAdded = null; - String className = attributes.getValue(CLASS_ATTRIBUTE); - if (OptionHelper.isEmpty(className)) { - addError("Missing class name for statusListener. Near [" - + name + "] line " + getLineNumber(ec)); - inError = true; - return; - } + try { + statusListener = (StatusListener) OptionHelper.instantiateByClassName(className, StatusListener.class, context); + effectivelyAdded = ec.getContext().getStatusManager().add(statusListener); + if (statusListener instanceof ContextAware) { + ((ContextAware) statusListener).setContext(context); + } + addInfo("Added status listener of type [" + className + "]"); + ec.pushObject(statusListener); + } catch (Exception e) { + inError = true; + addError("Could not create an StatusListener of type [" + className + "].", e); + throw new ActionException(e); + } - try { - statusListener = (StatusListener) OptionHelper.instantiateByClassName( - className, StatusListener.class, context); - effectivelyAdded = ec.getContext().getStatusManager().add(statusListener); - if (statusListener instanceof ContextAware) { - ((ContextAware) statusListener).setContext(context); - } - addInfo("Added status listener of type [" + className + "]"); - ec.pushObject(statusListener); - } catch (Exception e) { - inError = true; - addError( - "Could not create an StatusListener of type [" + className + "].", e); - throw new ActionException(e); } - } - - public void finish(InterpretationContext ec) { - } - - public void end(InterpretationContext ec, String e) { - if (inError) { - return; + public void finish(InterpretationContext ec) { } - if (isEffectivelyAdded() && statusListener instanceof LifeCycle) { - ((LifeCycle) statusListener).start(); - } - Object o = ec.peekObject(); - if (o != statusListener) { - addWarn("The object at the of the stack is not the statusListener pushed earlier."); - } else { - ec.popObject(); + + public void end(InterpretationContext ec, String e) { + if (inError) { + return; + } + if (isEffectivelyAdded() && statusListener instanceof LifeCycle) { + ((LifeCycle) statusListener).start(); + } + Object o = ec.peekObject(); + if (o != statusListener) { + addWarn("The object at the of the stack is not the statusListener pushed earlier."); + } else { + ec.popObject(); + } } - } - private boolean isEffectivelyAdded() { - if(effectivelyAdded == null) - return false; - return effectivelyAdded; - } + private boolean isEffectivelyAdded() { + if (effectivelyAdded == null) + return false; + return effectivelyAdded; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/action/TimestampAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/action/TimestampAction.java index a24968e3775b6e66fc32f8250dda0c86bf521ccf..b35aee1f7050dd4806460bf3bcef9d5a2aebd0a3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/action/TimestampAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/action/TimestampAction.java @@ -30,54 +30,50 @@ import ch.qos.logback.core.util.OptionHelper; * */ public class TimestampAction extends Action { - static String DATE_PATTERN_ATTRIBUTE = "datePattern"; - static String TIME_REFERENCE_ATTRIBUTE = "timeReference"; - static String CONTEXT_BIRTH = "contextBirth"; + static String DATE_PATTERN_ATTRIBUTE = "datePattern"; + static String TIME_REFERENCE_ATTRIBUTE = "timeReference"; + static String CONTEXT_BIRTH = "contextBirth"; - boolean inError = false; + boolean inError = false; - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - String keyStr = attributes.getValue(KEY_ATTRIBUTE); - if (OptionHelper.isEmpty(keyStr)) { - addError("Attribute named [" + KEY_ATTRIBUTE + "] cannot be empty"); - inError = true; - } - String datePatternStr = attributes.getValue(DATE_PATTERN_ATTRIBUTE); - if (OptionHelper.isEmpty(datePatternStr)) { - addError("Attribute named [" + DATE_PATTERN_ATTRIBUTE - + "] cannot be empty"); - inError = true; - } + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + String keyStr = attributes.getValue(KEY_ATTRIBUTE); + if (OptionHelper.isEmpty(keyStr)) { + addError("Attribute named [" + KEY_ATTRIBUTE + "] cannot be empty"); + inError = true; + } + String datePatternStr = attributes.getValue(DATE_PATTERN_ATTRIBUTE); + if (OptionHelper.isEmpty(datePatternStr)) { + addError("Attribute named [" + DATE_PATTERN_ATTRIBUTE + "] cannot be empty"); + inError = true; + } - String timeReferenceStr = attributes.getValue(TIME_REFERENCE_ATTRIBUTE); - long timeReference; - if (CONTEXT_BIRTH.equalsIgnoreCase(timeReferenceStr)) { - addInfo("Using context birth as time reference."); - timeReference = context.getBirthTime(); - } else { - timeReference = System.currentTimeMillis(); - addInfo("Using current interpretation time, i.e. now, as time reference."); - } + String timeReferenceStr = attributes.getValue(TIME_REFERENCE_ATTRIBUTE); + long timeReference; + if (CONTEXT_BIRTH.equalsIgnoreCase(timeReferenceStr)) { + addInfo("Using context birth as time reference."); + timeReference = context.getBirthTime(); + } else { + timeReference = System.currentTimeMillis(); + addInfo("Using current interpretation time, i.e. now, as time reference."); + } + if (inError) + return; - if (inError) - return; + String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); + Scope scope = ActionUtil.stringToScope(scopeStr); - String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE); - Scope scope = ActionUtil.stringToScope(scopeStr); - - CachingDateFormatter sdf = new CachingDateFormatter(datePatternStr); - String val = sdf.format(timeReference); + CachingDateFormatter sdf = new CachingDateFormatter(datePatternStr); + String val = sdf.format(timeReference); - addInfo("Adding property to the context with key=\"" + keyStr - + "\" and value=\"" + val + "\" to the " + scope + " scope"); - ActionUtil.setProperty(ec, keyStr, val, scope); - } + addInfo("Adding property to the context with key=\"" + keyStr + "\" and value=\"" + val + "\" to the " + scope + " scope"); + ActionUtil.setProperty(ec, keyStr, val, scope); + } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - } + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/Condition.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/Condition.java index dc8967ce5b974266d9a79a1074c59162822b1982..250dbad672c6665932183bb9f881c03af869e83e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/Condition.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/Condition.java @@ -14,5 +14,5 @@ package ch.qos.logback.core.joran.conditional; public interface Condition { - boolean evaluate(); + boolean evaluate(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ElseAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ElseAction.java index e521b004c10931efd7555eb064997cb0e7bcee00..cb3b09735905f1115d8113778ce871cf3c75ec29 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ElseAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ElseAction.java @@ -17,12 +17,12 @@ import java.util.List; import ch.qos.logback.core.joran.event.SaxEvent; -public class ElseAction extends ThenOrElseActionBase { +public class ElseAction extends ThenOrElseActionBase { - @Override - void registerEventList(IfAction ifAction, List eventList) { - ifAction.setElseSaxEventList(eventList); - - } + @Override + void registerEventList(IfAction ifAction, List eventList) { + ifAction.setElseSaxEventList(eventList); + + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/IfAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/IfAction.java index 7e07bd1b0b73636bb1ba97ac4435cc43595e74f8..1b44099455d4f3e8a645cf161a47c93c9090aaa1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/IfAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/IfAction.java @@ -28,128 +28,123 @@ import ch.qos.logback.core.joran.spi.Interpreter; import ch.qos.logback.core.util.OptionHelper; public class IfAction extends Action { - private static final String CONDITION_ATTR = "condition"; - - public static final String MISSING_JANINO_MSG = "Could not find Janino library on the class path. Skipping conditional processing."; - public static final String MISSING_JANINO_SEE = "See also " + CoreConstants.CODES_URL + "#ifJanino"; - - Stack stack = new Stack(); - - @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { - - IfState state = new IfState(); - boolean emptyStack = stack.isEmpty(); - stack.push(state); - - if(!emptyStack) { - return; + private static final String CONDITION_ATTR = "condition"; + + public static final String MISSING_JANINO_MSG = "Could not find Janino library on the class path. Skipping conditional processing."; + public static final String MISSING_JANINO_SEE = "See also " + CoreConstants.CODES_URL + "#ifJanino"; + + Stack stack = new Stack(); + + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { + + IfState state = new IfState(); + boolean emptyStack = stack.isEmpty(); + stack.push(state); + + if (!emptyStack) { + return; + } + + ic.pushObject(this); + if (!EnvUtil.isJaninoAvailable()) { + addError(MISSING_JANINO_MSG); + addError(MISSING_JANINO_SEE); + return; + } + + state.active = true; + Condition condition = null; + String conditionAttribute = attributes.getValue(CONDITION_ATTR); + + if (!OptionHelper.isEmpty(conditionAttribute)) { + conditionAttribute = OptionHelper.substVars(conditionAttribute, ic, context); + PropertyEvalScriptBuilder pesb = new PropertyEvalScriptBuilder(ic); + pesb.setContext(context); + try { + condition = pesb.build(conditionAttribute); + } catch (Exception e) { + addError("Failed to parse condition [" + conditionAttribute + "]", e); + } + + if (condition != null) { + state.boolResult = condition.evaluate(); + } + + } } - - ic.pushObject(this); - if(!EnvUtil.isJaninoAvailable()) { - addError(MISSING_JANINO_MSG); - addError(MISSING_JANINO_SEE); - return; - } - - state.active = true; - Condition condition = null; - String conditionAttribute = attributes.getValue(CONDITION_ATTR); - - - if (!OptionHelper.isEmpty(conditionAttribute)) { - conditionAttribute = OptionHelper.substVars(conditionAttribute, ic, context); - PropertyEvalScriptBuilder pesb = new PropertyEvalScriptBuilder(ic); - pesb.setContext(context); - try { - condition = pesb.build(conditionAttribute); - } catch (Exception e) { - addError("Failed to parse condition ["+conditionAttribute+"]", e); - } - - if(condition!=null) { - state.boolResult = condition.evaluate(); - } - - } - } - - @Override - public void end(InterpretationContext ic, String name) throws ActionException { - - IfState state = stack.pop(); - if(!state.active) { - return; - } - - - Object o = ic.peekObject(); - if (o == null) { - throw new IllegalStateException("Unexpected null object on stack"); - } - if (!(o instanceof IfAction)) { - throw new IllegalStateException("Unexpected object of type [" - + o.getClass() + "] on stack"); - } + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + + IfState state = stack.pop(); + if (!state.active) { + return; + } + + Object o = ic.peekObject(); + if (o == null) { + throw new IllegalStateException("Unexpected null object on stack"); + } + if (!(o instanceof IfAction)) { + throw new IllegalStateException("Unexpected object of type [" + o.getClass() + "] on stack"); + } + + if (o != this) { + throw new IllegalStateException("IfAction different then current one on stack"); + } + ic.popObject(); + + if (state.boolResult == null) { + addError("Failed to determine \"if then else\" result"); + return; + } + + Interpreter interpreter = ic.getJoranInterpreter(); + List listToPlay = state.thenSaxEventList; + if (!state.boolResult) { + listToPlay = state.elseSaxEventList; + } + + // if boolResult==false & missing else, listToPlay may be null + if (listToPlay != null) { + // insert past this event + interpreter.getEventPlayer().addEventsDynamically(listToPlay, 1); + } - if (o != this) { - throw new IllegalStateException( - "IfAction different then current one on stack"); } - ic.popObject(); - if (state.boolResult == null) { - addError("Failed to determine \"if then else\" result"); - return; + public void setThenSaxEventList(List thenSaxEventList) { + IfState state = stack.firstElement(); + if (state.active) { + state.thenSaxEventList = thenSaxEventList; + } else { + throw new IllegalStateException("setThenSaxEventList() invoked on inactive IfAction"); + } } - Interpreter interpreter = ic.getJoranInterpreter(); - List listToPlay = state.thenSaxEventList; - if (!state.boolResult) { - listToPlay = state.elseSaxEventList; - } + public void setElseSaxEventList(List elseSaxEventList) { + IfState state = stack.firstElement(); + if (state.active) { + state.elseSaxEventList = elseSaxEventList; + } else { + throw new IllegalStateException("setElseSaxEventList() invoked on inactive IfAction"); + } - // if boolResult==false & missing else, listToPlay may be null - if(listToPlay != null) { - // insert past this event - interpreter.getEventPlayer().addEventsDynamically(listToPlay, 1); } - } - - - public void setThenSaxEventList(List thenSaxEventList) { - IfState state = stack.firstElement(); - if(state.active) { - state.thenSaxEventList = thenSaxEventList; - } else { - throw new IllegalStateException("setThenSaxEventList() invoked on inactive IfAction"); - } - } - - public void setElseSaxEventList(List elseSaxEventList) { - IfState state = stack.firstElement(); - if(state.active) { - state.elseSaxEventList = elseSaxEventList; - } else { - throw new IllegalStateException("setElseSaxEventList() invoked on inactive IfAction"); + public boolean isActive() { + if (stack == null) + return false; + if (stack.isEmpty()) + return false; + return stack.peek().active; } - - } - - public boolean isActive() { - if(stack == null) return false; - if(stack.isEmpty()) return false; - return stack.peek().active; - } } class IfState { - Boolean boolResult; - List thenSaxEventList; - List elseSaxEventList; - boolean active; + Boolean boolResult; + List thenSaxEventList; + List elseSaxEventList; + boolean active; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilder.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilder.java index a806bfae7515738a35dfe474f53085a6273a00a4..8c7ee1236f2ae092a1fd560ee3b521aa3b43325b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilder.java @@ -26,36 +26,32 @@ import ch.qos.logback.core.spi.ContextAwareBase; public class PropertyEvalScriptBuilder extends ContextAwareBase { - private static String SCRIPT_PREFIX = "" - + "public boolean evaluate() { return "; - private static String SCRIPT_SUFFIX = "" + "; }"; + private static String SCRIPT_PREFIX = "" + "public boolean evaluate() { return "; + private static String SCRIPT_SUFFIX = "" + "; }"; - final PropertyContainer localPropContainer; + final PropertyContainer localPropContainer; - PropertyEvalScriptBuilder(PropertyContainer localPropContainer) { - this.localPropContainer = localPropContainer; - } + PropertyEvalScriptBuilder(PropertyContainer localPropContainer) { + this.localPropContainer = localPropContainer; + } - Map map = new HashMap(); + Map map = new HashMap(); - public Condition build(String script) throws IllegalAccessException, - CompileException, - InstantiationException, - SecurityException, NoSuchMethodException, IllegalArgumentException, - InvocationTargetException { + public Condition build(String script) throws IllegalAccessException, CompileException, InstantiationException, SecurityException, NoSuchMethodException, + IllegalArgumentException, InvocationTargetException { - ClassBodyEvaluator cbe = new ClassBodyEvaluator(); - cbe.setImplementedInterfaces(new Class[]{Condition.class}); - cbe.setExtendedClass(PropertyWrapperForScripts.class); - cbe.setParentClassLoader(ClassBodyEvaluator.class.getClassLoader()); - cbe.cook(SCRIPT_PREFIX + script + SCRIPT_SUFFIX); + ClassBodyEvaluator cbe = new ClassBodyEvaluator(); + cbe.setImplementedInterfaces(new Class[] { Condition.class }); + cbe.setExtendedClass(PropertyWrapperForScripts.class); + cbe.setParentClassLoader(ClassBodyEvaluator.class.getClassLoader()); + cbe.cook(SCRIPT_PREFIX + script + SCRIPT_SUFFIX); - Class clazz = cbe.getClazz(); - Condition instance = (Condition) clazz.newInstance(); - Method setMapMethod = clazz.getMethod("setPropertyContainers", PropertyContainer.class, PropertyContainer.class); - setMapMethod.invoke(instance, localPropContainer, context); + Class clazz = cbe.getClazz(); + Condition instance = (Condition) clazz.newInstance(); + Method setMapMethod = clazz.getMethod("setPropertyContainers", PropertyContainer.class, PropertyContainer.class); + setMapMethod.invoke(instance, localPropContainer, context); - return instance; - } + return instance; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.java index a93cce2bd77a0ce8e82373cda1c2444ab4cf0948..1409d40a925699fccfb6d1efd35f526735bd75dc 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.java @@ -18,34 +18,34 @@ import ch.qos.logback.core.util.OptionHelper; public class PropertyWrapperForScripts { - PropertyContainer local; - PropertyContainer context; - - // this method is invoked by reflection in PropertyEvalScriptBuilder - public void setPropertyContainers(PropertyContainer local, PropertyContainer context) { - this.local = local; - this.context = context; - } - - public boolean isNull(String k) { - String val = OptionHelper.propertyLookup(k, local, context); - return (val == null); - } - - public boolean isDefined(String k) { - String val = OptionHelper.propertyLookup(k, local, context); - return (val != null); - } - - public String p(String k) { - return property(k); - } - - public String property(String k) { - String val = OptionHelper.propertyLookup(k, local, context); - if(val != null) - return val; - else - return ""; - } + PropertyContainer local; + PropertyContainer context; + + // this method is invoked by reflection in PropertyEvalScriptBuilder + public void setPropertyContainers(PropertyContainer local, PropertyContainer context) { + this.local = local; + this.context = context; + } + + public boolean isNull(String k) { + String val = OptionHelper.propertyLookup(k, local, context); + return (val == null); + } + + public boolean isDefined(String k) { + String val = OptionHelper.propertyLookup(k, local, context); + return (val != null); + } + + public String p(String k) { + return property(k); + } + + public String property(String k) { + String val = OptionHelper.propertyLookup(k, local, context); + if (val != null) + return val; + else + return ""; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenAction.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenAction.java index a74638da3b906831617fe713a676df81bf172172..8217cbee12f7baa184b7d4e90d76c7df083e97bb 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenAction.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenAction.java @@ -17,11 +17,11 @@ import java.util.List; import ch.qos.logback.core.joran.event.SaxEvent; -public class ThenAction extends ThenOrElseActionBase { +public class ThenAction extends ThenOrElseActionBase { - @Override - void registerEventList(IfAction ifAction, List eventList) { - ifAction.setThenSaxEventList(eventList); - } + @Override + void registerEventList(IfAction ifAction, List eventList) { + ifAction.setThenSaxEventList(eventList); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenOrElseActionBase.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenOrElseActionBase.java index 5da1e0960f98bdf1c020b147e8927f61986054ea..5ce0b920c7778c9ecaf9548b39b34c12b3cf040c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenOrElseActionBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/ThenOrElseActionBase.java @@ -27,62 +27,64 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; abstract public class ThenOrElseActionBase extends Action { - Stack stateStack = new Stack(); + Stack stateStack = new Stack(); - @Override - public void begin(InterpretationContext ic, String name, Attributes attributes) - throws ActionException { + @Override + public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException { - if(!weAreActive(ic)) return; + if (!weAreActive(ic)) + return; - ThenActionState state = new ThenActionState(); - if (ic.isListenerListEmpty()) { - ic.addInPlayListener(state); - state.isRegistered = true; + ThenActionState state = new ThenActionState(); + if (ic.isListenerListEmpty()) { + ic.addInPlayListener(state); + state.isRegistered = true; + } + stateStack.push(state); } - stateStack.push(state); - } - - boolean weAreActive(InterpretationContext ic) { - Object o = ic.peekObject(); - if(!(o instanceof IfAction)) return false; - IfAction ifAction = (IfAction) o; - return ifAction.isActive(); - } - - @Override - public void end(InterpretationContext ic, String name) throws ActionException { - if(!weAreActive(ic)) return; - - ThenActionState state = stateStack.pop(); - if (state.isRegistered) { - ic.removeInPlayListener(state); - Object o = ic.peekObject(); - if (o instanceof IfAction) { + + boolean weAreActive(InterpretationContext ic) { + Object o = ic.peekObject(); + if (!(o instanceof IfAction)) + return false; IfAction ifAction = (IfAction) o; - removeFirstAndLastFromList(state.eventList); - registerEventList(ifAction, state.eventList); - } else { - throw new IllegalStateException("Missing IfAction on top of stack"); - } + return ifAction.isActive(); + } + + @Override + public void end(InterpretationContext ic, String name) throws ActionException { + if (!weAreActive(ic)) + return; + + ThenActionState state = stateStack.pop(); + if (state.isRegistered) { + ic.removeInPlayListener(state); + Object o = ic.peekObject(); + if (o instanceof IfAction) { + IfAction ifAction = (IfAction) o; + removeFirstAndLastFromList(state.eventList); + registerEventList(ifAction, state.eventList); + } else { + throw new IllegalStateException("Missing IfAction on top of stack"); + } + } } - } - - abstract void registerEventList(IfAction ifAction, List eventList); - void removeFirstAndLastFromList(List eventList) { - eventList.remove(0); - eventList.remove(eventList.size() - 1); - } + abstract void registerEventList(IfAction ifAction, List eventList); + + void removeFirstAndLastFromList(List eventList) { + eventList.remove(0); + eventList.remove(eventList.size() - 1); + } } class ThenActionState implements InPlayListener { - List eventList = new ArrayList(); - boolean isRegistered = false; - - public void inPlay(SaxEvent event) { - eventList.add(event); - } + List eventList = new ArrayList(); + boolean isRegistered = false; + + public void inPlay(SaxEvent event) { + eventList.add(event); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/BodyEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/BodyEvent.java index 85001f99d3cca12b131d5a7b97a74f16814f887b..1dba8fadccecc6fd527a43939f1c4d21b9bf9a07 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/BodyEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/BodyEvent.java @@ -15,36 +15,34 @@ package ch.qos.logback.core.joran.event; import org.xml.sax.Locator; - public class BodyEvent extends SaxEvent { - private String text; - - BodyEvent(String text, Locator locator) { - super(null, null, null, locator); - this.text = text; - } - - /** - * Always trim trailing spaces from the body text. - * - * @return - */ - public String getText() { - if(text != null) { - return text.trim(); - } - return text; - } - - @Override - public String toString() { - return "BodyEvent(" + getText() + ")" + locator.getLineNumber() + "," - + locator.getColumnNumber(); - } - - public void append(String str) { - text += str; - } + private String text; + + BodyEvent(String text, Locator locator) { + super(null, null, null, locator); + this.text = text; + } + + /** + * Always trim trailing spaces from the body text. + * + * @return + */ + public String getText() { + if (text != null) { + return text.trim(); + } + return text; + } + + @Override + public String toString() { + return "BodyEvent(" + getText() + ")" + locator.getLineNumber() + "," + locator.getColumnNumber(); + } + + public void append(String str) { + text += str; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/EndEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/EndEvent.java index c6d43f0dd0af1a8351fe4b6dbdabcb0eac57a02e..abafb8495e7ee197e68ddc7f65a5e07eef3f4090 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/EndEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/EndEvent.java @@ -15,17 +15,15 @@ package ch.qos.logback.core.joran.event; import org.xml.sax.Locator; - public class EndEvent extends SaxEvent { - EndEvent(String namespaceURI, String localName, String qName, Locator locator) { - super(namespaceURI, localName, qName, locator); - } - - @Override - public String toString() { - return " EndEvent("+getQName()+") ["+locator.getLineNumber()+","+locator.getColumnNumber()+"]"; - } + EndEvent(String namespaceURI, String localName, String qName, Locator locator) { + super(namespaceURI, localName, qName, locator); + } + @Override + public String toString() { + return " EndEvent(" + getQName() + ") [" + locator.getLineNumber() + "," + locator.getColumnNumber() + "]"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/InPlayListener.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/InPlayListener.java index c978d9a87d8273e9b363fca364d189257680dcb2..7e22a74139e58666739833c2306f865dd0c96e62 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/InPlayListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/InPlayListener.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.joran.event; - public interface InPlayListener { - void inPlay(SaxEvent event); -} + void inPlay(SaxEvent event); +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEvent.java index 362fa02271bf3fcf9cb38cd1a582ace287ebc0f8..1dd4ed0c0250f81cc0c3dce730807947959aa8e2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEvent.java @@ -18,32 +18,32 @@ import org.xml.sax.helpers.LocatorImpl; public class SaxEvent { - final public String namespaceURI; - final public String localName; - final public String qName; - final public Locator locator; - - SaxEvent(String namespaceURI, String localName, String qName, Locator locator) { - this.namespaceURI = namespaceURI; - this.localName = localName; - this.qName = qName; - // locator impl is used to take a snapshot! - this.locator = new LocatorImpl(locator); - } - - public String getLocalName() { - return localName; - } - - public Locator getLocator() { - return locator; - } - - public String getNamespaceURI() { - return namespaceURI; - } - - public String getQName() { - return qName; - } + final public String namespaceURI; + final public String localName; + final public String qName; + final public Locator locator; + + SaxEvent(String namespaceURI, String localName, String qName, Locator locator) { + this.namespaceURI = namespaceURI; + this.localName = localName; + this.qName = qName; + // locator impl is used to take a snapshot! + this.locator = new LocatorImpl(locator); + } + + public String getLocalName() { + return localName; + } + + public Locator getLocator() { + return locator; + } + + public String getNamespaceURI() { + return namespaceURI; + } + + public String getQName() { + return qName; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEventRecorder.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEventRecorder.java index 484c53b9fb233e5c03afbd2cc1b5302bd91bfe6f..fbae0f25f98119889bd30add1e9d4a8e093a7387 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEventRecorder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/SaxEventRecorder.java @@ -40,170 +40,163 @@ import ch.qos.logback.core.status.Status; public class SaxEventRecorder extends DefaultHandler implements ContextAware { - final ContextAwareImpl cai; - - public SaxEventRecorder(Context context) { - cai = new ContextAwareImpl(context, this); - } - - public List saxEventList = new ArrayList(); - Locator locator; - ElementPath globalElementPath = new ElementPath(); - - final public void recordEvents(InputStream inputStream) throws JoranException { - recordEvents(new InputSource(inputStream)); - } - - public List recordEvents(InputSource inputSource) - throws JoranException { - SAXParser saxParser = buildSaxParser(); - try { - saxParser.parse(inputSource, this); - return saxEventList; - } catch (IOException ie) { - handleError("I/O error occurred while parsing xml file", ie); - } catch(SAXException se) { - // Exception added into StatusManager via Sax error handling. No need to add it again - throw new JoranException("Problem parsing XML document. See previously reported errors.", se); - } catch (Exception ex) { - handleError("Unexpected exception while parsing XML document.", ex); - } - throw new IllegalStateException("This point can never be reached"); - } - - private void handleError(String errMsg, Throwable t) throws JoranException { - addError(errMsg, t); - throw new JoranException(errMsg, t); - } - - private SAXParser buildSaxParser() throws JoranException { - try { - SAXParserFactory spf = SAXParserFactory.newInstance(); - spf.setValidating(false); - spf.setNamespaceAware(true); - return spf.newSAXParser(); - } catch (Exception pce) { - String errMsg = "Parser configuration error occurred"; - addError(errMsg, pce); - throw new JoranException(errMsg, pce); - } - } - - public void startDocument() { - } - - public Locator getLocator() { - return locator; - } - - public void setDocumentLocator(Locator l) { - locator = l; - } - - public void startElement(String namespaceURI, String localName, String qName, - Attributes atts) { - - String tagName = getTagName(localName, qName); - globalElementPath.push(tagName); - ElementPath current = globalElementPath.duplicate(); - saxEventList.add(new StartEvent(current, namespaceURI, localName, qName, - atts, getLocator())); - } - - public void characters(char[] ch, int start, int length) { - String bodyStr = new String(ch, start, length); - SaxEvent lastEvent = getLastEvent(); - if (lastEvent instanceof BodyEvent) { - BodyEvent be = (BodyEvent) lastEvent; - be.append(bodyStr); - } else { - // ignore space only text if the previous event is not a BodyEvent - if (!isSpaceOnly(bodyStr)) { - saxEventList.add(new BodyEvent(bodyStr, getLocator())); - } - } - } - - boolean isSpaceOnly(String bodyStr) { - String bodyTrimmed = bodyStr.trim(); - return (bodyTrimmed.length() == 0); - } - - SaxEvent getLastEvent() { - if (saxEventList.isEmpty()) { - return null; - } - int size = saxEventList.size(); - return saxEventList.get(size - 1); - } - - public void endElement(String namespaceURI, String localName, String qName) { - saxEventList - .add(new EndEvent(namespaceURI, localName, qName, getLocator())); - globalElementPath.pop(); - } - - String getTagName(String localName, String qName) { - String tagName = localName; - if ((tagName == null) || (tagName.length() < 1)) { - tagName = qName; - } - return tagName; - } - - public void error(SAXParseException spe) throws SAXException { - addError(XML_PARSING +" - Parsing error on line " + spe.getLineNumber() + " and column " - + spe.getColumnNumber(), spe); - } - - public void fatalError(SAXParseException spe) throws SAXException { - addError(XML_PARSING +" - Parsing fatal error on line " + spe.getLineNumber() - + " and column " + spe.getColumnNumber(), spe); - } - - public void warning(SAXParseException spe) throws SAXException { - addWarn(XML_PARSING +" - Parsing warning on line " + spe.getLineNumber() + " and column " - + spe.getColumnNumber(), spe); - } - - public void addError(String msg) { - cai.addError(msg); - } - - public void addError(String msg, Throwable ex) { - cai.addError(msg, ex); - } - - public void addInfo(String msg) { - cai.addInfo(msg); - } - - public void addInfo(String msg, Throwable ex) { - cai.addInfo(msg, ex); - } - - public void addStatus(Status status) { - cai.addStatus(status); - } - - public void addWarn(String msg) { - cai.addWarn(msg); - } - - public void addWarn(String msg, Throwable ex) { - cai.addWarn(msg, ex); - } - - public Context getContext() { - return cai.getContext(); - } - - public void setContext(Context context) { - cai.setContext(context); - } - - public List getSaxEventList() { - return saxEventList; - } + final ContextAwareImpl cai; + + public SaxEventRecorder(Context context) { + cai = new ContextAwareImpl(context, this); + } + + public List saxEventList = new ArrayList(); + Locator locator; + ElementPath globalElementPath = new ElementPath(); + + final public void recordEvents(InputStream inputStream) throws JoranException { + recordEvents(new InputSource(inputStream)); + } + + public List recordEvents(InputSource inputSource) throws JoranException { + SAXParser saxParser = buildSaxParser(); + try { + saxParser.parse(inputSource, this); + return saxEventList; + } catch (IOException ie) { + handleError("I/O error occurred while parsing xml file", ie); + } catch (SAXException se) { + // Exception added into StatusManager via Sax error handling. No need to add it again + throw new JoranException("Problem parsing XML document. See previously reported errors.", se); + } catch (Exception ex) { + handleError("Unexpected exception while parsing XML document.", ex); + } + throw new IllegalStateException("This point can never be reached"); + } + + private void handleError(String errMsg, Throwable t) throws JoranException { + addError(errMsg, t); + throw new JoranException(errMsg, t); + } + + private SAXParser buildSaxParser() throws JoranException { + try { + SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setValidating(false); + spf.setNamespaceAware(true); + return spf.newSAXParser(); + } catch (Exception pce) { + String errMsg = "Parser configuration error occurred"; + addError(errMsg, pce); + throw new JoranException(errMsg, pce); + } + } + + public void startDocument() { + } + + public Locator getLocator() { + return locator; + } + + public void setDocumentLocator(Locator l) { + locator = l; + } + + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { + + String tagName = getTagName(localName, qName); + globalElementPath.push(tagName); + ElementPath current = globalElementPath.duplicate(); + saxEventList.add(new StartEvent(current, namespaceURI, localName, qName, atts, getLocator())); + } + + public void characters(char[] ch, int start, int length) { + String bodyStr = new String(ch, start, length); + SaxEvent lastEvent = getLastEvent(); + if (lastEvent instanceof BodyEvent) { + BodyEvent be = (BodyEvent) lastEvent; + be.append(bodyStr); + } else { + // ignore space only text if the previous event is not a BodyEvent + if (!isSpaceOnly(bodyStr)) { + saxEventList.add(new BodyEvent(bodyStr, getLocator())); + } + } + } + + boolean isSpaceOnly(String bodyStr) { + String bodyTrimmed = bodyStr.trim(); + return (bodyTrimmed.length() == 0); + } + + SaxEvent getLastEvent() { + if (saxEventList.isEmpty()) { + return null; + } + int size = saxEventList.size(); + return saxEventList.get(size - 1); + } + + public void endElement(String namespaceURI, String localName, String qName) { + saxEventList.add(new EndEvent(namespaceURI, localName, qName, getLocator())); + globalElementPath.pop(); + } + + String getTagName(String localName, String qName) { + String tagName = localName; + if ((tagName == null) || (tagName.length() < 1)) { + tagName = qName; + } + return tagName; + } + + public void error(SAXParseException spe) throws SAXException { + addError(XML_PARSING + " - Parsing error on line " + spe.getLineNumber() + " and column " + spe.getColumnNumber(), spe); + } + + public void fatalError(SAXParseException spe) throws SAXException { + addError(XML_PARSING + " - Parsing fatal error on line " + spe.getLineNumber() + " and column " + spe.getColumnNumber(), spe); + } + + public void warning(SAXParseException spe) throws SAXException { + addWarn(XML_PARSING + " - Parsing warning on line " + spe.getLineNumber() + " and column " + spe.getColumnNumber(), spe); + } + + public void addError(String msg) { + cai.addError(msg); + } + + public void addError(String msg, Throwable ex) { + cai.addError(msg, ex); + } + + public void addInfo(String msg) { + cai.addInfo(msg); + } + + public void addInfo(String msg, Throwable ex) { + cai.addInfo(msg, ex); + } + + public void addStatus(Status status) { + cai.addStatus(status); + } + + public void addWarn(String msg) { + cai.addWarn(msg); + } + + public void addWarn(String msg, Throwable ex) { + cai.addWarn(msg, ex); + } + + public Context getContext() { + return cai.getContext(); + } + + public void setContext(Context context) { + cai.setContext(context); + } + + public List getSaxEventList() { + return saxEventList; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/StartEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/StartEvent.java index a509bc5052a2edade18fd03dce42b2bea4295680..39e6dfba3038360702cdb13658e3c5ff6f991cc8 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/StartEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/StartEvent.java @@ -20,25 +20,23 @@ import org.xml.sax.helpers.AttributesImpl; public class StartEvent extends SaxEvent { - final public Attributes attributes; - final public ElementPath elementPath; - - StartEvent(ElementPath elementPath, String namespaceURI, String localName, String qName, - Attributes attributes, Locator locator) { - super(namespaceURI, localName, qName, locator); - // locator impl is used to take a snapshot! - this.attributes = new AttributesImpl(attributes); - this.elementPath = elementPath; - } + final public Attributes attributes; + final public ElementPath elementPath; - public Attributes getAttributes() { - return attributes; - } + StartEvent(ElementPath elementPath, String namespaceURI, String localName, String qName, Attributes attributes, Locator locator) { + super(namespaceURI, localName, qName, locator); + // locator impl is used to take a snapshot! + this.attributes = new AttributesImpl(attributes); + this.elementPath = elementPath; + } - - @Override - public String toString() { - return "StartEvent("+getQName()+") ["+locator.getLineNumber()+","+locator.getColumnNumber()+"]"; - } + public Attributes getAttributes() { + return attributes; + } + + @Override + public String toString() { + return "StartEvent(" + getQName() + ") [" + locator.getLineNumber() + "," + locator.getColumnNumber() + "]"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/BodyEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/BodyEvent.java index a0f8b57b3dfec041a9a5a9a57538f395d068cb90..39de16baf772dd02a0a879b79096b427943943d9 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/BodyEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/BodyEvent.java @@ -17,25 +17,23 @@ import javax.xml.stream.Location; public class BodyEvent extends StaxEvent { + private String text; - private String text; + BodyEvent(String text, Location location) { + super(null, location); + this.text = text; + } - BodyEvent(String text, Location location) { - super(null, location); - this.text = text; - } + public String getText() { + return text; + } - public String getText() { - return text; - } + void append(String txt) { + text += txt; + } - void append(String txt) { - text += txt; - } - - @Override - public String toString() { - return "BodyEvent(" + getText() + ")" + location.getLineNumber() + "," - + location.getColumnNumber(); - } + @Override + public String toString() { + return "BodyEvent(" + getText() + ")" + location.getLineNumber() + "," + location.getColumnNumber(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/EndEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/EndEvent.java index 6d5a95a0a925e79a06d6e146af74376edb9f065e..94c89c688ccf8514763a19a0471a2b43410894ea 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/EndEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/EndEvent.java @@ -24,14 +24,13 @@ import javax.xml.stream.Location; */ public class EndEvent extends StaxEvent { - public EndEvent(String name, Location location) { - super(name, location); - } - - @Override - public String toString() { - return "EndEvent("+getName()+") ["+location.getLineNumber()+","+location.getColumnNumber()+"]"; - } + public EndEvent(String name, Location location) { + super(name, location); + } + @Override + public String toString() { + return "EndEvent(" + getName() + ") [" + location.getLineNumber() + "," + location.getColumnNumber() + "]"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StartEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StartEvent.java index 23d336bac44eb311c55c13eb8c664868c1f29e10..b848f0d91bf150635b3994f31a9da045ba9c144e 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StartEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StartEvent.java @@ -23,45 +23,45 @@ import java.util.List; public class StartEvent extends StaxEvent { - List attributes; - public ElementPath elementPath; + List attributes; + public ElementPath elementPath; - StartEvent(ElementPath elementPath, String name, Iterator attributeIterator, Location location) { - super(name, location); - populateAttributes(attributeIterator); - this.elementPath = elementPath; - } + StartEvent(ElementPath elementPath, String name, Iterator attributeIterator, Location location) { + super(name, location); + populateAttributes(attributeIterator); + this.elementPath = elementPath; + } - private void populateAttributes(Iterator attributeIterator) { - while (attributeIterator.hasNext()) { - if (attributes == null) { - attributes = new ArrayList(2); - } - attributes.add(attributeIterator.next()); + private void populateAttributes(Iterator attributeIterator) { + while (attributeIterator.hasNext()) { + if (attributes == null) { + attributes = new ArrayList(2); + } + attributes.add(attributeIterator.next()); + } } - } - public ElementPath getElementPath() { - return elementPath; - } + public ElementPath getElementPath() { + return elementPath; + } - public List getAttributeList() { - return attributes; - } + public List getAttributeList() { + return attributes; + } - Attribute getAttributeByName(String name) { - if(attributes == null) - return null; + Attribute getAttributeByName(String name) { + if (attributes == null) + return null; - for(Attribute attr: attributes) { - if(name.equals(attr.getName().getLocalPart())) - return attr; + for (Attribute attr : attributes) { + if (name.equals(attr.getName().getLocalPart())) + return attr; + } + return null; } - return null; - } - @Override - public String toString() { - return "StartEvent(" + getName() + ") [" + location.getLineNumber() + "," + location.getColumnNumber() + "]"; - } + @Override + public String toString() { + return "StartEvent(" + getName() + ") [" + location.getLineNumber() + "," + location.getColumnNumber() + "]"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEvent.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEvent.java index df0874b4a79f9f9f483b02ee9a1d48f0f5eba965..67f241368f482a16336f09d9360d741dd544ce09 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEvent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEvent.java @@ -13,26 +13,25 @@ */ package ch.qos.logback.core.joran.event.stax; - import javax.xml.stream.Location; public class StaxEvent { - final String name; - final Location location; + final String name; + final Location location; - StaxEvent(String name, Location location) { - this.name = name; - this.location = location; + StaxEvent(String name, Location location) { + this.name = name; + this.location = location; - } + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Location getLocation() { - return location; - } + public Location getLocation() { + return location; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorder.java b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorder.java index e5779cf462641bbd1eac1f6327a1df9cab415431..bef8c99c8f9e45126bac725de2f4f18d26207c9a 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorder.java @@ -31,86 +31,86 @@ import java.util.List; public class StaxEventRecorder extends ContextAwareBase { - List eventList = new ArrayList(); - ElementPath globalElementPath = new ElementPath(); + List eventList = new ArrayList(); + ElementPath globalElementPath = new ElementPath(); - public StaxEventRecorder(Context context) { - setContext(context); - } + public StaxEventRecorder(Context context) { + setContext(context); + } - public void recordEvents(InputStream inputStream) throws JoranException { - try { - XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(inputStream); - read(xmlEventReader); - } catch (XMLStreamException e) { - throw new JoranException("Problem parsing XML document. See previously reported errors.", e); + public void recordEvents(InputStream inputStream) throws JoranException { + try { + XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(inputStream); + read(xmlEventReader); + } catch (XMLStreamException e) { + throw new JoranException("Problem parsing XML document. See previously reported errors.", e); + } } - } - public List getEventList() { - return eventList; - } + public List getEventList() { + return eventList; + } - private void read(XMLEventReader xmlEventReader) throws XMLStreamException { - while (xmlEventReader.hasNext()) { - XMLEvent xmlEvent = xmlEventReader.nextEvent(); - switch (xmlEvent.getEventType()) { - case XMLEvent.START_ELEMENT: - addStartElement(xmlEvent); - break; - case XMLEvent.CHARACTERS: - addCharacters(xmlEvent); - break; - case XMLEvent.END_ELEMENT: - addEndEvent(xmlEvent); - break; - default: - break; - } + private void read(XMLEventReader xmlEventReader) throws XMLStreamException { + while (xmlEventReader.hasNext()) { + XMLEvent xmlEvent = xmlEventReader.nextEvent(); + switch (xmlEvent.getEventType()) { + case XMLEvent.START_ELEMENT: + addStartElement(xmlEvent); + break; + case XMLEvent.CHARACTERS: + addCharacters(xmlEvent); + break; + case XMLEvent.END_ELEMENT: + addEndEvent(xmlEvent); + break; + default: + break; + } + } } - } - private void addStartElement(XMLEvent xmlEvent) { - StartElement se = xmlEvent.asStartElement(); - String tagName = se.getName().getLocalPart(); - globalElementPath.push(tagName); - ElementPath current = globalElementPath.duplicate(); - StartEvent startEvent = new StartEvent(current, tagName, se.getAttributes(), se.getLocation()); - eventList.add(startEvent); - } + private void addStartElement(XMLEvent xmlEvent) { + StartElement se = xmlEvent.asStartElement(); + String tagName = se.getName().getLocalPart(); + globalElementPath.push(tagName); + ElementPath current = globalElementPath.duplicate(); + StartEvent startEvent = new StartEvent(current, tagName, se.getAttributes(), se.getLocation()); + eventList.add(startEvent); + } - private void addCharacters(XMLEvent xmlEvent) { - Characters characters = xmlEvent.asCharacters(); - StaxEvent lastEvent = getLastEvent(); + private void addCharacters(XMLEvent xmlEvent) { + Characters characters = xmlEvent.asCharacters(); + StaxEvent lastEvent = getLastEvent(); - if (lastEvent instanceof BodyEvent) { - BodyEvent be = (BodyEvent) lastEvent; - be.append(characters.getData()); - } else { - // ignore space only text if the previous event is not a BodyEvent - if(!characters.isWhiteSpace()) { - BodyEvent bodyEvent = new BodyEvent(characters.getData(), xmlEvent.getLocation()); - eventList.add(bodyEvent); - } + if (lastEvent instanceof BodyEvent) { + BodyEvent be = (BodyEvent) lastEvent; + be.append(characters.getData()); + } else { + // ignore space only text if the previous event is not a BodyEvent + if (!characters.isWhiteSpace()) { + BodyEvent bodyEvent = new BodyEvent(characters.getData(), xmlEvent.getLocation()); + eventList.add(bodyEvent); + } + } } - } - private void addEndEvent(XMLEvent xmlEvent) { - EndElement ee = xmlEvent.asEndElement(); - String tagName = ee.getName().getLocalPart(); - EndEvent endEvent = new EndEvent(tagName, ee.getLocation()); - eventList.add(endEvent); - globalElementPath.pop(); - } + private void addEndEvent(XMLEvent xmlEvent) { + EndElement ee = xmlEvent.asEndElement(); + String tagName = ee.getName().getLocalPart(); + EndEvent endEvent = new EndEvent(tagName, ee.getLocation()); + eventList.add(endEvent); + globalElementPath.pop(); + } - StaxEvent getLastEvent() { - if (eventList.isEmpty()) { - return null; + StaxEvent getLastEvent() { + if (eventList.isEmpty()) { + return null; + } + int size = eventList.size(); + if (size == 0) + return null; + return eventList.get(size - 1); } - int size = eventList.size(); - if(size == 0) - return null; - return eventList.get(size - 1); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/node/ComponentNode.java b/logback-core/src/main/java/ch/qos/logback/core/joran/node/ComponentNode.java index a7973ddce5529abb1e956830c179ebbeba5725c0..6cc9bf1f6db115d8221e9b6d9664bb6d26c05fa1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/node/ComponentNode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/node/ComponentNode.java @@ -13,9 +13,8 @@ */ package ch.qos.logback.core.joran.node; - public class ComponentNode { - String classStr; + String classStr; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ActionException.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ActionException.java index 2daf269c6a8e51457f6b0acbb7a049aa696ba4e3..33477c7ac38f502b116bcba293187a1c4a27903c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ActionException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ActionException.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.joran.spi; - /** * By throwing an exception an action can signal the Interpreter to skip * processing of all the nested (child) elements of the element associated with @@ -23,14 +22,13 @@ package ch.qos.logback.core.joran.spi; */ public class ActionException extends Exception { - - private static final long serialVersionUID = 2743349809995319806L; + private static final long serialVersionUID = 2743349809995319806L; - public ActionException() { - } + public ActionException() { + } - public ActionException(final Throwable rootCause) { - super(rootCause); - } + public ActionException(final Throwable rootCause) { + super(rootCause); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConfigurationWatchList.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConfigurationWatchList.java index 475af5def9f57667e063587230117d1f3f518c02..b2f5e106bdaf5e416f4b55a92a1aac202a53d204 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConfigurationWatchList.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConfigurationWatchList.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.joran.spi; - import ch.qos.logback.core.spi.ContextAwareBase; import java.io.File; @@ -27,69 +26,69 @@ import java.util.List; */ public class ConfigurationWatchList extends ContextAwareBase { - URL mainURL; - List fileWatchList = new ArrayList(); - List lastModifiedList = new ArrayList(); + URL mainURL; + List fileWatchList = new ArrayList(); + List lastModifiedList = new ArrayList(); - public void clear() { - this.mainURL = null; - lastModifiedList.clear(); - fileWatchList.clear(); - } + public void clear() { + this.mainURL = null; + lastModifiedList.clear(); + fileWatchList.clear(); + } - /** - * The mainURL for the configuration file. Null values are allowed. - * @param mainURL - */ - public void setMainURL(URL mainURL) { - // main url can be null - this.mainURL = mainURL; - if (mainURL != null) - addAsFileToWatch(mainURL); - } + /** + * The mainURL for the configuration file. Null values are allowed. + * @param mainURL + */ + public void setMainURL(URL mainURL) { + // main url can be null + this.mainURL = mainURL; + if (mainURL != null) + addAsFileToWatch(mainURL); + } - private void addAsFileToWatch(URL url) { - File file = convertToFile(url); - if (file != null) { - fileWatchList.add(file); - lastModifiedList.add(file.lastModified()); + private void addAsFileToWatch(URL url) { + File file = convertToFile(url); + if (file != null) { + fileWatchList.add(file); + lastModifiedList.add(file.lastModified()); + } } - } - public void addToWatchList(URL url) { - addAsFileToWatch(url); - } + public void addToWatchList(URL url) { + addAsFileToWatch(url); + } - public URL getMainURL() { - return mainURL; - } + public URL getMainURL() { + return mainURL; + } - public List getCopyOfFileWatchList() { - return new ArrayList(fileWatchList); - } + public List getCopyOfFileWatchList() { + return new ArrayList(fileWatchList); + } - public boolean changeDetected() { - int len = fileWatchList.size(); - for (int i = 0; i < len; i++) { - long lastModified = lastModifiedList.get(i); - File file = fileWatchList.get(i); - if (lastModified != file.lastModified()) { - return true; - } + public boolean changeDetected() { + int len = fileWatchList.size(); + for (int i = 0; i < len; i++) { + long lastModified = lastModifiedList.get(i); + File file = fileWatchList.get(i); + if (lastModified != file.lastModified()) { + return true; + } + } + return false; + // return (lastModified != fileToScan.lastModified() && lastModified != SENTINEL); } - return false; - //return (lastModified != fileToScan.lastModified() && lastModified != SENTINEL); - } - @SuppressWarnings("deprecation") - File convertToFile(URL url) { - String protocol = url.getProtocol(); - if ("file".equals(protocol)) { - return new File(URLDecoder.decode(url.getFile())); - } else { - addInfo("URL [" + url + "] is not of type file"); - return null; + @SuppressWarnings("deprecation") + File convertToFile(URL url) { + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + return new File(URLDecoder.decode(url.getFile())); + } else { + addInfo("URL [" + url + "] is not of type file"); + return null; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConsoleTarget.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConsoleTarget.java index 5ef28017c4ee58afd651c351e317f47237f4d342..045f429aadf11ee7cb7f8d9228f3a2b5ec6e81f2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConsoleTarget.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ConsoleTarget.java @@ -26,71 +26,77 @@ import java.io.OutputStream; */ public enum ConsoleTarget { - SystemOut("System.out", new OutputStream() { - @Override - public void write(int b) throws IOException { - System.out.write(b); - } - @Override - public void write(byte b[]) throws IOException { - System.out.write(b); - } - @Override - public void write(byte b[], int off, int len) throws IOException { - System.out.write(b, off, len); - } - @Override - public void flush() throws IOException { - System.out.flush(); - } - }), + SystemOut("System.out", new OutputStream() { + @Override + public void write(int b) throws IOException { + System.out.write(b); + } - SystemErr("System.err", new OutputStream() { - @Override - public void write(int b) throws IOException { - System.err.write(b); + @Override + public void write(byte b[]) throws IOException { + System.out.write(b); + } + + @Override + public void write(byte b[], int off, int len) throws IOException { + System.out.write(b, off, len); + } + + @Override + public void flush() throws IOException { + System.out.flush(); + } + }), + + SystemErr("System.err", new OutputStream() { + @Override + public void write(int b) throws IOException { + System.err.write(b); + } + + @Override + public void write(byte b[]) throws IOException { + System.err.write(b); + } + + @Override + public void write(byte b[], int off, int len) throws IOException { + System.err.write(b, off, len); + } + + @Override + public void flush() throws IOException { + System.err.flush(); + } + }); + + public static ConsoleTarget findByName(String name) { + for (ConsoleTarget target : ConsoleTarget.values()) { + if (target.name.equalsIgnoreCase(name)) { + return target; + } + } + return null; } - @Override - public void write(byte b[]) throws IOException { - System.err.write(b); + + private final String name; + private final OutputStream stream; + + private ConsoleTarget(String name, OutputStream stream) { + this.name = name; + this.stream = stream; } - @Override - public void write(byte b[], int off, int len) throws IOException { - System.err.write(b, off, len); + + public String getName() { + return name; } - @Override - public void flush() throws IOException { - System.err.flush(); + + public OutputStream getStream() { + return stream; } - }); - public static ConsoleTarget findByName(String name) { - for (ConsoleTarget target : ConsoleTarget.values()) { - if (target.name.equalsIgnoreCase(name)) { - return target; - } + @Override + public String toString() { + return name; } - return null; - } - - private final String name; - private final OutputStream stream; - - private ConsoleTarget(String name, OutputStream stream) { - this.name = name; - this.stream = stream; - } - - public String getName() { - return name; - } - - public OutputStream getStream() { - return stream; - } - - @Override - public String toString() { - return name; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultClass.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultClass.java index 3cb386063f329df1a87f13c1b40b5bd37e25c152..552462b96df1b83649e69a168b706bc702cc7a32 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultClass.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultClass.java @@ -21,5 +21,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DefaultClass { - Class value(); + Class value(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistry.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistry.java index 1b3cd6762ab371746da049b21053e229c3cea748..c3444a059efc3d14d9ce19d6ce17f53f44d2a892 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistry.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistry.java @@ -24,30 +24,28 @@ import java.util.Map; */ public class DefaultNestedComponentRegistry { - Map> defaultComponentMap = new HashMap>(); + Map> defaultComponentMap = new HashMap>(); - public void add(Class hostClass, String propertyName, Class componentClass) { - HostClassAndPropertyDouble hpDouble = new HostClassAndPropertyDouble( - hostClass, propertyName.toLowerCase()); - defaultComponentMap.put(hpDouble, componentClass); - } + public void add(Class hostClass, String propertyName, Class componentClass) { + HostClassAndPropertyDouble hpDouble = new HostClassAndPropertyDouble(hostClass, propertyName.toLowerCase()); + defaultComponentMap.put(hpDouble, componentClass); + } - public Class findDefaultComponentType(Class hostClass, String propertyName) { - propertyName = propertyName.toLowerCase(); - while (hostClass != null) { - Class componentClass = oneShotFind(hostClass, propertyName); - if (componentClass != null) { - return componentClass; - } - hostClass = hostClass.getSuperclass(); + public Class findDefaultComponentType(Class hostClass, String propertyName) { + propertyName = propertyName.toLowerCase(); + while (hostClass != null) { + Class componentClass = oneShotFind(hostClass, propertyName); + if (componentClass != null) { + return componentClass; + } + hostClass = hostClass.getSuperclass(); + } + return null; } - return null; - } - private Class oneShotFind(Class hostClass, String propertyName) { - HostClassAndPropertyDouble hpDouble = new HostClassAndPropertyDouble( - hostClass, propertyName); - return defaultComponentMap.get(hpDouble); - } + private Class oneShotFind(Class hostClass, String propertyName) { + HostClassAndPropertyDouble hpDouble = new HostClassAndPropertyDouble(hostClass, propertyName); + return defaultComponentMap.get(hpDouble); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementPath.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementPath.java index feaf166544f5130871f72442adb71435f176be14..c149770c5587bd65991a6b60c113dfb331278f41 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementPath.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementPath.java @@ -23,113 +23,113 @@ import java.util.List; * @since 1.1.0 */ public class ElementPath { - // contains String instances - ArrayList partList = new ArrayList(); - - public ElementPath() { - } - - public ElementPath(List list) { - partList.addAll(list); - } - - /** - * Build an elementPath from a string. - *

- * Note that "/x" is considered equivalent to "x" and to "x/" - */ - public ElementPath(String pathStr) { - if (pathStr == null) { - return; + // contains String instances + ArrayList partList = new ArrayList(); + + public ElementPath() { } - String[] partArray = pathStr.split("/"); - if(partArray == null) return; + public ElementPath(List list) { + partList.addAll(list); + } - for(String part: partArray) { - if(part.length() >0) { - partList.add(part); - } + /** + * Build an elementPath from a string. + *

+ * Note that "/x" is considered equivalent to "x" and to "x/" + */ + public ElementPath(String pathStr) { + if (pathStr == null) { + return; + } + + String[] partArray = pathStr.split("/"); + if (partArray == null) + return; + + for (String part : partArray) { + if (part.length() > 0) { + partList.add(part); + } + } } - } - - public ElementPath duplicate() { - ElementPath p = new ElementPath(); - p.partList.addAll(this.partList); - return p; - } - - // Joran error skipping relies on the equals method - @Override - public boolean equals(Object o) { - if ((o == null) || !(o instanceof ElementPath)) { - return false; + + public ElementPath duplicate() { + ElementPath p = new ElementPath(); + p.partList.addAll(this.partList); + return p; } - ElementPath r = (ElementPath) o; + // Joran error skipping relies on the equals method + @Override + public boolean equals(Object o) { + if ((o == null) || !(o instanceof ElementPath)) { + return false; + } - if (r.size() != size()) { - return false; - } + ElementPath r = (ElementPath) o; - int len = size(); + if (r.size() != size()) { + return false; + } - for (int i = 0; i < len; i++) { - if (!equalityCheck(get(i), r.get(i))) { - return false; - } - } + int len = size(); - // if everything matches, then the two patterns are equal - return true; - } + for (int i = 0; i < len; i++) { + if (!equalityCheck(get(i), r.get(i))) { + return false; + } + } - private boolean equalityCheck(String x, String y) { - return x.equalsIgnoreCase(y); - } + // if everything matches, then the two patterns are equal + return true; + } - public List getCopyOfPartList() { - return new ArrayList(partList); - } + private boolean equalityCheck(String x, String y) { + return x.equalsIgnoreCase(y); + } - public void push(String s) { - partList.add(s); - } + public List getCopyOfPartList() { + return new ArrayList(partList); + } - public String get(int i) { - return (String) partList.get(i); - } + public void push(String s) { + partList.add(s); + } - public void pop() { - if (!partList.isEmpty()) { - partList.remove(partList.size() - 1); + public String get(int i) { + return (String) partList.get(i); } - } - - public String peekLast() { - if (!partList.isEmpty()) { - int size = partList.size(); - return (String) partList.get(size - 1); - } else { - return null; + + public void pop() { + if (!partList.isEmpty()) { + partList.remove(partList.size() - 1); + } } - } - public int size() { - return partList.size(); - } + public String peekLast() { + if (!partList.isEmpty()) { + int size = partList.size(); + return (String) partList.get(size - 1); + } else { + return null; + } + } + public int size() { + return partList.size(); + } - protected String toStableString() { - StringBuilder result = new StringBuilder(); - for (String current : partList) { - result.append("[").append(current).append("]"); + protected String toStableString() { + StringBuilder result = new StringBuilder(); + for (String current : partList) { + result.append("[").append(current).append("]"); + } + return result.toString(); } - return result.toString(); - } - @Override - public String toString() { - return toStableString(); - } + @Override + public String toString() { + return toStableString(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementSelector.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementSelector.java index d19658ccecd5567fa6405907c4bab300948c5269..93a1782dc9d4d4624c1d98b0a33c7fc34e18031c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementSelector.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/ElementSelector.java @@ -27,157 +27,155 @@ import java.util.List; */ public class ElementSelector extends ElementPath { - public ElementSelector() { - super(); - } - - public ElementSelector(List list) { - super(list); - } - - /** - * Build an elementPath from a string. - * - * Note that "/x" is considered equivalent to "x" and to "x/" - * - */ - public ElementSelector(String p) { - super(p); - } - - public boolean fullPathMatch(ElementPath path) { - if (path.size() != size()) { - return false; + public ElementSelector() { + super(); } - int len = size(); - for (int i = 0; i < len; i++) { - if (!equalityCheck(get(i), path.get(i))) { - return false; - } + public ElementSelector(List list) { + super(list); } - // if everything matches, then the two patterns are equal - return true; - } - - /** - * Returns the number of "tail" components that this pattern has in common - * with the pattern p passed as parameter. By "tail" components we mean the - * components at the end of the pattern. - */ - public int getTailMatchLength(ElementPath p) { - if (p == null) { - return 0; - } - - int lSize = this.partList.size(); - int rSize = p.partList.size(); - // no match possible for empty sets - if ((lSize == 0) || (rSize == 0)) { - return 0; + /** + * Build an elementPath from a string. + * + * Note that "/x" is considered equivalent to "x" and to "x/" + * + */ + public ElementSelector(String p) { + super(p); } - int minLen = (lSize <= rSize) ? lSize : rSize; - int match = 0; - - // loop from the end to the front - for (int i = 1; i <= minLen; i++) { - String l = this.partList.get(lSize - i); - String r = p.partList.get(rSize - i); - - if (equalityCheck(l, r)) { - match++; - } else { - break; - } + public boolean fullPathMatch(ElementPath path) { + if (path.size() != size()) { + return false; + } + + int len = size(); + for (int i = 0; i < len; i++) { + if (!equalityCheck(get(i), path.get(i))) { + return false; + } + } + // if everything matches, then the two patterns are equal + return true; } - return match; - } - public boolean isContainedIn(ElementPath p) { - if(p == null) { - return false; + /** + * Returns the number of "tail" components that this pattern has in common + * with the pattern p passed as parameter. By "tail" components we mean the + * components at the end of the pattern. + */ + public int getTailMatchLength(ElementPath p) { + if (p == null) { + return 0; + } + + int lSize = this.partList.size(); + int rSize = p.partList.size(); + + // no match possible for empty sets + if ((lSize == 0) || (rSize == 0)) { + return 0; + } + + int minLen = (lSize <= rSize) ? lSize : rSize; + int match = 0; + + // loop from the end to the front + for (int i = 1; i <= minLen; i++) { + String l = this.partList.get(lSize - i); + String r = p.partList.get(rSize - i); + + if (equalityCheck(l, r)) { + match++; + } else { + break; + } + } + return match; } - return p.toStableString().contains(toStableString()); - } - - - /** - * Returns the number of "prefix" components that this pattern has in common - * with the pattern p passed as parameter. By "prefix" components we mean the - * components at the beginning of the pattern. - */ - public int getPrefixMatchLength(ElementPath p) { - if (p == null) { - return 0; - } - - int lSize = this.partList.size(); - int rSize = p.partList.size(); - // no match possible for empty sets - if ((lSize == 0) || (rSize == 0)) { - return 0; + public boolean isContainedIn(ElementPath p) { + if (p == null) { + return false; + } + return p.toStableString().contains(toStableString()); } - int minLen = (lSize <= rSize) ? lSize : rSize; - int match = 0; - - for (int i = 0; i < minLen; i++) { - String l = this.partList.get(i); - String r = p.partList.get(i); - - if (equalityCheck(l, r)) { - match++; - } else { - break; - } + /** + * Returns the number of "prefix" components that this pattern has in common + * with the pattern p passed as parameter. By "prefix" components we mean the + * components at the beginning of the pattern. + */ + public int getPrefixMatchLength(ElementPath p) { + if (p == null) { + return 0; + } + + int lSize = this.partList.size(); + int rSize = p.partList.size(); + + // no match possible for empty sets + if ((lSize == 0) || (rSize == 0)) { + return 0; + } + + int minLen = (lSize <= rSize) ? lSize : rSize; + int match = 0; + + for (int i = 0; i < minLen; i++) { + String l = this.partList.get(i); + String r = p.partList.get(i); + + if (equalityCheck(l, r)) { + match++; + } else { + break; + } + } + + return match; } - return match; - } - - private boolean equalityCheck(String x, String y) { - return x.equalsIgnoreCase(y); - } - - @Override - public boolean equals(Object o) { - if ((o == null) || !(o instanceof ElementSelector)) { - return false; + private boolean equalityCheck(String x, String y) { + return x.equalsIgnoreCase(y); } - ElementSelector r = (ElementSelector) o; + @Override + public boolean equals(Object o) { + if ((o == null) || !(o instanceof ElementSelector)) { + return false; + } - if (r.size() != size()) { - return false; - } + ElementSelector r = (ElementSelector) o; - int len = size(); + if (r.size() != size()) { + return false; + } - for (int i = 0; i < len; i++) { - if (!equalityCheck(get(i), r.get(i))) { - return false; - } - } - - // if everything matches, then the two patterns are equal - return true; - } + int len = size(); - @Override - public int hashCode() { - int hc = 0; - int len = size(); + for (int i = 0; i < len; i++) { + if (!equalityCheck(get(i), r.get(i))) { + return false; + } + } - for (int i = 0; i < len; i++) { - // make Pattern comparisons case insensitive - // http://jira.qos.ch/browse/LBCORE-76 - hc ^= get(i).toLowerCase().hashCode(); + // if everything matches, then the two patterns are equal + return true; } - return hc; - } + @Override + public int hashCode() { + int hc = 0; + int len = size(); + + for (int i = 0; i < len; i++) { + // make Pattern comparisons case insensitive + // http://jira.qos.ch/browse/LBCORE-76 + hc ^= get(i).toLowerCase().hashCode(); + } + return hc; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/EventPlayer.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/EventPlayer.java index 9280ecc203010a25a135a1e3501de6c0d13c5129..4167513781a2f6e50a8877199c335a47e03b2fa2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/EventPlayer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/EventPlayer.java @@ -23,49 +23,49 @@ import ch.qos.logback.core.joran.event.StartEvent; public class EventPlayer { - final Interpreter interpreter; - List eventList; - int currentIndex; + final Interpreter interpreter; + List eventList; + int currentIndex; - public EventPlayer(Interpreter interpreter) { - this.interpreter = interpreter; - } + public EventPlayer(Interpreter interpreter) { + this.interpreter = interpreter; + } + + /** + * Return a copy of the current event list in the player. + * @return + * @since 0.9.20 + */ + public List getCopyOfPlayerEventList() { + return new ArrayList(eventList); + } - /** - * Return a copy of the current event list in the player. - * @return - * @since 0.9.20 - */ - public List getCopyOfPlayerEventList() { - return new ArrayList(eventList); - } + public void play(List aSaxEventList) { + eventList = aSaxEventList; + SaxEvent se; + for (currentIndex = 0; currentIndex < eventList.size(); currentIndex++) { + se = eventList.get(currentIndex); + + if (se instanceof StartEvent) { + interpreter.startElement((StartEvent) se); + // invoke fireInPlay after startElement processing + interpreter.getInterpretationContext().fireInPlay(se); + } + if (se instanceof BodyEvent) { + // invoke fireInPlay before characters processing + interpreter.getInterpretationContext().fireInPlay(se); + interpreter.characters((BodyEvent) se); + } + if (se instanceof EndEvent) { + // invoke fireInPlay before endElement processing + interpreter.getInterpretationContext().fireInPlay(se); + interpreter.endElement((EndEvent) se); + } + + } + } - public void play(List aSaxEventList) { - eventList = aSaxEventList; - SaxEvent se; - for(currentIndex = 0; currentIndex < eventList.size(); currentIndex++) { - se = eventList.get(currentIndex); - - if(se instanceof StartEvent) { - interpreter.startElement((StartEvent) se); - // invoke fireInPlay after startElement processing - interpreter.getInterpretationContext().fireInPlay(se); - } - if(se instanceof BodyEvent) { - // invoke fireInPlay before characters processing - interpreter.getInterpretationContext().fireInPlay(se); - interpreter.characters((BodyEvent) se); - } - if(se instanceof EndEvent) { - // invoke fireInPlay before endElement processing - interpreter.getInterpretationContext().fireInPlay(se); - interpreter.endElement((EndEvent) se); - } - + public void addEventsDynamically(List eventList, int offset) { + this.eventList.addAll(currentIndex + offset, eventList); } - } - - public void addEventsDynamically(List eventList, int offset) { - this.eventList.addAll(currentIndex+offset, eventList); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/HostClassAndPropertyDouble.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/HostClassAndPropertyDouble.java index 473021f4ae8e23f6d508e3e10b0c7bf692fdad91..f22ae0995b02382c0e984eab8de9b1ab00b161c9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/HostClassAndPropertyDouble.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/HostClassAndPropertyDouble.java @@ -25,52 +25,51 @@ package ch.qos.logback.core.joran.spi; */ public class HostClassAndPropertyDouble { - final Class hostClass; - final String propertyName; + final Class hostClass; + final String propertyName; - public HostClassAndPropertyDouble(Class hostClass, String propertyName) { - this.hostClass = hostClass; - this.propertyName = propertyName; - } + public HostClassAndPropertyDouble(Class hostClass, String propertyName) { + this.hostClass = hostClass; + this.propertyName = propertyName; + } - public Class getHostClass() { - return hostClass; - } + public Class getHostClass() { + return hostClass; + } - public String getPropertyName() { - return propertyName; - } + public String getPropertyName() { + return propertyName; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((hostClass == null) ? 0 : hostClass.hashCode()); - result = prime * result - + ((propertyName == null) ? 0 : propertyName.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((hostClass == null) ? 0 : hostClass.hashCode()); + result = prime * result + ((propertyName == null) ? 0 : propertyName.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final HostClassAndPropertyDouble other = (HostClassAndPropertyDouble) obj; - if (hostClass == null) { - if (other.hostClass != null) - return false; - } else if (!hostClass.equals(other.hostClass)) - return false; - if (propertyName == null) { - if (other.propertyName != null) - return false; - } else if (!propertyName.equals(other.propertyName)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final HostClassAndPropertyDouble other = (HostClassAndPropertyDouble) obj; + if (hostClass == null) { + if (other.hostClass != null) + return false; + } else if (!hostClass.equals(other.hostClass)) + return false; + if (propertyName == null) { + if (other.propertyName != null) + return false; + } else if (!propertyName.equals(other.propertyName)) + return false; + return true; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/InterpretationContext.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/InterpretationContext.java index ecc7404ec0f0812fb7ba46b593efdacb29782e98..72180851ce3745f87f3f5ac04e53f71b9489e7ac 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/InterpretationContext.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/InterpretationContext.java @@ -38,149 +38,144 @@ import ch.qos.logback.core.util.OptionHelper; * * @author Ceki Gülcü */ -public class InterpretationContext extends ContextAwareBase implements - PropertyContainer { - Stack objectStack; - Map objectMap; - Map propertiesMap; - - Interpreter joranInterpreter; - final List listenerList = new ArrayList(); - DefaultNestedComponentRegistry defaultNestedComponentRegistry = new DefaultNestedComponentRegistry(); - - public InterpretationContext(Context context, Interpreter joranInterpreter) { - this.context = context; - this.joranInterpreter = joranInterpreter; - objectStack = new Stack(); - objectMap = new HashMap(5); - propertiesMap = new HashMap(5); - } - - - public DefaultNestedComponentRegistry getDefaultNestedComponentRegistry() { - return defaultNestedComponentRegistry; - } - - public Map getCopyOfPropertyMap() { - return new HashMap(propertiesMap); - } - - void setPropertiesMap(Map propertiesMap) { - this.propertiesMap = propertiesMap; - } - - String updateLocationInfo(String msg) { - Locator locator = joranInterpreter.getLocator(); - - if (locator != null) { - return msg + locator.getLineNumber() + ":" + locator.getColumnNumber(); - } else { - return msg; - } - } - - public Locator getLocator() { - return joranInterpreter.getLocator(); - } - - public Interpreter getJoranInterpreter() { - return joranInterpreter; - } - - public Stack getObjectStack() { - return objectStack; - } - - public boolean isEmpty() { - return objectStack.isEmpty(); - } - - public Object peekObject() { - return objectStack.peek(); - } - - public void pushObject(Object o) { - objectStack.push(o); - } - - public Object popObject() { - return objectStack.pop(); - } - - public Object getObject(int i) { - return objectStack.get(i); - } - - public Map getObjectMap() { - return objectMap; - } - - /** - * Add a property to the properties of this execution context. If the property - * exists already, it is overwritten. - */ - public void addSubstitutionProperty(String key, String value) { - if (key == null || value == null) { - return; - } - // values with leading or trailing spaces are bad. We remove them now. - value = value.trim(); - propertiesMap.put(key, value); - } - - public void addSubstitutionProperties(Properties props) { - if (props == null) { - return; - } - for(Object keyObject: props.keySet()) { - String key = (String) keyObject; - String val = props.getProperty(key); - addSubstitutionProperty(key, val); - } - } - - /** - * If a key is found in propertiesMap then return it. Otherwise, delegate to - * the context. - */ - public String getProperty(String key) { - String v = propertiesMap.get(key); - if (v != null) { - return v; - } else { - return context.getProperty(key); - } - } - - public String subst(String value) { - if (value == null) { - return null; - } - return OptionHelper.substVars(value, this, context); - } - - - - - public boolean isListenerListEmpty() { - return listenerList.isEmpty(); - } - - public void addInPlayListener(InPlayListener ipl) { - if (listenerList.contains(ipl)) { - addWarn("InPlayListener " + ipl + " has been already registered"); - } else { - listenerList.add(ipl); - } - } - - public boolean removeInPlayListener(InPlayListener ipl) { - return listenerList.remove(ipl); - } - - void fireInPlay(SaxEvent event) { - for (InPlayListener ipl : listenerList) { - ipl.inPlay(event); - } - } +public class InterpretationContext extends ContextAwareBase implements PropertyContainer { + Stack objectStack; + Map objectMap; + Map propertiesMap; + + Interpreter joranInterpreter; + final List listenerList = new ArrayList(); + DefaultNestedComponentRegistry defaultNestedComponentRegistry = new DefaultNestedComponentRegistry(); + + public InterpretationContext(Context context, Interpreter joranInterpreter) { + this.context = context; + this.joranInterpreter = joranInterpreter; + objectStack = new Stack(); + objectMap = new HashMap(5); + propertiesMap = new HashMap(5); + } + + public DefaultNestedComponentRegistry getDefaultNestedComponentRegistry() { + return defaultNestedComponentRegistry; + } + + public Map getCopyOfPropertyMap() { + return new HashMap(propertiesMap); + } + + void setPropertiesMap(Map propertiesMap) { + this.propertiesMap = propertiesMap; + } + + String updateLocationInfo(String msg) { + Locator locator = joranInterpreter.getLocator(); + + if (locator != null) { + return msg + locator.getLineNumber() + ":" + locator.getColumnNumber(); + } else { + return msg; + } + } + + public Locator getLocator() { + return joranInterpreter.getLocator(); + } + + public Interpreter getJoranInterpreter() { + return joranInterpreter; + } + + public Stack getObjectStack() { + return objectStack; + } + + public boolean isEmpty() { + return objectStack.isEmpty(); + } + + public Object peekObject() { + return objectStack.peek(); + } + + public void pushObject(Object o) { + objectStack.push(o); + } + + public Object popObject() { + return objectStack.pop(); + } + + public Object getObject(int i) { + return objectStack.get(i); + } + + public Map getObjectMap() { + return objectMap; + } + + /** + * Add a property to the properties of this execution context. If the property + * exists already, it is overwritten. + */ + public void addSubstitutionProperty(String key, String value) { + if (key == null || value == null) { + return; + } + // values with leading or trailing spaces are bad. We remove them now. + value = value.trim(); + propertiesMap.put(key, value); + } + + public void addSubstitutionProperties(Properties props) { + if (props == null) { + return; + } + for (Object keyObject : props.keySet()) { + String key = (String) keyObject; + String val = props.getProperty(key); + addSubstitutionProperty(key, val); + } + } + + /** + * If a key is found in propertiesMap then return it. Otherwise, delegate to + * the context. + */ + public String getProperty(String key) { + String v = propertiesMap.get(key); + if (v != null) { + return v; + } else { + return context.getProperty(key); + } + } + + public String subst(String value) { + if (value == null) { + return null; + } + return OptionHelper.substVars(value, this, context); + } + + public boolean isListenerListEmpty() { + return listenerList.isEmpty(); + } + + public void addInPlayListener(InPlayListener ipl) { + if (listenerList.contains(ipl)) { + addWarn("InPlayListener " + ipl + " has been already registered"); + } else { + listenerList.add(ipl); + } + } + + public boolean removeInPlayListener(InPlayListener ipl) { + return listenerList.remove(ipl); + } + + void fireInPlay(SaxEvent event) { + for (InPlayListener ipl : listenerList) { + ipl.inPlay(event); + } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/Interpreter.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/Interpreter.java index 764b74f016b4a1cff045aec06bb8297d50e70371..72c76393481744479e7f1b9f4ed87699cf6cea81 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/Interpreter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/Interpreter.java @@ -65,270 +65,262 @@ import ch.qos.logback.core.spi.ContextAwareImpl; * */ public class Interpreter { - private static List EMPTY_LIST = new Vector(0); - - final private RuleStore ruleStore; - final private InterpretationContext interpretationContext; - final private ArrayList implicitActions; - final private CAI_WithLocatorSupport cai; - private ElementPath elementPath; - Locator locator; - EventPlayer eventPlayer; - - /** - * The actionListStack contains a list of actions that are executing - * for the given XML element. - * - * A list of actions is pushed by the {link #startElement} and popped by - * {@link #endElement}. - * - */ - Stack> actionListStack; - - /** - * If the skip nested is set, then we skip all its nested elements until it is - * set back to null at when the element's end is reached. - */ - ElementPath skip = null; - - public Interpreter(Context context, RuleStore rs, ElementPath initialElementPath) { - this.cai = new CAI_WithLocatorSupport(context, this); - ruleStore = rs; - interpretationContext = new InterpretationContext(context, this); - implicitActions = new ArrayList(3); - this.elementPath = initialElementPath; - actionListStack = new Stack>(); - eventPlayer = new EventPlayer(this); - } - - public EventPlayer getEventPlayer() { - return eventPlayer; - } - - public void setInterpretationContextPropertiesMap( - Map propertiesMap) { - interpretationContext.setPropertiesMap(propertiesMap); - } - - /** - * @deprecated replaced by {@link #getInterpretationContext()} - */ - public InterpretationContext getExecutionContext() { - return getInterpretationContext(); - } - - public InterpretationContext getInterpretationContext() { - return interpretationContext; - } - - public void startDocument() { - } - - public void startElement(StartEvent se) { - setDocumentLocator(se.getLocator()); - startElement(se.namespaceURI, se.localName, se.qName, se.attributes); - } - - private void startElement(String namespaceURI, String localName, - String qName, Attributes atts) { - - String tagName = getTagName(localName, qName); - elementPath.push(tagName); - - if (skip != null) { - // every startElement pushes an action list - pushEmptyActionList(); - return; + private static List EMPTY_LIST = new Vector(0); + + final private RuleStore ruleStore; + final private InterpretationContext interpretationContext; + final private ArrayList implicitActions; + final private CAI_WithLocatorSupport cai; + private ElementPath elementPath; + Locator locator; + EventPlayer eventPlayer; + + /** + * The actionListStack contains a list of actions that are executing + * for the given XML element. + * + * A list of actions is pushed by the {link #startElement} and popped by + * {@link #endElement}. + * + */ + Stack> actionListStack; + + /** + * If the skip nested is set, then we skip all its nested elements until it is + * set back to null at when the element's end is reached. + */ + ElementPath skip = null; + + public Interpreter(Context context, RuleStore rs, ElementPath initialElementPath) { + this.cai = new CAI_WithLocatorSupport(context, this); + ruleStore = rs; + interpretationContext = new InterpretationContext(context, this); + implicitActions = new ArrayList(3); + this.elementPath = initialElementPath; + actionListStack = new Stack>(); + eventPlayer = new EventPlayer(this); } - List applicableActionList = getApplicableActionList(elementPath, atts); - if (applicableActionList != null) { - actionListStack.add(applicableActionList); - callBeginAction(applicableActionList, tagName, atts); - } else { - // every startElement pushes an action list - pushEmptyActionList(); - String errMsg = "no applicable action for [" + tagName - + "], current ElementPath is [" + elementPath + "]"; - cai.addError(errMsg); + public EventPlayer getEventPlayer() { + return eventPlayer; } - } - /** - * This method is used to - */ - private void pushEmptyActionList() { - actionListStack.add(EMPTY_LIST); - } + public void setInterpretationContextPropertiesMap(Map propertiesMap) { + interpretationContext.setPropertiesMap(propertiesMap); + } - public void characters(BodyEvent be) { + /** + * @deprecated replaced by {@link #getInterpretationContext()} + */ + public InterpretationContext getExecutionContext() { + return getInterpretationContext(); + } - setDocumentLocator(be.locator); + public InterpretationContext getInterpretationContext() { + return interpretationContext; + } + + public void startDocument() { + } - String body = be.getText(); - List applicableActionList = actionListStack.peek(); + public void startElement(StartEvent se) { + setDocumentLocator(se.getLocator()); + startElement(se.namespaceURI, se.localName, se.qName, se.attributes); + } - if (body != null) { - body = body.trim(); - if (body.length() > 0) { - // System.out.println("calling body method with ["+body+ "]"); - callBodyAction(applicableActionList, body); - } + private void startElement(String namespaceURI, String localName, String qName, Attributes atts) { + + String tagName = getTagName(localName, qName); + elementPath.push(tagName); + + if (skip != null) { + // every startElement pushes an action list + pushEmptyActionList(); + return; + } + + List applicableActionList = getApplicableActionList(elementPath, atts); + if (applicableActionList != null) { + actionListStack.add(applicableActionList); + callBeginAction(applicableActionList, tagName, atts); + } else { + // every startElement pushes an action list + pushEmptyActionList(); + String errMsg = "no applicable action for [" + tagName + "], current ElementPath is [" + elementPath + "]"; + cai.addError(errMsg); + } } - } - - public void endElement(EndEvent endEvent) { - setDocumentLocator(endEvent.locator); - endElement(endEvent.namespaceURI, endEvent.localName, endEvent.qName); - } - - private void endElement(String namespaceURI, String localName, String qName) { - // given that an action list is always pushed for every startElement, we - // need - // to always pop for every endElement - List applicableActionList = (List) actionListStack.pop(); - - if (skip != null) { - if (skip.equals(elementPath)) { - skip = null; - } - } else if (applicableActionList != EMPTY_LIST) { - callEndAction(applicableActionList, getTagName(localName, qName)); + + /** + * This method is used to + */ + private void pushEmptyActionList() { + actionListStack.add(EMPTY_LIST); } - // given that we always push, we must also pop the pattern - elementPath.pop(); - } + public void characters(BodyEvent be) { - public Locator getLocator() { - return locator; - } + setDocumentLocator(be.locator); - public void setDocumentLocator(Locator l) { - locator = l; - } + String body = be.getText(); + List applicableActionList = actionListStack.peek(); - String getTagName(String localName, String qName) { - String tagName = localName; + if (body != null) { + body = body.trim(); + if (body.length() > 0) { + // System.out.println("calling body method with ["+body+ "]"); + callBodyAction(applicableActionList, body); + } + } + } + + public void endElement(EndEvent endEvent) { + setDocumentLocator(endEvent.locator); + endElement(endEvent.namespaceURI, endEvent.localName, endEvent.qName); + } - if ((tagName == null) || (tagName.length() < 1)) { - tagName = qName; + private void endElement(String namespaceURI, String localName, String qName) { + // given that an action list is always pushed for every startElement, we + // need + // to always pop for every endElement + List applicableActionList = (List) actionListStack.pop(); + + if (skip != null) { + if (skip.equals(elementPath)) { + skip = null; + } + } else if (applicableActionList != EMPTY_LIST) { + callEndAction(applicableActionList, getTagName(localName, qName)); + } + + // given that we always push, we must also pop the pattern + elementPath.pop(); } - return tagName; - } + public Locator getLocator() { + return locator; + } - public void addImplicitAction(ImplicitAction ia) { - implicitActions.add(ia); - } + public void setDocumentLocator(Locator l) { + locator = l; + } - /** - * Check if any implicit actions are applicable. As soon as an applicable - * action is found, it is returned. Thus, the returned list will have at most - * one element. - */ - List lookupImplicitAction(ElementPath elementPath, Attributes attributes, - InterpretationContext ec) { - int len = implicitActions.size(); + String getTagName(String localName, String qName) { + String tagName = localName; - for (int i = 0; i < len; i++) { - ImplicitAction ia = (ImplicitAction) implicitActions.get(i); + if ((tagName == null) || (tagName.length() < 1)) { + tagName = qName; + } - if (ia.isApplicable(elementPath, attributes, ec)) { - List actionList = new ArrayList(1); - actionList.add(ia); + return tagName; + } - return actionList; - } + public void addImplicitAction(ImplicitAction ia) { + implicitActions.add(ia); } - return null; - } + /** + * Check if any implicit actions are applicable. As soon as an applicable + * action is found, it is returned. Thus, the returned list will have at most + * one element. + */ + List lookupImplicitAction(ElementPath elementPath, Attributes attributes, InterpretationContext ec) { + int len = implicitActions.size(); - /** - * Return the list of applicable patterns for this - */ - List getApplicableActionList(ElementPath elementPath, Attributes attributes) { - List applicableActionList = ruleStore.matchActions(elementPath); + for (int i = 0; i < len; i++) { + ImplicitAction ia = (ImplicitAction) implicitActions.get(i); - // logger.debug("set of applicable patterns: " + applicableActionList); - if (applicableActionList == null) { - applicableActionList = lookupImplicitAction(elementPath, attributes, - interpretationContext); - } + if (ia.isApplicable(elementPath, attributes, ec)) { + List actionList = new ArrayList(1); + actionList.add(ia); - return applicableActionList; - } + return actionList; + } + } - void callBeginAction(List applicableActionList, String tagName, - Attributes atts) { - if (applicableActionList == null) { - return; + return null; } - Iterator i = applicableActionList.iterator(); - while (i.hasNext()) { - Action action = (Action) i.next(); - // now let us invoke the action. We catch and report any eventual - // exceptions - try { - action.begin(interpretationContext, tagName, atts); - } catch (ActionException e) { - skip = elementPath.duplicate(); - cai.addError("ActionException in Action for tag [" + tagName + "]", e); - } catch (RuntimeException e) { - skip = elementPath.duplicate(); - cai.addError("RuntimeException in Action for tag [" + tagName + "]", e); - } - } - } + /** + * Return the list of applicable patterns for this + */ + List getApplicableActionList(ElementPath elementPath, Attributes attributes) { + List applicableActionList = ruleStore.matchActions(elementPath); - private void callBodyAction(List applicableActionList, String body) { - if (applicableActionList == null) { - return; + // logger.debug("set of applicable patterns: " + applicableActionList); + if (applicableActionList == null) { + applicableActionList = lookupImplicitAction(elementPath, attributes, interpretationContext); + } + + return applicableActionList; } - Iterator i = applicableActionList.iterator(); - - while (i.hasNext()) { - Action action = i.next(); - try { - action.body(interpretationContext, body); - } catch (ActionException ae) { - cai - .addError("Exception in end() methd for action [" + action + "]", - ae); - } + + void callBeginAction(List applicableActionList, String tagName, Attributes atts) { + if (applicableActionList == null) { + return; + } + + Iterator i = applicableActionList.iterator(); + while (i.hasNext()) { + Action action = (Action) i.next(); + // now let us invoke the action. We catch and report any eventual + // exceptions + try { + action.begin(interpretationContext, tagName, atts); + } catch (ActionException e) { + skip = elementPath.duplicate(); + cai.addError("ActionException in Action for tag [" + tagName + "]", e); + } catch (RuntimeException e) { + skip = elementPath.duplicate(); + cai.addError("RuntimeException in Action for tag [" + tagName + "]", e); + } + } } - } - private void callEndAction(List applicableActionList, String tagName) { - if (applicableActionList == null) { - return; + private void callBodyAction(List applicableActionList, String body) { + if (applicableActionList == null) { + return; + } + Iterator i = applicableActionList.iterator(); + + while (i.hasNext()) { + Action action = i.next(); + try { + action.body(interpretationContext, body); + } catch (ActionException ae) { + cai.addError("Exception in end() methd for action [" + action + "]", ae); + } + } } - // logger.debug("About to call end actions on node: [" + localName + "]"); - Iterator i = applicableActionList.iterator(); - - while (i.hasNext()) { - Action action = i.next(); - // now let us invoke the end method of the action. We catch and report - // any eventual exceptions - try { - action.end(interpretationContext, tagName); - } catch (ActionException ae) { - // at this point endAction, there is no point in skipping children as - // they have been already processed - cai.addError("ActionException in Action for tag [" + tagName + "]", ae); - } catch (RuntimeException e) { - // no point in setting skip - cai.addError("RuntimeException in Action for tag [" + tagName + "]", e); - } + private void callEndAction(List applicableActionList, String tagName) { + if (applicableActionList == null) { + return; + } + + // logger.debug("About to call end actions on node: [" + localName + "]"); + Iterator i = applicableActionList.iterator(); + + while (i.hasNext()) { + Action action = i.next(); + // now let us invoke the end method of the action. We catch and report + // any eventual exceptions + try { + action.end(interpretationContext, tagName); + } catch (ActionException ae) { + // at this point endAction, there is no point in skipping children as + // they have been already processed + cai.addError("ActionException in Action for tag [" + tagName + "]", ae); + } catch (RuntimeException e) { + // no point in setting skip + cai.addError("RuntimeException in Action for tag [" + tagName + "]", e); + } + } } - } - public RuleStore getRuleStore() { - return ruleStore; - } + public RuleStore getRuleStore() { + return ruleStore; + } } /** @@ -340,19 +332,18 @@ public class Interpreter { */ class CAI_WithLocatorSupport extends ContextAwareImpl { - CAI_WithLocatorSupport(Context context, Interpreter interpreter) { - super(context, interpreter); - } - - @Override - protected Object getOrigin() { - Interpreter i = (Interpreter) super.getOrigin(); - Locator locator = i.locator; - if (locator != null) { - return Interpreter.class.getName() + "@" + locator.getLineNumber() + ":" - + locator.getColumnNumber(); - } else { - return Interpreter.class.getName() + "@NA:NA"; + CAI_WithLocatorSupport(Context context, Interpreter interpreter) { + super(context, interpreter); + } + + @Override + protected Object getOrigin() { + Interpreter i = (Interpreter) super.getOrigin(); + Locator locator = i.locator; + if (locator != null) { + return Interpreter.class.getName() + "@" + locator.getLineNumber() + ":" + locator.getColumnNumber(); + } else { + return Interpreter.class.getName() + "@NA:NA"; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/JoranException.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/JoranException.java index 2d409b61485e2aa144cf8da0b90c2b70ca416c5a..f8b308eb732d2dabe25814e5c259c173b4edbe51 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/JoranException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/JoranException.java @@ -15,13 +15,13 @@ package ch.qos.logback.core.joran.spi; public class JoranException extends Exception { - private static final long serialVersionUID = 1112493363728774021L; + private static final long serialVersionUID = 1112493363728774021L; - public JoranException(String msg) { - super(msg); - } - - public JoranException(String msg, Throwable cause) { - super(msg, cause); - } + public JoranException(String msg) { + super(msg); + } + + public JoranException(String msg, Throwable cause) { + super(msg, cause); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/NoAutoStartUtil.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/NoAutoStartUtil.java index f1604a6d9c3b28a13d0316d3a675561bda748dd8..5bf622575e3e168860f706c35137e9c4975da85c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/NoAutoStartUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/NoAutoStartUtil.java @@ -15,20 +15,20 @@ package ch.qos.logback.core.joran.spi; public class NoAutoStartUtil { - /** - * Returns true if the class of the object 'o' passed as parameter is *not* - * marked with the NoAutoStart annotation. Return true otherwise. - * - * @param o - * @return true for classes not marked with the NoAutoStart annotation - */ - static public boolean notMarkedWithNoAutoStart(Object o) { - if (o == null) { - return false; + /** + * Returns true if the class of the object 'o' passed as parameter is *not* + * marked with the NoAutoStart annotation. Return true otherwise. + * + * @param o + * @return true for classes not marked with the NoAutoStart annotation + */ + static public boolean notMarkedWithNoAutoStart(Object o) { + if (o == null) { + return false; + } + Class clazz = o.getClass(); + NoAutoStart a = clazz.getAnnotation(NoAutoStart.class); + return a == null; } - Class clazz = o.getClass(); - NoAutoStart a = clazz.getAnnotation(NoAutoStart.class); - return a == null; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/RuleStore.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/RuleStore.java index 47d039c0b94009b2e3d733c793ce858bf0c19500..4c3ea2f5236625b461adacecd27470101cc7a936 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/RuleStore.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/RuleStore.java @@ -31,29 +31,28 @@ import ch.qos.logback.core.joran.action.Action; */ public interface RuleStore { - /** - * Add a new rule, given by a pattern and a action class (String). - * - * @param elementSelector - * @param actionClassStr - * @throws ClassNotFoundException - */ - void addRule(ElementSelector elementSelector, String actionClassStr) - throws ClassNotFoundException; + /** + * Add a new rule, given by a pattern and a action class (String). + * + * @param elementSelector + * @param actionClassStr + * @throws ClassNotFoundException + */ + void addRule(ElementSelector elementSelector, String actionClassStr) throws ClassNotFoundException; - /** - * Add a new rule, given by a pattern and an action instance. - * - * @param elementSelector - * @param action - */ - void addRule(ElementSelector elementSelector, Action action); + /** + * Add a new rule, given by a pattern and an action instance. + * + * @param elementSelector + * @param action + */ + void addRule(ElementSelector elementSelector, Action action); - /** - * Return a list of actions matching a pattern. - * - * @param elementPath the path to match for - * @return list of matching actions - */ - List matchActions(ElementPath elementPath); + /** + * Return a list of actions matching a pattern. + * + * @param elementPath the path to match for + * @return list of matching actions + */ + List matchActions(ElementPath elementPath); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/SimpleRuleStore.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/SimpleRuleStore.java index 2a12f27f8674a4e98ecea90d5c20128c92942ee1..6c840a44876b1cebb148266a13bcd30dc2ea8867 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/SimpleRuleStore.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/SimpleRuleStore.java @@ -31,180 +31,177 @@ import ch.qos.logback.core.util.OptionHelper; */ public class SimpleRuleStore extends ContextAwareBase implements RuleStore { - static String KLEENE_STAR = "*"; - - // key: Pattern instance, value: ArrayList containing actions - HashMap> rules = new HashMap>(); - - // public SimpleRuleStore() { - // } - - public SimpleRuleStore(Context context) { - setContext(context); - } - - /** - * Add a new rule, i.e. a pattern, action pair to the rule store.

Note - * that the added action's LoggerRepository will be set in the process. - */ - public void addRule(ElementSelector elementSelector, Action action) { - action.setContext(context); - - List a4p = rules.get(elementSelector); - - if (a4p == null) { - a4p = new ArrayList(); - rules.put(elementSelector, a4p); - } + static String KLEENE_STAR = "*"; - a4p.add(action); - } + // key: Pattern instance, value: ArrayList containing actions + HashMap> rules = new HashMap>(); - public void addRule(ElementSelector elementSelector, String actionClassName) { - Action action = null; + // public SimpleRuleStore() { + // } - try { - action = (Action) OptionHelper.instantiateByClassName(actionClassName, - Action.class, context); - } catch (Exception e) { - addError("Could not instantiate class [" + actionClassName + "]", e); - } - if (action != null) { - addRule(elementSelector, action); + public SimpleRuleStore(Context context) { + setContext(context); } - } - - // exact match has highest priority - // if no exact match, check for suffix (tail) match, i.e matches - // of type */x/y. Suffix match for */x/y has higher priority than match for - // */x - // if no suffix match, check for prefix match, i.e. matches for x/* - // match for x/y/* has higher priority than matches for x/* - - public List matchActions(ElementPath elementPath) { - List actionList; - - if ((actionList = fullPathMatch(elementPath)) != null) { - return actionList; - } else if ((actionList = suffixMatch(elementPath)) != null) { - return actionList; - } else if ((actionList = prefixMatch(elementPath)) != null) { - return actionList; - } else if ((actionList = middleMatch(elementPath)) != null) { - return actionList; - } else { - return null; + + /** + * Add a new rule, i.e. a pattern, action pair to the rule store.

Note + * that the added action's LoggerRepository will be set in the process. + */ + public void addRule(ElementSelector elementSelector, Action action) { + action.setContext(context); + + List a4p = rules.get(elementSelector); + + if (a4p == null) { + a4p = new ArrayList(); + rules.put(elementSelector, a4p); + } + + a4p.add(action); } - } - List fullPathMatch(ElementPath elementPath) { - for (ElementSelector selector : rules.keySet()) { - if(selector.fullPathMatch(elementPath)) - return rules.get(selector); + public void addRule(ElementSelector elementSelector, String actionClassName) { + Action action = null; + + try { + action = (Action) OptionHelper.instantiateByClassName(actionClassName, Action.class, context); + } catch (Exception e) { + addError("Could not instantiate class [" + actionClassName + "]", e); + } + if (action != null) { + addRule(elementSelector, action); + } } - return null; - } - - // Suffix matches are matches of type */x/y - List suffixMatch(ElementPath elementPath) { - int max = 0; - ElementSelector longestMatchingElementSelector = null; - - for (ElementSelector selector : rules.keySet()) { - if (isSuffixPattern(selector)) { - int r = selector.getTailMatchLength(elementPath); - if (r > max) { - max = r; - longestMatchingElementSelector = selector; + + // exact match has highest priority + // if no exact match, check for suffix (tail) match, i.e matches + // of type */x/y. Suffix match for */x/y has higher priority than match for + // */x + // if no suffix match, check for prefix match, i.e. matches for x/* + // match for x/y/* has higher priority than matches for x/* + + public List matchActions(ElementPath elementPath) { + List actionList; + + if ((actionList = fullPathMatch(elementPath)) != null) { + return actionList; + } else if ((actionList = suffixMatch(elementPath)) != null) { + return actionList; + } else if ((actionList = prefixMatch(elementPath)) != null) { + return actionList; + } else if ((actionList = middleMatch(elementPath)) != null) { + return actionList; + } else { + return null; } - } } - if (longestMatchingElementSelector != null) { - return rules.get(longestMatchingElementSelector); - } else { - return null; + List fullPathMatch(ElementPath elementPath) { + for (ElementSelector selector : rules.keySet()) { + if (selector.fullPathMatch(elementPath)) + return rules.get(selector); + } + return null; } - } - - private boolean isSuffixPattern(ElementSelector p) { - return (p.size() > 1) && p.get(0).equals(KLEENE_STAR); - } - - List prefixMatch(ElementPath elementPath) { - int max = 0; - ElementSelector longestMatchingElementSelector = null; - - for (ElementSelector selector : rules.keySet()) { - String last = selector.peekLast(); - if (isKleeneStar(last)) { - int r = selector.getPrefixMatchLength(elementPath); - // to qualify the match length must equal p's size omitting the '*' - if ((r == selector.size() - 1) && (r > max)) { - max = r; - longestMatchingElementSelector = selector; + + // Suffix matches are matches of type */x/y + List suffixMatch(ElementPath elementPath) { + int max = 0; + ElementSelector longestMatchingElementSelector = null; + + for (ElementSelector selector : rules.keySet()) { + if (isSuffixPattern(selector)) { + int r = selector.getTailMatchLength(elementPath); + if (r > max) { + max = r; + longestMatchingElementSelector = selector; + } + } + } + + if (longestMatchingElementSelector != null) { + return rules.get(longestMatchingElementSelector); + } else { + return null; } - } } - if (longestMatchingElementSelector != null) { - return rules.get(longestMatchingElementSelector); - } else { - return null; + private boolean isSuffixPattern(ElementSelector p) { + return (p.size() > 1) && p.get(0).equals(KLEENE_STAR); } - } - - private boolean isKleeneStar(String last) { - return KLEENE_STAR.equals(last); - } - - List middleMatch(ElementPath path) { - - int max = 0; - ElementSelector longestMatchingElementSelector = null; - - for (ElementSelector selector : rules.keySet()) { - String last = selector.peekLast(); - String first = null; - if(selector.size() > 1) { - first = selector.get(0); - } - if (isKleeneStar(last) && isKleeneStar(first)) { - List copyOfPartList = selector.getCopyOfPartList(); - if(copyOfPartList.size() > 2) { - copyOfPartList.remove(0); - copyOfPartList.remove(copyOfPartList.size()-1); - } - - int r = 0; - ElementSelector clone = new ElementSelector(copyOfPartList); - if(clone.isContainedIn(path)) { - r = clone.size(); + + List prefixMatch(ElementPath elementPath) { + int max = 0; + ElementSelector longestMatchingElementSelector = null; + + for (ElementSelector selector : rules.keySet()) { + String last = selector.peekLast(); + if (isKleeneStar(last)) { + int r = selector.getPrefixMatchLength(elementPath); + // to qualify the match length must equal p's size omitting the '*' + if ((r == selector.size() - 1) && (r > max)) { + max = r; + longestMatchingElementSelector = selector; + } + } } - if (r > max) { - max = r; - longestMatchingElementSelector = selector; + + if (longestMatchingElementSelector != null) { + return rules.get(longestMatchingElementSelector); + } else { + return null; } - } } - if (longestMatchingElementSelector != null) { - return rules.get(longestMatchingElementSelector); - } else { - return null; + private boolean isKleeneStar(String last) { + return KLEENE_STAR.equals(last); } - } - - public String toString() { - final String TAB = " "; + List middleMatch(ElementPath path) { + + int max = 0; + ElementSelector longestMatchingElementSelector = null; + + for (ElementSelector selector : rules.keySet()) { + String last = selector.peekLast(); + String first = null; + if (selector.size() > 1) { + first = selector.get(0); + } + if (isKleeneStar(last) && isKleeneStar(first)) { + List copyOfPartList = selector.getCopyOfPartList(); + if (copyOfPartList.size() > 2) { + copyOfPartList.remove(0); + copyOfPartList.remove(copyOfPartList.size() - 1); + } + + int r = 0; + ElementSelector clone = new ElementSelector(copyOfPartList); + if (clone.isContainedIn(path)) { + r = clone.size(); + } + if (r > max) { + max = r; + longestMatchingElementSelector = selector; + } + } + } + + if (longestMatchingElementSelector != null) { + return rules.get(longestMatchingElementSelector); + } else { + return null; + } + } + + public String toString() { + final String TAB = " "; - StringBuilder retValue = new StringBuilder(); + StringBuilder retValue = new StringBuilder(); - retValue.append("SimpleRuleStore ( ").append("rules = ").append(this.rules) - .append(TAB).append(" )"); + retValue.append("SimpleRuleStore ( ").append("rules = ").append(this.rules).append(TAB).append(" )"); - return retValue.toString(); - } + return retValue.toString(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/XMLUtil.java b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/XMLUtil.java index 2611dcd9e4ba466e314f791d17eda1ce415fdb79..07308e31a0befc49849b55f451b2a96355be6a6a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/spi/XMLUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/spi/XMLUtil.java @@ -18,13 +18,12 @@ import java.net.URL; import ch.qos.logback.core.status.StatusManager; public class XMLUtil { - - static public final int ILL_FORMED = 1; - static public final int UNRECOVERABLE_ERROR = 2; - - static public int checkIfWellFormed(URL url, StatusManager sm) { - return 0; - } - + static public final int ILL_FORMED = 1; + static public final int UNRECOVERABLE_ERROR = 2; + + static public int checkIfWellFormed(URL url, StatusManager sm) { + return 0; + } + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/util/ConfigurationWatchListUtil.java b/logback-core/src/main/java/ch/qos/logback/core/joran/util/ConfigurationWatchListUtil.java index 6b0f2b83801a4d6093cc6b78143b8fa4398e8f29..9c5ead607fd6c1d44029601b20aea023ff7cee45 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/util/ConfigurationWatchListUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/util/ConfigurationWatchListUtil.java @@ -28,75 +28,76 @@ import java.net.URL; */ public class ConfigurationWatchListUtil { - final static ConfigurationWatchListUtil origin = new ConfigurationWatchListUtil(); + final static ConfigurationWatchListUtil origin = new ConfigurationWatchListUtil(); - private ConfigurationWatchListUtil() { - } + private ConfigurationWatchListUtil() { + } - public static void setMainWatchURL(Context context, URL url) { - ConfigurationWatchList cwl = getConfigurationWatchList(context); - if (cwl == null) { - cwl = new ConfigurationWatchList(); - cwl.setContext(context); - context.putObject(CoreConstants.CONFIGURATION_WATCH_LIST, cwl); - } else { - cwl.clear(); + public static void setMainWatchURL(Context context, URL url) { + ConfigurationWatchList cwl = getConfigurationWatchList(context); + if (cwl == null) { + cwl = new ConfigurationWatchList(); + cwl.setContext(context); + context.putObject(CoreConstants.CONFIGURATION_WATCH_LIST, cwl); + } else { + cwl.clear(); + } + setConfigurationWatchListResetFlag(context, true); + cwl.setMainURL(url); } - setConfigurationWatchListResetFlag(context, true); - cwl.setMainURL(url); - } - public static URL getMainWatchURL(Context context) { - ConfigurationWatchList cwl = getConfigurationWatchList(context); - if (cwl == null) { - return null; - } else { - return cwl.getMainURL(); + public static URL getMainWatchURL(Context context) { + ConfigurationWatchList cwl = getConfigurationWatchList(context); + if (cwl == null) { + return null; + } else { + return cwl.getMainURL(); + } } - } - public static void addToWatchList(Context context, URL url) { - ConfigurationWatchList cwl = getConfigurationWatchList(context); - if (cwl == null) { - addWarn(context, "Null ConfigurationWatchList. Cannot add " + url); - } else { - addInfo(context, "Adding [" + url + "] to configuration watch list."); - cwl.addToWatchList(url); + public static void addToWatchList(Context context, URL url) { + ConfigurationWatchList cwl = getConfigurationWatchList(context); + if (cwl == null) { + addWarn(context, "Null ConfigurationWatchList. Cannot add " + url); + } else { + addInfo(context, "Adding [" + url + "] to configuration watch list."); + cwl.addToWatchList(url); + } } - } - public static boolean wasConfigurationWatchListReset(Context context) { - Object o = context.getObject(CoreConstants.CONFIGURATION_WATCH_LIST_RESET); - if (o == null) - return false; - else { - return ((Boolean) o).booleanValue(); + public static boolean wasConfigurationWatchListReset(Context context) { + Object o = context.getObject(CoreConstants.CONFIGURATION_WATCH_LIST_RESET); + if (o == null) + return false; + else { + return ((Boolean) o).booleanValue(); + } } - } - public static void setConfigurationWatchListResetFlag(Context context, boolean val) { - context.putObject(CoreConstants.CONFIGURATION_WATCH_LIST_RESET, new Boolean(val)); - } + public static void setConfigurationWatchListResetFlag(Context context, boolean val) { + context.putObject(CoreConstants.CONFIGURATION_WATCH_LIST_RESET, new Boolean(val)); + } - public static ConfigurationWatchList getConfigurationWatchList(Context context) { - return (ConfigurationWatchList) context.getObject(CoreConstants.CONFIGURATION_WATCH_LIST); - } + public static ConfigurationWatchList getConfigurationWatchList(Context context) { + return (ConfigurationWatchList) context.getObject(CoreConstants.CONFIGURATION_WATCH_LIST); + } - static void addStatus(Context context, Status s) { - if (context == null) { - System.out.println("Null context in " + ConfigurationWatchList.class.getName()); - return; + static void addStatus(Context context, Status s) { + if (context == null) { + System.out.println("Null context in " + ConfigurationWatchList.class.getName()); + return; + } + StatusManager sm = context.getStatusManager(); + if (sm == null) + return; + sm.add(s); } - StatusManager sm = context.getStatusManager(); - if (sm == null) return; - sm.add(s); - } - static void addInfo(Context context, String msg) { - addStatus(context, new InfoStatus(msg, origin)); - } + static void addInfo(Context context, String msg) { + addStatus(context, new InfoStatus(msg, origin)); + } - static void addWarn(Context context, String msg) { - addStatus(context, new WarnStatus(msg, origin)); - } + static void addWarn(Context context, String msg) { + addStatus(context, new WarnStatus(msg, origin)); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java b/logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java index d3c839524da25ffe4304c03011375738c1620c79..b5f30bc0085f5d3e036818f4da851ad97d066036 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/util/PropertySetter.java @@ -53,442 +53,421 @@ import ch.qos.logback.core.util.PropertySetterException; */ public class PropertySetter extends ContextAwareBase { - protected Object obj; - protected Class objClass; - protected PropertyDescriptor[] propertyDescriptors; - protected MethodDescriptor[] methodDescriptors; - - /** - * Create a new PropertySetter for the specified Object. This is done in - * preparation for invoking {@link #setProperty} one or more times. - * - * @param obj - * the object for which to set properties - */ - public PropertySetter(Object obj) { - this.obj = obj; - this.objClass = obj.getClass(); - } - - /** - * Uses JavaBeans {@link Introspector} to computer setters of object to be - * configured. - */ - protected void introspect() { - try { - BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); - propertyDescriptors = bi.getPropertyDescriptors(); - methodDescriptors = bi.getMethodDescriptors(); - } catch (IntrospectionException ex) { - addError("Failed to introspect " + obj + ": " + ex.getMessage()); - propertyDescriptors = new PropertyDescriptor[0]; - methodDescriptors = new MethodDescriptor[0]; - } - } - - /** - * Set a property on this PropertySetter's Object. If successful, this method - * will invoke a setter method on the underlying Object. The setter is the one - * for the specified property name and the value is determined partly from the - * setter argument type and partly from the value specified in the call to - * this method. - * - *

- * If the setter expects a String no conversion is necessary. If it expects an - * int, then an attempt is made to convert 'value' to an int using new - * Integer(value). If the setter expects a boolean, the conversion is by new - * Boolean(value). - * - * @param name - * name of the property - * @param value - * String value of the property - */ - public void setProperty(String name, String value) { - if (value == null) { - return; - } - - name = Introspector.decapitalize(name); - - PropertyDescriptor prop = getPropertyDescriptor(name); - - if (prop == null) { - addWarn("No such property [" + name + "] in " + objClass.getName() + "."); - } else { - try { - setProperty(prop, name, value); - } catch (PropertySetterException ex) { - addWarn("Failed to set property [" + name + "] to value \"" + value - + "\". ", ex); - } - } - } - - /** - * Set the named property given a {@link PropertyDescriptor}. - * - * @param prop - * A PropertyDescriptor describing the characteristics of the - * property to set. - * @param name - * The named of the property to set. - * @param value - * The value of the property. - */ - public void setProperty(PropertyDescriptor prop, String name, String value) - throws PropertySetterException { - Method setter = prop.getWriteMethod(); - - if (setter == null) { - throw new PropertySetterException("No setter for property [" + name - + "]."); - } - - Class[] paramTypes = setter.getParameterTypes(); - - if (paramTypes.length != 1) { - throw new PropertySetterException("#params for setter != 1"); - } - - Object arg; - - try { - arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); - } catch (Throwable t) { - throw new PropertySetterException("Conversion to type [" + paramTypes[0] - + "] failed. ", t); - } - - if (arg == null) { - throw new PropertySetterException("Conversion to type [" + paramTypes[0] - + "] failed."); - } - try { - setter.invoke(obj, arg); - } catch (Exception ex) { - throw new PropertySetterException(ex); - } - } - - public AggregationType computeAggregationType(String name) { - String cName = capitalizeFirstLetter(name); - - Method addMethod = findAdderMethod(cName); - - // if the - if (addMethod != null) { - AggregationType type = computeRawAggregationType(addMethod); - switch (type) { - case NOT_FOUND: - return AggregationType.NOT_FOUND; - case AS_BASIC_PROPERTY: - return AggregationType.AS_BASIC_PROPERTY_COLLECTION; - case AS_COMPLEX_PROPERTY: - return AggregationType.AS_COMPLEX_PROPERTY_COLLECTION; - } - } + protected Object obj; + protected Class objClass; + protected PropertyDescriptor[] propertyDescriptors; + protected MethodDescriptor[] methodDescriptors; + + /** + * Create a new PropertySetter for the specified Object. This is done in + * preparation for invoking {@link #setProperty} one or more times. + * + * @param obj + * the object for which to set properties + */ + public PropertySetter(Object obj) { + this.obj = obj; + this.objClass = obj.getClass(); + } + + /** + * Uses JavaBeans {@link Introspector} to computer setters of object to be + * configured. + */ + protected void introspect() { + try { + BeanInfo bi = Introspector.getBeanInfo(obj.getClass()); + propertyDescriptors = bi.getPropertyDescriptors(); + methodDescriptors = bi.getMethodDescriptors(); + } catch (IntrospectionException ex) { + addError("Failed to introspect " + obj + ": " + ex.getMessage()); + propertyDescriptors = new PropertyDescriptor[0]; + methodDescriptors = new MethodDescriptor[0]; + } + } + + /** + * Set a property on this PropertySetter's Object. If successful, this method + * will invoke a setter method on the underlying Object. The setter is the one + * for the specified property name and the value is determined partly from the + * setter argument type and partly from the value specified in the call to + * this method. + * + *

+ * If the setter expects a String no conversion is necessary. If it expects an + * int, then an attempt is made to convert 'value' to an int using new + * Integer(value). If the setter expects a boolean, the conversion is by new + * Boolean(value). + * + * @param name + * name of the property + * @param value + * String value of the property + */ + public void setProperty(String name, String value) { + if (value == null) { + return; + } + + name = Introspector.decapitalize(name); + + PropertyDescriptor prop = getPropertyDescriptor(name); + + if (prop == null) { + addWarn("No such property [" + name + "] in " + objClass.getName() + "."); + } else { + try { + setProperty(prop, name, value); + } catch (PropertySetterException ex) { + addWarn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex); + } + } + } + + /** + * Set the named property given a {@link PropertyDescriptor}. + * + * @param prop + * A PropertyDescriptor describing the characteristics of the + * property to set. + * @param name + * The named of the property to set. + * @param value + * The value of the property. + */ + public void setProperty(PropertyDescriptor prop, String name, String value) throws PropertySetterException { + Method setter = prop.getWriteMethod(); + + if (setter == null) { + throw new PropertySetterException("No setter for property [" + name + "]."); + } + + Class[] paramTypes = setter.getParameterTypes(); + + if (paramTypes.length != 1) { + throw new PropertySetterException("#params for setter != 1"); + } + + Object arg; + + try { + arg = StringToObjectConverter.convertArg(this, value, paramTypes[0]); + } catch (Throwable t) { + throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. ", t); + } + + if (arg == null) { + throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); + } + try { + setter.invoke(obj, arg); + } catch (Exception ex) { + throw new PropertySetterException(ex); + } + } + + public AggregationType computeAggregationType(String name) { + String cName = capitalizeFirstLetter(name); + + Method addMethod = findAdderMethod(cName); + + // if the + if (addMethod != null) { + AggregationType type = computeRawAggregationType(addMethod); + switch (type) { + case NOT_FOUND: + return AggregationType.NOT_FOUND; + case AS_BASIC_PROPERTY: + return AggregationType.AS_BASIC_PROPERTY_COLLECTION; + case AS_COMPLEX_PROPERTY: + return AggregationType.AS_COMPLEX_PROPERTY_COLLECTION; + } + } + + Method setterMethod = findSetterMethod(name); + if (setterMethod != null) { + return computeRawAggregationType(setterMethod); + } else { + // we have failed + return AggregationType.NOT_FOUND; + } + } + + private Method findAdderMethod(String name) { + name = capitalizeFirstLetter(name); + return getMethod("add" + name); + } + + private Method findSetterMethod(String name) { + String dName = Introspector.decapitalize(name); + PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dName); + if (propertyDescriptor != null) { + return propertyDescriptor.getWriteMethod(); + } else { + return null; + } + } + + private Class getParameterClassForMethod(Method method) { + if (method == null) { + return null; + } + Class[] classArray = method.getParameterTypes(); + if (classArray.length != 1) { + return null; + } else { + return classArray[0]; + } + } + + private AggregationType computeRawAggregationType(Method method) { + Class parameterClass = getParameterClassForMethod(method); + if (parameterClass == null) { + return AggregationType.NOT_FOUND; + } + if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { + return AggregationType.AS_BASIC_PROPERTY; + } else { + return AggregationType.AS_COMPLEX_PROPERTY; + } + } + + /** + * Can the given clazz instantiable with certainty? + * + * @param clazz + * The class to test for instantiability + * @return true if clazz can be instantiated, and false otherwise. + */ + private boolean isUnequivocallyInstantiable(Class clazz) { + if (clazz.isInterface()) { + return false; + } + // checking for constructors would be more elegant, but in + // classes without any declared constructors, Class.getConstructor() + // returns null. + Object o; + try { + o = clazz.newInstance(); + if (o != null) { + return true; + } else { + return false; + } + } catch (InstantiationException e) { + return false; + } catch (IllegalAccessException e) { + return false; + } + } + + public Class getObjClass() { + return objClass; + } + + public void addComplexProperty(String name, Object complexProperty) { + Method adderMethod = findAdderMethod(name); + // first let us use the addXXX method + if (adderMethod != null) { + Class[] paramTypes = adderMethod.getParameterTypes(); + if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, complexProperty)) { + return; + } + invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); + } else { + addError("Could not find method [" + "add" + name + "] in class [" + objClass.getName() + "]."); + } + } + + void invokeMethodWithSingleParameterOnThisObject(Method method, Object parameter) { + Class ccc = parameter.getClass(); + try { + method.invoke(this.obj, parameter); + } catch (Exception e) { + addError("Could not invoke method " + method.getName() + " in class " + obj.getClass().getName() + " with parameter of type " + ccc.getName(), e); + } + } + + public void addBasicProperty(String name, String strValue) { + + if (strValue == null) { + return; + } + + name = capitalizeFirstLetter(name); + Method adderMethod = findAdderMethod(name); + + if (adderMethod == null) { + addError("No adder for property [" + name + "]."); + return; + } + + Class[] paramTypes = adderMethod.getParameterTypes(); + isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); + + Object arg; + try { + arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); + } catch (Throwable t) { + addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); + return; + } + if (arg != null) { + invokeMethodWithSingleParameterOnThisObject(adderMethod, strValue); + } + } + + public void setComplexProperty(String name, Object complexProperty) { + String dName = Introspector.decapitalize(name); + PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dName); + + if (propertyDescriptor == null) { + addWarn("Could not find PropertyDescriptor for [" + name + "] in " + objClass.getName()); + + return; + } + + Method setter = propertyDescriptor.getWriteMethod(); + + if (setter == null) { + addWarn("Not setter method for property [" + name + "] in " + obj.getClass().getName()); + + return; + } + + Class[] paramTypes = setter.getParameterTypes(); + + if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { + return; + } + try { + invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); + + } catch (Exception e) { + addError("Could not set component " + obj + " for parent component " + obj, e); + } + } + + private boolean isSanityCheckSuccessful(String name, Method method, Class[] params, Object complexProperty) { + Class ccc = complexProperty.getClass(); + if (params.length != 1) { + addError("Wrong number of parameters in setter method for property [" + name + "] in " + obj.getClass().getName()); - Method setterMethod = findSetterMethod(name); - if (setterMethod != null) { - return computeRawAggregationType(setterMethod); - } else { - // we have failed - return AggregationType.NOT_FOUND; - } - } - - private Method findAdderMethod(String name) { - name = capitalizeFirstLetter(name); - return getMethod("add" + name); - } - - private Method findSetterMethod(String name) { - String dName = Introspector.decapitalize(name); - PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dName); - if (propertyDescriptor != null) { - return propertyDescriptor.getWriteMethod(); - } else { - return null; - } - } + return false; + } - private Class getParameterClassForMethod(Method method) { - if (method == null) { - return null; - } - Class[] classArray = method.getParameterTypes(); - if (classArray.length != 1) { - return null; - } else { - return classArray[0]; - } - } + if (!params[0].isAssignableFrom(complexProperty.getClass())) { + addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" + params[0].getName() + "\" variable."); + addError("The class \"" + params[0].getName() + "\" was loaded by "); + addError("[" + params[0].getClassLoader() + "] whereas object of type "); + addError("\"" + ccc.getName() + "\" was loaded by [" + ccc.getClassLoader() + "]."); + return false; + } - private AggregationType computeRawAggregationType(Method method) { - Class parameterClass = getParameterClassForMethod(method); - if (parameterClass == null) { - return AggregationType.NOT_FOUND; - } - if (StringToObjectConverter.canBeBuiltFromSimpleString(parameterClass)) { - return AggregationType.AS_BASIC_PROPERTY; - } else { - return AggregationType.AS_COMPLEX_PROPERTY; - } - } - - /** - * Can the given clazz instantiable with certainty? - * - * @param clazz - * The class to test for instantiability - * @return true if clazz can be instantiated, and false otherwise. - */ - private boolean isUnequivocallyInstantiable(Class clazz) { - if (clazz.isInterface()) { - return false; - } - // checking for constructors would be more elegant, but in - // classes without any declared constructors, Class.getConstructor() - // returns null. - Object o; - try { - o = clazz.newInstance(); - if (o != null) { return true; - } else { - return false; - } - } catch (InstantiationException e) { - return false; - } catch (IllegalAccessException e) { - return false; - } - } - - public Class getObjClass() { - return objClass; - } - - public void addComplexProperty(String name, Object complexProperty) { - Method adderMethod = findAdderMethod(name); - // first let us use the addXXX method - if (adderMethod != null) { - Class[] paramTypes = adderMethod.getParameterTypes(); - if (!isSanityCheckSuccessful(name, adderMethod, paramTypes, - complexProperty)) { - return; - } - invokeMethodWithSingleParameterOnThisObject(adderMethod, complexProperty); - } else { - addError("Could not find method [" + "add" + name + "] in class [" - + objClass.getName() + "]."); - } - } - - void invokeMethodWithSingleParameterOnThisObject(Method method, - Object parameter) { - Class ccc = parameter.getClass(); - try { - method.invoke(this.obj, parameter); - } catch (Exception e) { - addError("Could not invoke method " + method.getName() + " in class " - + obj.getClass().getName() + " with parameter of type " - + ccc.getName(), e); - } - } - - public void addBasicProperty(String name, String strValue) { - - if (strValue == null) { - return; - } - - name = capitalizeFirstLetter(name); - Method adderMethod = findAdderMethod(name); - - if (adderMethod == null) { - addError("No adder for property [" + name + "]."); - return; - } - - Class[] paramTypes = adderMethod.getParameterTypes(); - isSanityCheckSuccessful(name, adderMethod, paramTypes, strValue); - - Object arg; - try { - arg = StringToObjectConverter.convertArg(this, strValue, paramTypes[0]); - } catch (Throwable t) { - addError("Conversion to type [" + paramTypes[0] + "] failed. ", t); - return; - } - if (arg != null) { - invokeMethodWithSingleParameterOnThisObject(adderMethod, strValue); - } - } - - public void setComplexProperty(String name, Object complexProperty) { - String dName = Introspector.decapitalize(name); - PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dName); - - if (propertyDescriptor == null) { - addWarn("Could not find PropertyDescriptor for [" + name + "] in " - + objClass.getName()); - - return; - } - - Method setter = propertyDescriptor.getWriteMethod(); - - if (setter == null) { - addWarn("Not setter method for property [" + name + "] in " - + obj.getClass().getName()); - - return; } - Class[] paramTypes = setter.getParameterTypes(); - - if (!isSanityCheckSuccessful(name, setter, paramTypes, complexProperty)) { - return; + private String capitalizeFirstLetter(String name) { + return name.substring(0, 1).toUpperCase() + name.substring(1); } - try { - invokeMethodWithSingleParameterOnThisObject(setter, complexProperty); - } catch (Exception e) { - addError("Could not set component " + obj + " for parent component " - + obj, e); - } - } + protected Method getMethod(String methodName) { + if (methodDescriptors == null) { + introspect(); + } - private boolean isSanityCheckSuccessful(String name, Method method, - Class[] params, Object complexProperty) { - Class ccc = complexProperty.getClass(); - if (params.length != 1) { - addError("Wrong number of parameters in setter method for property [" - + name + "] in " + obj.getClass().getName()); + for (int i = 0; i < methodDescriptors.length; i++) { + if (methodName.equals(methodDescriptors[i].getName())) { + return methodDescriptors[i].getMethod(); + } + } - return false; + return null; } - if (!params[0].isAssignableFrom(complexProperty.getClass())) { - addError("A \"" + ccc.getName() + "\" object is not assignable to a \"" - + params[0].getName() + "\" variable."); - addError("The class \"" + params[0].getName() + "\" was loaded by "); - addError("[" + params[0].getClassLoader() + "] whereas object of type "); - addError("\"" + ccc.getName() + "\" was loaded by [" - + ccc.getClassLoader() + "]."); - return false; - } - - return true; - } + protected PropertyDescriptor getPropertyDescriptor(String name) { + if (propertyDescriptors == null) { + introspect(); + } - private String capitalizeFirstLetter(String name) { - return name.substring(0, 1).toUpperCase() + name.substring(1); - } + for (int i = 0; i < propertyDescriptors.length; i++) { + // System.out.println("Comparing " + name + " against " + // + propertyDescriptors[i].getName()); + if (name.equals(propertyDescriptors[i].getName())) { + // System.out.println("matched"); + return propertyDescriptors[i]; + } + } - protected Method getMethod(String methodName) { - if (methodDescriptors == null) { - introspect(); + return null; } - for (int i = 0; i < methodDescriptors.length; i++) { - if (methodName.equals(methodDescriptors[i].getName())) { - return methodDescriptors[i].getMethod(); - } + public Object getObj() { + return obj; } - return null; - } - - protected PropertyDescriptor getPropertyDescriptor(String name) { - if (propertyDescriptors == null) { - introspect(); + Method getRelevantMethod(String name, AggregationType aggregationType) { + String cName = capitalizeFirstLetter(name); + Method relevantMethod; + if (aggregationType == AggregationType.AS_COMPLEX_PROPERTY_COLLECTION) { + relevantMethod = findAdderMethod(cName); + } else if (aggregationType == AggregationType.AS_COMPLEX_PROPERTY) { + relevantMethod = findSetterMethod(cName); + } else { + throw new IllegalStateException(aggregationType + " not allowed here"); + } + return relevantMethod; } - for (int i = 0; i < propertyDescriptors.length; i++) { - // System.out.println("Comparing " + name + " against " - // + propertyDescriptors[i].getName()); - if (name.equals(propertyDescriptors[i].getName())) { - // System.out.println("matched"); - return propertyDescriptors[i]; - } - } + T getAnnotation(String name, Class annonationClass, Method relevantMethod) { - return null; - } - - public Object getObj() { - return obj; - } - - Method getRelevantMethod(String name, AggregationType aggregationType) { - String cName = capitalizeFirstLetter(name); - Method relevantMethod; - if (aggregationType == AggregationType.AS_COMPLEX_PROPERTY_COLLECTION) { - relevantMethod = findAdderMethod(cName); - } else if (aggregationType == AggregationType.AS_COMPLEX_PROPERTY) { - relevantMethod = findSetterMethod(cName); - } else { - throw new IllegalStateException(aggregationType + " not allowed here"); + if (relevantMethod != null) { + return relevantMethod.getAnnotation(annonationClass); + } else { + return null; + } } - return relevantMethod; - } - - T getAnnotation(String name, Class annonationClass, - Method relevantMethod) { - if (relevantMethod != null) { - return relevantMethod.getAnnotation(annonationClass); - } else { - return null; + Class getDefaultClassNameByAnnonation(String name, Method relevantMethod) { + DefaultClass defaultClassAnnon = getAnnotation(name, DefaultClass.class, relevantMethod); + if (defaultClassAnnon != null) { + return defaultClassAnnon.value(); + } + return null; } - } - Class getDefaultClassNameByAnnonation(String name, Method relevantMethod) { - DefaultClass defaultClassAnnon = getAnnotation(name, DefaultClass.class, - relevantMethod); - if (defaultClassAnnon != null) { - return defaultClassAnnon.value(); - } - return null; - } + Class getByConcreteType(String name, Method relevantMethod) { - Class getByConcreteType(String name, Method relevantMethod) { + Class paramType = getParameterClassForMethod(relevantMethod); + if (paramType == null) { + return null; + } - Class paramType = getParameterClassForMethod(relevantMethod); - if (paramType == null) { - return null; - } + boolean isUnequivocallyInstantiable = isUnequivocallyInstantiable(paramType); + if (isUnequivocallyInstantiable) { + return paramType; + } else { + return null; + } - boolean isUnequivocallyInstantiable = isUnequivocallyInstantiable(paramType); - if (isUnequivocallyInstantiable) { - return paramType; - } else { - return null; } - } + public Class getClassNameViaImplicitRules(String name, AggregationType aggregationType, DefaultNestedComponentRegistry registry) { - public Class getClassNameViaImplicitRules(String name, - AggregationType aggregationType, DefaultNestedComponentRegistry registry) { - - Class registryResult = registry.findDefaultComponentType(obj.getClass(), - name); - if (registryResult != null) { - return registryResult; - } - // find the relevant method for the given property name and aggregationType - Method relevantMethod = getRelevantMethod(name, aggregationType); - if (relevantMethod == null) { - return null; - } - Class byAnnotation = getDefaultClassNameByAnnonation(name, relevantMethod); - if (byAnnotation != null) { - return byAnnotation; + Class registryResult = registry.findDefaultComponentType(obj.getClass(), name); + if (registryResult != null) { + return registryResult; + } + // find the relevant method for the given property name and aggregationType + Method relevantMethod = getRelevantMethod(name, aggregationType); + if (relevantMethod == null) { + return null; + } + Class byAnnotation = getDefaultClassNameByAnnonation(name, relevantMethod); + if (byAnnotation != null) { + return byAnnotation; + } + return getByConcreteType(name, relevantMethod); } - return getByConcreteType(name, relevantMethod); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/joran/util/StringToObjectConverter.java b/logback-core/src/main/java/ch/qos/logback/core/joran/util/StringToObjectConverter.java index 5b03a3786a6db1de3d9b5d9df58ae924dd1380ae..c0817fbde476d76f4c321825a3963e2949cc6217 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/joran/util/StringToObjectConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/joran/util/StringToObjectConverter.java @@ -28,110 +28,104 @@ import ch.qos.logback.core.spi.ContextAware; */ public class StringToObjectConverter { - private static final Class[] STING_CLASS_PARAMETER = new Class[] { String.class }; + private static final Class[] STING_CLASS_PARAMETER = new Class[] { String.class }; - static public boolean canBeBuiltFromSimpleString(Class parameterClass) { - Package p = parameterClass.getPackage(); - if (parameterClass.isPrimitive()) { - return true; - } else if (p != null && "java.lang".equals(p.getName())) { - return true; - } else if (followsTheValueOfConvention(parameterClass)) { - return true; - } else if (parameterClass.isEnum()) { - return true; - } else if (isOfTypeCharset(parameterClass)) { - return true; + static public boolean canBeBuiltFromSimpleString(Class parameterClass) { + Package p = parameterClass.getPackage(); + if (parameterClass.isPrimitive()) { + return true; + } else if (p != null && "java.lang".equals(p.getName())) { + return true; + } else if (followsTheValueOfConvention(parameterClass)) { + return true; + } else if (parameterClass.isEnum()) { + return true; + } else if (isOfTypeCharset(parameterClass)) { + return true; + } + return false; } - return false; - } - /** - * Convert val a String parameter to an object of a given type. - */ - @SuppressWarnings("unchecked") - public static Object convertArg(ContextAware ca, String val, Class type) { - if (val == null) { - return null; - } - String v = val.trim(); - if (String.class.isAssignableFrom(type)) { - return v; - } else if (Integer.TYPE.isAssignableFrom(type)) { - return new Integer(v); - } else if (Long.TYPE.isAssignableFrom(type)) { - return new Long(v); - } else if (Float.TYPE.isAssignableFrom(type)) { - return new Float(v); - } else if (Double.TYPE.isAssignableFrom(type)) { - return new Double(v); - } else if (Boolean.TYPE.isAssignableFrom(type)) { - if ("true".equalsIgnoreCase(v)) { - return Boolean.TRUE; - } else if ("false".equalsIgnoreCase(v)) { - return Boolean.FALSE; - } - } else if (type.isEnum()) { - return convertToEnum(ca, v, (Class) type); - } else if (StringToObjectConverter.followsTheValueOfConvention(type)) { - return convertByValueOfMethod(ca, type, v); - } else if (isOfTypeCharset(type)) { - return convertToCharset(ca, val); - } + /** + * Convert val a String parameter to an object of a given type. + */ + @SuppressWarnings("unchecked") + public static Object convertArg(ContextAware ca, String val, Class type) { + if (val == null) { + return null; + } + String v = val.trim(); + if (String.class.isAssignableFrom(type)) { + return v; + } else if (Integer.TYPE.isAssignableFrom(type)) { + return new Integer(v); + } else if (Long.TYPE.isAssignableFrom(type)) { + return new Long(v); + } else if (Float.TYPE.isAssignableFrom(type)) { + return new Float(v); + } else if (Double.TYPE.isAssignableFrom(type)) { + return new Double(v); + } else if (Boolean.TYPE.isAssignableFrom(type)) { + if ("true".equalsIgnoreCase(v)) { + return Boolean.TRUE; + } else if ("false".equalsIgnoreCase(v)) { + return Boolean.FALSE; + } + } else if (type.isEnum()) { + return convertToEnum(ca, v, (Class) type); + } else if (StringToObjectConverter.followsTheValueOfConvention(type)) { + return convertByValueOfMethod(ca, type, v); + } else if (isOfTypeCharset(type)) { + return convertToCharset(ca, val); + } - return null; - } + return null; + } - static private boolean isOfTypeCharset(Class type) { - return Charset.class.isAssignableFrom(type); - } + static private boolean isOfTypeCharset(Class type) { + return Charset.class.isAssignableFrom(type); + } - static private Charset convertToCharset(ContextAware ca, String val) { - try { - return Charset.forName(val); - } catch (UnsupportedCharsetException e) { - ca.addError("Failed to get charset [" + val + "]", e); - return null; + static private Charset convertToCharset(ContextAware ca, String val) { + try { + return Charset.forName(val); + } catch (UnsupportedCharsetException e) { + ca.addError("Failed to get charset [" + val + "]", e); + return null; + } } - } - static private boolean followsTheValueOfConvention(Class parameterClass) { - try { - Method valueOfMethod = parameterClass.getMethod(CoreConstants.VALUE_OF, - STING_CLASS_PARAMETER); - int mod = valueOfMethod.getModifiers(); - if (Modifier.isStatic(mod)) { - return true; - } - } catch (SecurityException e) { - // nop - } catch (NoSuchMethodException e) { - // nop + static private boolean followsTheValueOfConvention(Class parameterClass) { + try { + Method valueOfMethod = parameterClass.getMethod(CoreConstants.VALUE_OF, STING_CLASS_PARAMETER); + int mod = valueOfMethod.getModifiers(); + if (Modifier.isStatic(mod)) { + return true; + } + } catch (SecurityException e) { + // nop + } catch (NoSuchMethodException e) { + // nop + } + return false; } - return false; - } - private static Object convertByValueOfMethod(ContextAware ca, Class type, - String val) { - try { - Method valueOfMethod = type.getMethod(CoreConstants.VALUE_OF, - STING_CLASS_PARAMETER); - return valueOfMethod.invoke(null, val); - } catch (Exception e) { - ca.addError("Failed to invoke " + CoreConstants.VALUE_OF - + "{} method in class [" + type.getName() + "] with value [" + val - + "]"); - return null; + private static Object convertByValueOfMethod(ContextAware ca, Class type, String val) { + try { + Method valueOfMethod = type.getMethod(CoreConstants.VALUE_OF, STING_CLASS_PARAMETER); + return valueOfMethod.invoke(null, val); + } catch (Exception e) { + ca.addError("Failed to invoke " + CoreConstants.VALUE_OF + "{} method in class [" + type.getName() + "] with value [" + val + "]"); + return null; + } } - } - @SuppressWarnings("unchecked") - private static Object convertToEnum(ContextAware ca, String val, - Class enumType) { - return Enum.valueOf(enumType, val); - } + @SuppressWarnings("unchecked") + private static Object convertToEnum(ContextAware ca, String val, Class enumType) { + return Enum.valueOf(enumType, val); + } - boolean isBuildableFromSimpleString() { - return false; - } + boolean isBuildableFromSimpleString() { + return false; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/layout/EchoLayout.java b/logback-core/src/main/java/ch/qos/logback/core/layout/EchoLayout.java index 28899390d4a51a29dbe5cba2171e89e443a6e349..c9ecdea7db456fbd0bb397983f24bb652232f36c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/layout/EchoLayout.java +++ b/logback-core/src/main/java/ch/qos/logback/core/layout/EchoLayout.java @@ -23,8 +23,8 @@ import ch.qos.logback.core.LayoutBase; */ public class EchoLayout extends LayoutBase { - public String doLayout(E event) { - return event+CoreConstants.LINE_SEPARATOR; - } + public String doLayout(E event) { + return event + CoreConstants.LINE_SEPARATOR; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSSLSocketAppender.java b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSSLSocketAppender.java index eafaaa3f20f94ac2da26ac67954ab27056414e4b..251b20ed9d6eac855e5838210e96430f6e9b7245 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSSLSocketAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSSLSocketAppender.java @@ -27,64 +27,61 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; * * @author Carl Harris */ -public abstract class AbstractSSLSocketAppender extends AbstractSocketAppender - implements SSLComponent { +public abstract class AbstractSSLSocketAppender extends AbstractSocketAppender implements SSLComponent { - private SSLConfiguration ssl; - private SocketFactory socketFactory; + private SSLConfiguration ssl; + private SocketFactory socketFactory; - /** - * Constructs a new appender. - */ - protected AbstractSSLSocketAppender() { - } - - /** - * Gets an {@link SocketFactory} that produces SSL sockets using an - * {@link SSLContext} that is derived from the appender's configuration. - * @return socket factory - */ - @Override - protected SocketFactory getSocketFactory() { - return socketFactory; - } + /** + * Constructs a new appender. + */ + protected AbstractSSLSocketAppender() { + } - /** - * {@inheritDoc} - */ - @Override - public void start() { - try { - SSLContext sslContext = getSsl().createContext(this); - SSLParametersConfiguration parameters = getSsl().getParameters(); - parameters.setContext(getContext()); - socketFactory = new ConfigurableSSLSocketFactory(parameters, - sslContext.getSocketFactory()); - super.start(); + /** + * Gets an {@link SocketFactory} that produces SSL sockets using an + * {@link SSLContext} that is derived from the appender's configuration. + * @return socket factory + */ + @Override + protected SocketFactory getSocketFactory() { + return socketFactory; } - catch (Exception ex) { - addError(ex.getMessage(), ex); + + /** + * {@inheritDoc} + */ + @Override + public void start() { + try { + SSLContext sslContext = getSsl().createContext(this); + SSLParametersConfiguration parameters = getSsl().getParameters(); + parameters.setContext(getContext()); + socketFactory = new ConfigurableSSLSocketFactory(parameters, sslContext.getSocketFactory()); + super.start(); + } catch (Exception ex) { + addError(ex.getMessage(), ex); + } } - } - /** - * Gets the SSL configuration. - * @return SSL configuration; if no configuration has been set, a - * default configuration is returned - */ - public SSLConfiguration getSsl() { - if (ssl == null) { - ssl = new SSLConfiguration(); + /** + * Gets the SSL configuration. + * @return SSL configuration; if no configuration has been set, a + * default configuration is returned + */ + public SSLConfiguration getSsl() { + if (ssl == null) { + ssl = new SSLConfiguration(); + } + return ssl; } - return ssl; - } - /** - * Sets the SSL configuration. - * @param ssl the SSL configuration to set - */ - public void setSsl(SSLConfiguration ssl) { - this.ssl = ssl; - } + /** + * Sets the SSL configuration. + * @param ssl the SSL configuration to set + */ + public void setSsl(SSLConfiguration ssl) { + this.ssl = ssl; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java index 229f69167ce9ccbc66c9ffd53f9da0dc5acc7388..9d89980f26674be97628ac13290ca956c7b54d8a 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java @@ -41,364 +41,363 @@ import ch.qos.logback.core.util.Duration; * @author Sebastian Gröbler */ -public abstract class AbstractSocketAppender extends AppenderBase - implements SocketConnector.ExceptionHandler { - - /** - * The default port number of remote logging server (4560). - */ - public static final int DEFAULT_PORT = 4560; - - /** - * The default reconnection delay (30000 milliseconds or 30 seconds). - */ - public static final int DEFAULT_RECONNECTION_DELAY = 30000; - - /** - * Default size of the deque used to hold logging events that are destined - * for the remote peer. - */ - public static final int DEFAULT_QUEUE_SIZE = 128; - - /** - * Default timeout when waiting for the remote server to accept our - * connection. - */ - private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000; - - /** - * Default timeout for how long to wait when inserting an event into - * the BlockingQueue. - */ - private static final int DEFAULT_EVENT_DELAY_TIMEOUT = 100; - - private final ObjectWriterFactory objectWriterFactory; - private final QueueFactory queueFactory; - - private String remoteHost; - private int port = DEFAULT_PORT; - private InetAddress address; - private Duration reconnectionDelay = new Duration(DEFAULT_RECONNECTION_DELAY); - private int queueSize = DEFAULT_QUEUE_SIZE; - private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY; - private Duration eventDelayLimit = new Duration(DEFAULT_EVENT_DELAY_TIMEOUT); - - private BlockingDeque deque; - private String peerId; - private SocketConnector connector; - private Future task; - - private volatile Socket socket; - - /** - * Constructs a new appender. - */ - protected AbstractSocketAppender() { - this(new QueueFactory(), new ObjectWriterFactory()); - } - - /** - * Constructs a new appender using the given {@link QueueFactory} and {@link ObjectWriterFactory}. - */ - AbstractSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { - this.objectWriterFactory = objectWriterFactory; - this.queueFactory = queueFactory; - } - - /** - * {@inheritDoc} - */ - public void start() { - if (isStarted()) return; - int errorCount = 0; - if (port <= 0) { - errorCount++; - addError("No port was configured for appender" - + name - + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_port"); +public abstract class AbstractSocketAppender extends AppenderBase implements SocketConnector.ExceptionHandler { + + /** + * The default port number of remote logging server (4560). + */ + public static final int DEFAULT_PORT = 4560; + + /** + * The default reconnection delay (30000 milliseconds or 30 seconds). + */ + public static final int DEFAULT_RECONNECTION_DELAY = 30000; + + /** + * Default size of the deque used to hold logging events that are destined + * for the remote peer. + */ + public static final int DEFAULT_QUEUE_SIZE = 128; + + /** + * Default timeout when waiting for the remote server to accept our + * connection. + */ + private static final int DEFAULT_ACCEPT_CONNECTION_DELAY = 5000; + + /** + * Default timeout for how long to wait when inserting an event into + * the BlockingQueue. + */ + private static final int DEFAULT_EVENT_DELAY_TIMEOUT = 100; + + private final ObjectWriterFactory objectWriterFactory; + private final QueueFactory queueFactory; + + private String remoteHost; + private int port = DEFAULT_PORT; + private InetAddress address; + private Duration reconnectionDelay = new Duration(DEFAULT_RECONNECTION_DELAY); + private int queueSize = DEFAULT_QUEUE_SIZE; + private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY; + private Duration eventDelayLimit = new Duration(DEFAULT_EVENT_DELAY_TIMEOUT); + + private BlockingDeque deque; + private String peerId; + private SocketConnector connector; + private Future task; + + private volatile Socket socket; + + /** + * Constructs a new appender. + */ + protected AbstractSocketAppender() { + this(new QueueFactory(), new ObjectWriterFactory()); } - if (remoteHost == null) { - errorCount++; - addError("No remote host was configured for appender" - + name - + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host"); + /** + * Constructs a new appender using the given {@link QueueFactory} and {@link ObjectWriterFactory}. + */ + AbstractSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { + this.objectWriterFactory = objectWriterFactory; + this.queueFactory = queueFactory; } - - if (queueSize == 0) { - addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); + + /** + * {@inheritDoc} + */ + public void start() { + if (isStarted()) + return; + int errorCount = 0; + if (port <= 0) { + errorCount++; + addError("No port was configured for appender" + name + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_port"); + } + + if (remoteHost == null) { + errorCount++; + addError("No remote host was configured for appender" + name + + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host"); + } + + if (queueSize == 0) { + addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); + } + + if (queueSize < 0) { + errorCount++; + addError("Queue size must be greater than zero"); + } + + if (errorCount == 0) { + try { + address = InetAddress.getByName(remoteHost); + } catch (UnknownHostException ex) { + addError("unknown host: " + remoteHost); + errorCount++; + } + } + + if (errorCount == 0) { + deque = queueFactory.newLinkedBlockingDeque(queueSize); + peerId = "remote peer " + remoteHost + ":" + port + ": "; + connector = createConnector(address, port, 0, reconnectionDelay.getMilliseconds()); + task = getContext().getExecutorService().submit(new Runnable() { + @Override + public void run() { + connectSocketAndDispatchEvents(); + } + }); + super.start(); + } } - if (queueSize < 0) { - errorCount++; - addError("Queue size must be greater than zero"); + /** + * {@inheritDoc} + */ + @Override + public void stop() { + if (!isStarted()) + return; + CloseUtil.closeQuietly(socket); + task.cancel(true); + super.stop(); } - if (errorCount == 0) { - try { - address = InetAddress.getByName(remoteHost); - } catch (UnknownHostException ex) { - addError("unknown host: " + remoteHost); - errorCount++; - } + /** + * {@inheritDoc} + */ + @Override + protected void append(E event) { + if (event == null || !isStarted()) + return; + + try { + final boolean inserted = deque.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS); + if (!inserted) { + addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded"); + } + } catch (InterruptedException e) { + addError("Interrupted while appending event to SocketAppender", e); + } } - if (errorCount == 0) { - deque = queueFactory.newLinkedBlockingDeque(queueSize); - peerId = "remote peer " + remoteHost + ":" + port + ": "; - connector = createConnector(address, port, 0, reconnectionDelay.getMilliseconds()); - task = getContext().getExecutorService().submit(new Runnable() { - @Override - public void run() { - connectSocketAndDispatchEvents(); + private void connectSocketAndDispatchEvents() { + try { + while (socketConnectionCouldBeEstablished()) { + try { + ObjectWriter objectWriter = createObjectWriterForSocket(); + addInfo(peerId + "connection established"); + dispatchEvents(objectWriter); + } catch (IOException ex) { + addInfo(peerId + "connection failed: " + ex); + } finally { + CloseUtil.closeQuietly(socket); + socket = null; + addInfo(peerId + "connection closed"); + } + } + } catch (InterruptedException ex) { + assert true; // ok... we'll exit now } - }); - super.start(); + addInfo("shutting down"); } - } - - /** - * {@inheritDoc} - */ - @Override - public void stop() { - if (!isStarted()) return; - CloseUtil.closeQuietly(socket); - task.cancel(true); - super.stop(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void append(E event) { - if (event == null || !isStarted()) return; - - try { - final boolean inserted = deque.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS); - if (!inserted) { - addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded"); - } - } catch (InterruptedException e) { - addError("Interrupted while appending event to SocketAppender", e); + + private boolean socketConnectionCouldBeEstablished() throws InterruptedException { + return (socket = connector.call()) != null; } - } - private void connectSocketAndDispatchEvents() { - try { - while (socketConnectionCouldBeEstablished()) { - try { - ObjectWriter objectWriter = createObjectWriterForSocket(); - addInfo(peerId + "connection established"); - dispatchEvents(objectWriter); - } catch (IOException ex) { - addInfo(peerId + "connection failed: " + ex); - } finally { - CloseUtil.closeQuietly(socket); - socket = null; - addInfo(peerId + "connection closed"); + private ObjectWriter createObjectWriterForSocket() throws IOException { + socket.setSoTimeout(acceptConnectionTimeout); + ObjectWriter objectWriter = objectWriterFactory.newAutoFlushingObjectWriter(socket.getOutputStream()); + socket.setSoTimeout(0); + return objectWriter; + } + + private SocketConnector createConnector(InetAddress address, int port, int initialDelay, long retryDelay) { + SocketConnector connector = newConnector(address, port, initialDelay, retryDelay); + connector.setExceptionHandler(this); + connector.setSocketFactory(getSocketFactory()); + return connector; + } + + private void dispatchEvents(ObjectWriter objectWriter) throws InterruptedException, IOException { + while (true) { + E event = deque.takeFirst(); + postProcessEvent(event); + Serializable serializableEvent = getPST().transform(event); + try { + objectWriter.write(serializableEvent); + } catch (IOException e) { + tryReAddingEventToFrontOfQueue(event); + throw e; + } + } + } + + private void tryReAddingEventToFrontOfQueue(E event) { + final boolean wasInserted = deque.offerFirst(event); + if (!wasInserted) { + addInfo("Dropping event due to socket connection error and maxed out deque capacity"); } - } - } catch (InterruptedException ex) { - assert true; // ok... we'll exit now } - addInfo("shutting down"); - } - - private boolean socketConnectionCouldBeEstablished() throws InterruptedException { - return (socket = connector.call()) != null; - } - - private ObjectWriter createObjectWriterForSocket() throws IOException { - socket.setSoTimeout(acceptConnectionTimeout); - ObjectWriter objectWriter = objectWriterFactory.newAutoFlushingObjectWriter(socket.getOutputStream()); - socket.setSoTimeout(0); - return objectWriter; - } - - private SocketConnector createConnector(InetAddress address, int port, int initialDelay, long retryDelay) { - SocketConnector connector = newConnector(address, port, initialDelay, retryDelay); - connector.setExceptionHandler(this); - connector.setSocketFactory(getSocketFactory()); - return connector; - } - - private void dispatchEvents(ObjectWriter objectWriter) throws InterruptedException, IOException { - while (true) { - E event = deque.takeFirst(); - postProcessEvent(event); - Serializable serializableEvent = getPST().transform(event); - try { - objectWriter.write(serializableEvent); - } catch (IOException e) { - tryReAddingEventToFrontOfQueue(event); - throw e; - } + + /** + * {@inheritDoc} + */ + public void connectionFailed(SocketConnector connector, Exception ex) { + if (ex instanceof InterruptedException) { + addInfo("connector interrupted"); + } else if (ex instanceof ConnectException) { + addInfo(peerId + "connection refused"); + } else { + addInfo(peerId + ex); + } + } + + /** + * Creates a new {@link SocketConnector}. + *

+ * The default implementation creates an instance of {@link DefaultSocketConnector}. + * A subclass may override to provide a different {@link SocketConnector} + * implementation. + * + * @param address target remote address + * @param port target remote port + * @param initialDelay delay before the first connection attempt + * @param retryDelay delay before a reconnection attempt + * @return socket connector + */ + protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) { + return new DefaultSocketConnector(address, port, initialDelay, retryDelay); } - } - private void tryReAddingEventToFrontOfQueue(E event) { - final boolean wasInserted = deque.offerFirst(event); - if (!wasInserted) { - addInfo("Dropping event due to socket connection error and maxed out deque capacity"); + /** + * Gets the default {@link SocketFactory} for the platform. + *

+ * Subclasses may override to provide a custom socket factory. + */ + protected SocketFactory getSocketFactory() { + return SocketFactory.getDefault(); } - } - - /** - * {@inheritDoc} - */ - public void connectionFailed(SocketConnector connector, Exception ex) { - if (ex instanceof InterruptedException) { - addInfo("connector interrupted"); - } else if (ex instanceof ConnectException) { - addInfo(peerId + "connection refused"); - } else { - addInfo(peerId + ex); + + /** + * Post-processes an event before it is serialized for delivery to the + * remote receiver. + * @param event the event to post-process + */ + protected abstract void postProcessEvent(E event); + + /** + * Get the pre-serialization transformer that will be used to transform + * each event into a Serializable object before delivery to the remote + * receiver. + * @return transformer object + */ + protected abstract PreSerializationTransformer getPST(); + + /** + * The RemoteHost property takes the name of of the host where a corresponding server is running. + */ + public void setRemoteHost(String host) { + remoteHost = host; + } + + /** + * Returns value of the RemoteHost property. + */ + public String getRemoteHost() { + return remoteHost; + } + + /** + * The Port property takes a positive integer representing the port + * where the server is waiting for connections. + */ + public void setPort(int port) { + this.port = port; + } + + /** + * Returns value of the Port property. + */ + public int getPort() { + return port; + } + + /** + * The reconnectionDelay property takes a positive {@link Duration} value + * representing the time to wait between each failed connection attempt + * to the server. The default value of this option is to 30 seconds. + * + *

+ * Setting this option to zero turns off reconnection capability. + */ + public void setReconnectionDelay(Duration delay) { + this.reconnectionDelay = delay; + } + + /** + * Returns value of the reconnectionDelay property. + */ + public Duration getReconnectionDelay() { + return reconnectionDelay; + } + + /** + * The queueSize property takes a non-negative integer representing + * the number of logging events to retain for delivery to the remote receiver. + * When the deque size is zero, event delivery to the remote receiver is + * synchronous. When the deque size is greater than zero, the + * {@link #append(Object)} method returns immediately after enqueing the + * event, assuming that there is space available in the deque. Using a + * non-zero deque length can improve performance by eliminating delays + * caused by transient network delays. + * + * @param queueSize the deque size to set. + */ + public void setQueueSize(int queueSize) { + this.queueSize = queueSize; + } + + /** + * Returns the value of the queueSize property. + */ + public int getQueueSize() { + return queueSize; + } + + /** + * The eventDelayLimit takes a non-negative integer representing the + * number of milliseconds to allow the appender to block if the underlying + * BlockingQueue is full. Once this limit is reached, the event is dropped. + * + * @param eventDelayLimit the event delay limit + */ + public void setEventDelayLimit(Duration eventDelayLimit) { + this.eventDelayLimit = eventDelayLimit; + } + + /** + * Returns the value of the eventDelayLimit property. + */ + public Duration getEventDelayLimit() { + return eventDelayLimit; + } + + /** + * Sets the timeout that controls how long we'll wait for the remote + * peer to accept our connection attempt. + *

+ * This property is configurable primarily to support instrumentation + * for unit testing. + * + * @param acceptConnectionTimeout timeout value in milliseconds + */ + void setAcceptConnectionTimeout(int acceptConnectionTimeout) { + this.acceptConnectionTimeout = acceptConnectionTimeout; } - } - - /** - * Creates a new {@link SocketConnector}. - *

- * The default implementation creates an instance of {@link DefaultSocketConnector}. - * A subclass may override to provide a different {@link SocketConnector} - * implementation. - * - * @param address target remote address - * @param port target remote port - * @param initialDelay delay before the first connection attempt - * @param retryDelay delay before a reconnection attempt - * @return socket connector - */ - protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) { - return new DefaultSocketConnector(address, port, initialDelay, retryDelay); - } - - /** - * Gets the default {@link SocketFactory} for the platform. - *

- * Subclasses may override to provide a custom socket factory. - */ - protected SocketFactory getSocketFactory() { - return SocketFactory.getDefault(); - } - - /** - * Post-processes an event before it is serialized for delivery to the - * remote receiver. - * @param event the event to post-process - */ - protected abstract void postProcessEvent(E event); - - /** - * Get the pre-serialization transformer that will be used to transform - * each event into a Serializable object before delivery to the remote - * receiver. - * @return transformer object - */ - protected abstract PreSerializationTransformer getPST(); - - /** - * The RemoteHost property takes the name of of the host where a corresponding server is running. - */ - public void setRemoteHost(String host) { - remoteHost = host; - } - - /** - * Returns value of the RemoteHost property. - */ - public String getRemoteHost() { - return remoteHost; - } - - /** - * The Port property takes a positive integer representing the port - * where the server is waiting for connections. - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Returns value of the Port property. - */ - public int getPort() { - return port; - } - - /** - * The reconnectionDelay property takes a positive {@link Duration} value - * representing the time to wait between each failed connection attempt - * to the server. The default value of this option is to 30 seconds. - * - *

- * Setting this option to zero turns off reconnection capability. - */ - public void setReconnectionDelay(Duration delay) { - this.reconnectionDelay = delay; - } - - /** - * Returns value of the reconnectionDelay property. - */ - public Duration getReconnectionDelay() { - return reconnectionDelay; - } - - /** - * The queueSize property takes a non-negative integer representing - * the number of logging events to retain for delivery to the remote receiver. - * When the deque size is zero, event delivery to the remote receiver is - * synchronous. When the deque size is greater than zero, the - * {@link #append(Object)} method returns immediately after enqueing the - * event, assuming that there is space available in the deque. Using a - * non-zero deque length can improve performance by eliminating delays - * caused by transient network delays. - * - * @param queueSize the deque size to set. - */ - public void setQueueSize(int queueSize) { - this.queueSize = queueSize; - } - - /** - * Returns the value of the queueSize property. - */ - public int getQueueSize() { - return queueSize; - } - - /** - * The eventDelayLimit takes a non-negative integer representing the - * number of milliseconds to allow the appender to block if the underlying - * BlockingQueue is full. Once this limit is reached, the event is dropped. - * - * @param eventDelayLimit the event delay limit - */ - public void setEventDelayLimit(Duration eventDelayLimit) { - this.eventDelayLimit = eventDelayLimit; - } - - /** - * Returns the value of the eventDelayLimit property. - */ - public Duration getEventDelayLimit() { - return eventDelayLimit; - } - - /** - * Sets the timeout that controls how long we'll wait for the remote - * peer to accept our connection attempt. - *

- * This property is configurable primarily to support instrumentation - * for unit testing. - * - * @param acceptConnectionTimeout timeout value in milliseconds - */ - void setAcceptConnectionTimeout(int acceptConnectionTimeout) { - this.acceptConnectionTimeout = acceptConnectionTimeout; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java index 2298075c946ec46b647b82df17321ccddd440ae2..6a781b75b0389e0bbfcee55fc2451864332bf326 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java @@ -24,37 +24,37 @@ import java.io.ObjectOutputStream; */ public class AutoFlushingObjectWriter implements ObjectWriter { - private final ObjectOutputStream objectOutputStream; - private final int resetFrequency; - private int writeCounter = 0; + private final ObjectOutputStream objectOutputStream; + private final int resetFrequency; + private int writeCounter = 0; - /** - * Creates a new instance for the given {@link java.io.ObjectOutputStream}. - * - * @param objectOutputStream the stream to write to - * @param resetFrequency the frequency with which the given stream will be - * automatically reset to prevent a memory leak - */ - public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) { - this.objectOutputStream = objectOutputStream; - this.resetFrequency = resetFrequency; - } + /** + * Creates a new instance for the given {@link java.io.ObjectOutputStream}. + * + * @param objectOutputStream the stream to write to + * @param resetFrequency the frequency with which the given stream will be + * automatically reset to prevent a memory leak + */ + public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) { + this.objectOutputStream = objectOutputStream; + this.resetFrequency = resetFrequency; + } - @Override - public void write(Object object) throws IOException { - objectOutputStream.writeObject(object); - objectOutputStream.flush(); - preventMemoryLeak(); - } + @Override + public void write(Object object) throws IOException { + objectOutputStream.writeObject(object); + objectOutputStream.flush(); + preventMemoryLeak(); + } - /** - * Failing to reset the object output stream every now and then creates a serious memory leak which - * is why the underlying stream will be reset according to the {@code resetFrequency}. - */ - private void preventMemoryLeak() throws IOException { - if (++writeCounter >= resetFrequency) { - objectOutputStream.reset(); - writeCounter = 0; + /** + * Failing to reset the object output stream every now and then creates a serious memory leak which + * is why the underlying stream will be reset according to the {@code resetFrequency}. + */ + private void preventMemoryLeak() throws IOException { + if (++writeCounter >= resetFrequency) { + objectOutputStream.reset(); + writeCounter = 0; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/DefaultSocketConnector.java b/logback-core/src/main/java/ch/qos/logback/core/net/DefaultSocketConnector.java index 6fe92f6780633ac9f78278bdb2cf75396a399c27..426777b890c370d6dded41525eda5d6129e7479a 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/net/DefaultSocketConnector.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/DefaultSocketConnector.java @@ -30,96 +30,94 @@ import ch.qos.logback.core.util.FixedDelay; */ public class DefaultSocketConnector implements SocketConnector { - private final InetAddress address; - private final int port; - private final DelayStrategy delayStrategy; - - private ExceptionHandler exceptionHandler; - private SocketFactory socketFactory; - - /** - * Constructs a new connector. - * - * @param address address of remote listener - * @param port port of remote listener - * @param initialDelay delay before initial connection attempt - * @param retryDelay delay after failed connection attempt - */ - public DefaultSocketConnector(InetAddress address, int port, - long initialDelay, long retryDelay) { - this(address, port, new FixedDelay(initialDelay, retryDelay)); - } - - /** - * Constructs a new connector. - * - * @param address address of remote listener - * @param port port of remote listener - * @param delayStrategy strategy for choosing the delay to impose before - * each connection attempt - */ - public DefaultSocketConnector(InetAddress address, int port, - DelayStrategy delayStrategy) { - this.address = address; - this.port = port; - this.delayStrategy = delayStrategy; - } - - /** - * Loops until the desired connection is established and returns the resulting connector. - */ - public Socket call() throws InterruptedException { - useDefaultsForMissingFields(); - Socket socket = createSocket(); - while (socket == null && !Thread.currentThread().isInterrupted()) { - Thread.sleep(delayStrategy.nextDelay()); - socket = createSocket(); + private final InetAddress address; + private final int port; + private final DelayStrategy delayStrategy; + + private ExceptionHandler exceptionHandler; + private SocketFactory socketFactory; + + /** + * Constructs a new connector. + * + * @param address address of remote listener + * @param port port of remote listener + * @param initialDelay delay before initial connection attempt + * @param retryDelay delay after failed connection attempt + */ + public DefaultSocketConnector(InetAddress address, int port, long initialDelay, long retryDelay) { + this(address, port, new FixedDelay(initialDelay, retryDelay)); } - return socket; - } - - private Socket createSocket() { - Socket newSocket = null; - try { - newSocket = socketFactory.createSocket(address, port); - } catch (IOException ioex) { - exceptionHandler.connectionFailed(this, ioex); + + /** + * Constructs a new connector. + * + * @param address address of remote listener + * @param port port of remote listener + * @param delayStrategy strategy for choosing the delay to impose before + * each connection attempt + */ + public DefaultSocketConnector(InetAddress address, int port, DelayStrategy delayStrategy) { + this.address = address; + this.port = port; + this.delayStrategy = delayStrategy; + } + + /** + * Loops until the desired connection is established and returns the resulting connector. + */ + public Socket call() throws InterruptedException { + useDefaultsForMissingFields(); + Socket socket = createSocket(); + while (socket == null && !Thread.currentThread().isInterrupted()) { + Thread.sleep(delayStrategy.nextDelay()); + socket = createSocket(); + } + return socket; + } + + private Socket createSocket() { + Socket newSocket = null; + try { + newSocket = socketFactory.createSocket(address, port); + } catch (IOException ioex) { + exceptionHandler.connectionFailed(this, ioex); + } + return newSocket; } - return newSocket; - } - private void useDefaultsForMissingFields() { - if (exceptionHandler == null) { - exceptionHandler = new ConsoleExceptionHandler(); + private void useDefaultsForMissingFields() { + if (exceptionHandler == null) { + exceptionHandler = new ConsoleExceptionHandler(); + } + if (socketFactory == null) { + socketFactory = SocketFactory.getDefault(); + } } - if (socketFactory == null) { - socketFactory = SocketFactory.getDefault(); + + /** + * {@inheritDoc} + */ + public void setExceptionHandler(ExceptionHandler exceptionHandler) { + this.exceptionHandler = exceptionHandler; } - } - - /** - * {@inheritDoc} - */ - public void setExceptionHandler(ExceptionHandler exceptionHandler) { - this.exceptionHandler = exceptionHandler; - } - - /** - * {@inheritDoc} - */ - public void setSocketFactory(SocketFactory socketFactory) { - this.socketFactory = socketFactory; - } - - /** - * A default {@link ExceptionHandler} that writes to {@code System.out} - */ - private static class ConsoleExceptionHandler implements ExceptionHandler { - - public void connectionFailed(SocketConnector connector, Exception ex) { - System.out.println(ex); + + /** + * {@inheritDoc} + */ + public void setSocketFactory(SocketFactory socketFactory) { + this.socketFactory = socketFactory; } - } + /** + * A default {@link ExceptionHandler} that writes to {@code System.out} + */ + private static class ConsoleExceptionHandler implements ExceptionHandler { + + public void connectionFailed(SocketConnector connector, Exception ex) { + System.out.println(ex); + } + + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/JMSAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/net/JMSAppenderBase.java index 537f5dac52443080f3137b48ac768276daca945f..78110bfe9a263df8b228e6323dc9b0b5467caf87 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/JMSAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/JMSAppenderBase.java @@ -35,143 +35,137 @@ import ch.qos.logback.core.AppenderBase; */ public abstract class JMSAppenderBase extends AppenderBase { - protected String securityPrincipalName; - protected String securityCredentials; - protected String initialContextFactoryName; - protected String urlPkgPrefixes; - protected String providerURL; - protected String userName; - protected String password; - - - protected Object lookup(Context ctx, String name) throws NamingException { - try { - return ctx.lookup(name); - } catch (NameNotFoundException e) { - addError("Could not find name [" + name + "]."); - throw e; - } - } - - public Context buildJNDIContext() throws NamingException { - Context jndi = null; - - // addInfo("Getting initial context."); - if (initialContextFactoryName != null) { - Properties env = buildEnvProperties(); - jndi = new InitialContext(env); - } else { - jndi = new InitialContext(); - } - return jndi; - } - - public Properties buildEnvProperties() { - Properties env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); - if (providerURL != null) { - env.put(Context.PROVIDER_URL, providerURL); - } else { - addWarn("You have set InitialContextFactoryName option but not the " - + "ProviderURL. This is likely to cause problems."); - } - if (urlPkgPrefixes != null) { - env.put(Context.URL_PKG_PREFIXES, urlPkgPrefixes); - } - - if (securityPrincipalName != null) { - env.put(Context.SECURITY_PRINCIPAL, securityPrincipalName); - if (securityCredentials != null) { - env.put(Context.SECURITY_CREDENTIALS, securityCredentials); - } else { - addWarn("You have set SecurityPrincipalName option but not the " - + "SecurityCredentials. This is likely to cause problems."); - } - } - return env; - } - - - - /** - * Returns the value of the InitialContextFactoryName option. See - * {@link #setInitialContextFactoryName} for more details on the meaning of - * this option. - */ - public String getInitialContextFactoryName() { - return initialContextFactoryName; - } - - /** - * Setting the InitialContextFactoryName method will cause this - * JMSAppender instance to use the {@link - * InitialContext#InitialContext(Hashtable)} method instead of the no-argument - * constructor. If you set this option, you should also at least set the - * ProviderURL option. - * - *

- * See also {@link #setProviderURL(String)}. - */ - public void setInitialContextFactoryName(String initialContextFactoryName) { - this.initialContextFactoryName = initialContextFactoryName; - } - - public String getProviderURL() { - return providerURL; - } - - public void setProviderURL(String providerURL) { - this.providerURL = providerURL; - } - - public String getURLPkgPrefixes() { - return urlPkgPrefixes; - } - - public void setURLPkgPrefixes(String urlPkgPrefixes) { - this.urlPkgPrefixes = urlPkgPrefixes; - } - - public String getSecurityCredentials() { - return securityCredentials; - } - - public void setSecurityCredentials(String securityCredentials) { - this.securityCredentials = securityCredentials; - } - - public String getSecurityPrincipalName() { - return securityPrincipalName; - } - - public void setSecurityPrincipalName(String securityPrincipalName) { - this.securityPrincipalName = securityPrincipalName; - } - - public String getUserName() { - return userName; - } - - /** - * The user name to use when {@link - * javax.jms.TopicConnectionFactory#createTopicConnection(String, String)} - * creating a topic session}. If you set this option, you should also set the - * Password option. See {@link #setPassword(String)}. - */ - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - /** - * The password to use when creating a topic session. - */ - public void setPassword(String password) { - this.password = password; - } - - + protected String securityPrincipalName; + protected String securityCredentials; + protected String initialContextFactoryName; + protected String urlPkgPrefixes; + protected String providerURL; + protected String userName; + protected String password; + + protected Object lookup(Context ctx, String name) throws NamingException { + try { + return ctx.lookup(name); + } catch (NameNotFoundException e) { + addError("Could not find name [" + name + "]."); + throw e; + } + } + + public Context buildJNDIContext() throws NamingException { + Context jndi = null; + + // addInfo("Getting initial context."); + if (initialContextFactoryName != null) { + Properties env = buildEnvProperties(); + jndi = new InitialContext(env); + } else { + jndi = new InitialContext(); + } + return jndi; + } + + public Properties buildEnvProperties() { + Properties env = new Properties(); + env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); + if (providerURL != null) { + env.put(Context.PROVIDER_URL, providerURL); + } else { + addWarn("You have set InitialContextFactoryName option but not the " + "ProviderURL. This is likely to cause problems."); + } + if (urlPkgPrefixes != null) { + env.put(Context.URL_PKG_PREFIXES, urlPkgPrefixes); + } + + if (securityPrincipalName != null) { + env.put(Context.SECURITY_PRINCIPAL, securityPrincipalName); + if (securityCredentials != null) { + env.put(Context.SECURITY_CREDENTIALS, securityCredentials); + } else { + addWarn("You have set SecurityPrincipalName option but not the " + "SecurityCredentials. This is likely to cause problems."); + } + } + return env; + } + + /** + * Returns the value of the InitialContextFactoryName option. See + * {@link #setInitialContextFactoryName} for more details on the meaning of + * this option. + */ + public String getInitialContextFactoryName() { + return initialContextFactoryName; + } + + /** + * Setting the InitialContextFactoryName method will cause this + * JMSAppender instance to use the {@link + * InitialContext#InitialContext(Hashtable)} method instead of the no-argument + * constructor. If you set this option, you should also at least set the + * ProviderURL option. + * + *

+ * See also {@link #setProviderURL(String)}. + */ + public void setInitialContextFactoryName(String initialContextFactoryName) { + this.initialContextFactoryName = initialContextFactoryName; + } + + public String getProviderURL() { + return providerURL; + } + + public void setProviderURL(String providerURL) { + this.providerURL = providerURL; + } + + public String getURLPkgPrefixes() { + return urlPkgPrefixes; + } + + public void setURLPkgPrefixes(String urlPkgPrefixes) { + this.urlPkgPrefixes = urlPkgPrefixes; + } + + public String getSecurityCredentials() { + return securityCredentials; + } + + public void setSecurityCredentials(String securityCredentials) { + this.securityCredentials = securityCredentials; + } + + public String getSecurityPrincipalName() { + return securityPrincipalName; + } + + public void setSecurityPrincipalName(String securityPrincipalName) { + this.securityPrincipalName = securityPrincipalName; + } + + public String getUserName() { + return userName; + } + + /** + * The user name to use when {@link + * javax.jms.TopicConnectionFactory#createTopicConnection(String, String)} + * creating a topic session}. If you set this option, you should also set the + * Password option. See {@link #setPassword(String)}. + */ + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + /** + * The password to use when creating a topic session. + */ + public void setPassword(String password) { + this.password = password; + } + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/LoginAuthenticator.java b/logback-core/src/main/java/ch/qos/logback/core/net/LoginAuthenticator.java index f5e979572699dd090373af023003887e0936fce2..018545337d2fad7c74e939ecea8e349826b2486f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/LoginAuthenticator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/LoginAuthenticator.java @@ -21,16 +21,16 @@ import javax.mail.PasswordAuthentication; */ public class LoginAuthenticator extends Authenticator { - String username; - String password; - - LoginAuthenticator(String username, String password) { - this.username = username; - this.password = password; - } - - public PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); -} + String username; + String password; + + LoginAuthenticator(String username, String password) { + this.username = username; + this.password = password; + } + + public PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java index 6682e762d8e135e68b41af2c6bb3023cdf923c87..9ac2e7c6a67e9d6ff6bc929ff81caac8b34d87ea 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java @@ -22,12 +22,12 @@ import java.io.IOException; */ public interface ObjectWriter { - /** - * Writes an object to an output. - * - * @param object the {@link Object} to write - * @throws IOException in case input/output fails, details are defined by the implementation - */ - void write(Object object) throws IOException; + /** + * Writes an object to an output. + * + * @param object the {@link Object} to write + * @throws IOException in case input/output fails, details are defined by the implementation + */ + void write(Object object) throws IOException; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java index 0bc7ccc66bf07049284d92f27f78cde436103f54..e79cc4f175ce52e6c8885019b28938075eeb9d0f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java @@ -26,14 +26,14 @@ import ch.qos.logback.core.CoreConstants; */ public class ObjectWriterFactory { - /** - * Creates a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance. - * - * @param outputStream the underlying {@link java.io.OutputStream} to write to - * @return a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance - * @throws IOException if an I/O error occurs while writing stream header - */ - public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { - return new AutoFlushingObjectWriter(new ObjectOutputStream(outputStream), CoreConstants.OOS_RESET_FREQUENCY); - } + /** + * Creates a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance. + * + * @param outputStream the underlying {@link java.io.OutputStream} to write to + * @return a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance + * @throws IOException if an I/O error occurs while writing stream header + */ + public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { + return new AutoFlushingObjectWriter(new ObjectOutputStream(outputStream), CoreConstants.OOS_RESET_FREQUENCY); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java index 5a9ba72afbc06f8ab71b8bfad57eeed29f0ccd52..4493739af38a8b94521ea02681742bd97d91b13d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java @@ -23,17 +23,17 @@ import java.util.concurrent.LinkedBlockingDeque; */ public class QueueFactory { - /** - * Creates a new {@link LinkedBlockingDeque} with the given {@code capacity}. - * In case the given capacity is smaller than one it will automatically be - * converted to one. - * - * @param capacity the capacity to use for the queue - * @param the type of elements held in the queue - * @return a new instance of {@link ArrayBlockingQueue} - */ - public LinkedBlockingDeque newLinkedBlockingDeque(int capacity) { - final int actualCapacity = capacity < 1 ? 1 : capacity; - return new LinkedBlockingDeque(actualCapacity); - } + /** + * Creates a new {@link LinkedBlockingDeque} with the given {@code capacity}. + * In case the given capacity is smaller than one it will automatically be + * converted to one. + * + * @param capacity the capacity to use for the queue + * @param the type of elements held in the queue + * @return a new instance of {@link ArrayBlockingQueue} + */ + public LinkedBlockingDeque newLinkedBlockingDeque(int capacity) { + final int actualCapacity = capacity < 1 ? 1 : capacity; + return new LinkedBlockingDeque(actualCapacity); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java index 1c8daacbc96c34e0bc799af23bd0b84a7026599f..98a3924e1fe39f98d634d0529ae7bdac9e825808 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/SMTPAppenderBase.java @@ -61,620 +61,614 @@ import ch.qos.logback.core.util.OptionHelper; */ public abstract class SMTPAppenderBase extends AppenderBase { - static InternetAddress[] EMPTY_IA_ARRAY = new InternetAddress[0]; - // ~ 14 days - static final long MAX_DELAY_BETWEEN_STATUS_MESSAGES = 1228800 * CoreConstants.MILLIS_IN_ONE_SECOND; + static InternetAddress[] EMPTY_IA_ARRAY = new InternetAddress[0]; + // ~ 14 days + static final long MAX_DELAY_BETWEEN_STATUS_MESSAGES = 1228800 * CoreConstants.MILLIS_IN_ONE_SECOND; - long lastTrackerStatusPrint = 0; - long delayBetweenStatusMessages = 300 * CoreConstants.MILLIS_IN_ONE_SECOND; + long lastTrackerStatusPrint = 0; + long delayBetweenStatusMessages = 300 * CoreConstants.MILLIS_IN_ONE_SECOND; - protected Layout subjectLayout; - protected Layout layout; + protected Layout subjectLayout; + protected Layout layout; - private List> toPatternLayoutList = new ArrayList>(); - private String from; - private String subjectStr = null; - private String smtpHost; - private int smtpPort = 25; - private boolean starttls = false; - private boolean ssl = false; - private boolean sessionViaJNDI = false; - private String jndiLocation = CoreConstants.JNDI_COMP_PREFIX + "/mail/Session"; + private List> toPatternLayoutList = new ArrayList>(); + private String from; + private String subjectStr = null; + private String smtpHost; + private int smtpPort = 25; + private boolean starttls = false; + private boolean ssl = false; + private boolean sessionViaJNDI = false; + private String jndiLocation = CoreConstants.JNDI_COMP_PREFIX + "/mail/Session"; + String username; + String password; + String localhost; - String username; - String password; - String localhost; + boolean asynchronousSending = true; - boolean asynchronousSending = true; + private String charsetEncoding = "UTF-8"; - private String charsetEncoding = "UTF-8"; + protected Session session; - protected Session session; + protected EventEvaluator eventEvaluator; - protected EventEvaluator eventEvaluator; + protected Discriminator discriminator = new DefaultDiscriminator(); + protected CyclicBufferTracker cbTracker; - protected Discriminator discriminator = new DefaultDiscriminator(); - protected CyclicBufferTracker cbTracker; + private int errorCount = 0; - private int errorCount = 0; + /** + * return a layout for the subject string as appropriate for the module. If the + * subjectStr parameter is null, then a default value for subjectStr should be + * used. + * + * @param subjectStr + * @return a layout as appropriate for the module + */ + abstract protected Layout makeSubjectLayout(String subjectStr); - /** - * return a layout for the subject string as appropriate for the module. If the - * subjectStr parameter is null, then a default value for subjectStr should be - * used. - * - * @param subjectStr - * @return a layout as appropriate for the module - */ - abstract protected Layout makeSubjectLayout(String subjectStr); + /** + * Start the appender + */ + public void start() { - /** - * Start the appender - */ - public void start() { + if (cbTracker == null) { + cbTracker = new CyclicBufferTracker(); + } + + if (sessionViaJNDI) + session = lookupSessionInJNDI(); + else + session = buildSessionFromProperties(); + + if (session == null) { + addError("Failed to obtain javax.mail.Session. Cannot start."); + return; + } - if (cbTracker == null) { - cbTracker = new CyclicBufferTracker(); + subjectLayout = makeSubjectLayout(subjectStr); + + started = true; } - if (sessionViaJNDI) - session = lookupSessionInJNDI(); - else - session = buildSessionFromProperties(); + private Session lookupSessionInJNDI() { + addInfo("Looking up javax.mail.Session at JNDI location [" + jndiLocation + "]"); + try { + Context initialContext = new InitialContext(); + Object obj = initialContext.lookup(jndiLocation); + return (Session) obj; + } catch (Exception e) { + addError("Failed to obtain javax.mail.Session from JNDI location [" + jndiLocation + "]"); + return null; + } + } - if (session == null) { - addError("Failed to obtain javax.mail.Session. Cannot start."); - return; + private Session buildSessionFromProperties() { + Properties props = new Properties(OptionHelper.getSystemProperties()); + if (smtpHost != null) { + props.put("mail.smtp.host", smtpHost); + } + props.put("mail.smtp.port", Integer.toString(smtpPort)); + + if (localhost != null) { + props.put("mail.smtp.localhost", localhost); + } + + LoginAuthenticator loginAuthenticator = null; + + if (username != null) { + loginAuthenticator = new LoginAuthenticator(username, password); + props.put("mail.smtp.auth", "true"); + } + + if (isSTARTTLS() && isSSL()) { + addError("Both SSL and StartTLS cannot be enabled simultaneously"); + } else { + if (isSTARTTLS()) { + // see also http://jira.qos.ch/browse/LBCORE-225 + props.put("mail.smtp.starttls.enable", "true"); + } + if (isSSL()) { + String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; + props.put("mail.smtp.socketFactory.port", Integer.toString(smtpPort)); + props.put("mail.smtp.socketFactory.class", SSL_FACTORY); + props.put("mail.smtp.socketFactory.fallback", "true"); + } + } + + // props.put("mail.debug", "true"); + + return Session.getInstance(props, loginAuthenticator); } - subjectLayout = makeSubjectLayout(subjectStr); + /** + * Perform SMTPAppender specific appending actions, delegating some of them to + * a subclass and checking if the event triggers an e-mail to be sent. + */ + protected void append(E eventObject) { + + if (!checkEntryConditions()) { + return; + } + + String key = discriminator.getDiscriminatingValue(eventObject); + long now = System.currentTimeMillis(); + final CyclicBuffer cb = cbTracker.getOrCreate(key, now); + subAppend(cb, eventObject); + + try { + if (eventEvaluator.evaluate(eventObject)) { + // clone the CyclicBuffer before sending out asynchronously + CyclicBuffer cbClone = new CyclicBuffer(cb); + // see http://jira.qos.ch/browse/LBCLASSIC-221 + cb.clear(); + + if (asynchronousSending) { + // perform actual sending asynchronously + SenderRunnable senderRunnable = new SenderRunnable(cbClone, eventObject); + context.getExecutorService().execute(senderRunnable); + } else { + // synchronous sending + sendBuffer(cbClone, eventObject); + } + } + } catch (EvaluationException ex) { + errorCount++; + if (errorCount < CoreConstants.MAX_ERROR_COUNT) { + addError("SMTPAppender's EventEvaluator threw an Exception-", ex); + } + } - started = true; - } + // immediately remove the buffer if asked by the user + if (eventMarksEndOfLife(eventObject)) { + cbTracker.endOfLife(key); + } + + cbTracker.removeStaleComponents(now); - private Session lookupSessionInJNDI() { - addInfo("Looking up javax.mail.Session at JNDI location [" + jndiLocation + "]"); - try { - Context initialContext = new InitialContext(); - Object obj = initialContext.lookup(jndiLocation); - return (Session) obj; - } catch (Exception e) { - addError("Failed to obtain javax.mail.Session from JNDI location [" + jndiLocation+"]"); - return null; + if (lastTrackerStatusPrint + delayBetweenStatusMessages < now) { + addInfo("SMTPAppender [" + name + "] is tracking [" + cbTracker.getComponentCount() + "] buffers"); + lastTrackerStatusPrint = now; + // quadruple 'delay' assuming less than max delay + if (delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES) { + delayBetweenStatusMessages *= 4; + } + } } - } - private Session buildSessionFromProperties() { - Properties props = new Properties(OptionHelper.getSystemProperties()); - if (smtpHost != null) { - props.put("mail.smtp.host", smtpHost); + abstract protected boolean eventMarksEndOfLife(E eventObject); + + abstract protected void subAppend(CyclicBuffer cb, E eventObject); + + /** + * This method determines if there is a sense in attempting to append. + *

+ *

+ * It checks whether there is a set output target and also if there is a set + * layout. If these checks fail, then the boolean value false is + * returned. + */ + public boolean checkEntryConditions() { + if (!this.started) { + addError("Attempting to append to a non-started appender: " + this.getName()); + return false; + } + + if (this.eventEvaluator == null) { + addError("No EventEvaluator is set for appender [" + name + "]."); + return false; + } + + if (this.layout == null) { + addError("No layout set for appender named [" + name + "]. For more information, please visit http://logback.qos.ch/codes.html#smtp_no_layout"); + return false; + } + return true; + } + + synchronized public void stop() { + this.started = false; + } + + InternetAddress getAddress(String addressStr) { + try { + return new InternetAddress(addressStr); + } catch (AddressException e) { + addError("Could not parse address [" + addressStr + "].", e); + return null; + } + } + + private List parseAddress(E event) { + int len = toPatternLayoutList.size(); + + List iaList = new ArrayList(); + + for (int i = 0; i < len; i++) { + try { + PatternLayoutBase emailPL = toPatternLayoutList.get(i); + String emailAdrr = emailPL.doLayout(event); + if (emailAdrr == null || emailAdrr.length() == 0) { + continue; + } + InternetAddress[] tmp = InternetAddress.parse(emailAdrr, true); + iaList.addAll(Arrays.asList(tmp)); + } catch (AddressException e) { + addError("Could not parse email address for [" + toPatternLayoutList.get(i) + "] for event [" + event + "]", e); + return iaList; + } + } + + return iaList; } - props.put("mail.smtp.port", Integer.toString(smtpPort)); - if (localhost != null) { - props.put("mail.smtp.localhost", localhost); + /** + * Returns value of the toList option. + */ + public List> getToList() { + return toPatternLayoutList; + } + + /** + * Send the contents of the cyclic buffer as an e-mail message. + */ + protected void sendBuffer(CyclicBuffer cb, E lastEventObject) { + + // Note: this code already owns the monitor for this + // appender. This frees us from needing to synchronize on 'cb'. + try { + MimeBodyPart part = new MimeBodyPart(); + + StringBuffer sbuf = new StringBuffer(); + + String header = layout.getFileHeader(); + if (header != null) { + sbuf.append(header); + } + String presentationHeader = layout.getPresentationHeader(); + if (presentationHeader != null) { + sbuf.append(presentationHeader); + } + fillBuffer(cb, sbuf); + String presentationFooter = layout.getPresentationFooter(); + if (presentationFooter != null) { + sbuf.append(presentationFooter); + } + String footer = layout.getFileFooter(); + if (footer != null) { + sbuf.append(footer); + } + + String subjectStr = "Undefined subject"; + if (subjectLayout != null) { + subjectStr = subjectLayout.doLayout(lastEventObject); + + // The subject must not contain new-line characters, which cause + // an SMTP error (LOGBACK-865). Truncate the string at the first + // new-line character. + int newLinePos = (subjectStr != null) ? subjectStr.indexOf('\n') : -1; + if (newLinePos > -1) { + subjectStr = subjectStr.substring(0, newLinePos); + } + } + + MimeMessage mimeMsg = new MimeMessage(session); + + if (from != null) { + mimeMsg.setFrom(getAddress(from)); + } else { + mimeMsg.setFrom(); + } + + mimeMsg.setSubject(subjectStr, charsetEncoding); + + List destinationAddresses = parseAddress(lastEventObject); + if (destinationAddresses.isEmpty()) { + addInfo("Empty destination address. Aborting email transmission"); + return; + } + + InternetAddress[] toAddressArray = destinationAddresses.toArray(EMPTY_IA_ARRAY); + mimeMsg.setRecipients(Message.RecipientType.TO, toAddressArray); + + String contentType = layout.getContentType(); + + if (ContentTypeUtil.isTextual(contentType)) { + part.setText(sbuf.toString(), charsetEncoding, ContentTypeUtil.getSubType(contentType)); + } else { + part.setContent(sbuf.toString(), layout.getContentType()); + } + + Multipart mp = new MimeMultipart(); + mp.addBodyPart(part); + mimeMsg.setContent(mp); + + mimeMsg.setSentDate(new Date()); + addInfo("About to send out SMTP message \"" + subjectStr + "\" to " + Arrays.toString(toAddressArray)); + Transport.send(mimeMsg); + } catch (Exception e) { + addError("Error occurred while sending e-mail notification.", e); + } } - LoginAuthenticator loginAuthenticator = null; + abstract protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf); - if (username != null) { - loginAuthenticator = new LoginAuthenticator(username, password); - props.put("mail.smtp.auth", "true"); + /** + * Returns value of the From option. + */ + public String getFrom() { + return from; } - if (isSTARTTLS() && isSSL()) { - addError("Both SSL and StartTLS cannot be enabled simultaneously"); - } else { - if (isSTARTTLS()) { - // see also http://jira.qos.ch/browse/LBCORE-225 - props.put("mail.smtp.starttls.enable", "true"); - } - if (isSSL()) { - String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; - props.put("mail.smtp.socketFactory.port", Integer.toString(smtpPort)); - props.put("mail.smtp.socketFactory.class", SSL_FACTORY); - props.put("mail.smtp.socketFactory.fallback", "true"); - } + /** + * Returns value of the Subject option. + */ + public String getSubject() { + return subjectStr; } - // props.put("mail.debug", "true"); + /** + * The From option takes a string value which should be a e-mail + * address of the sender. + */ + public void setFrom(String from) { + this.from = from; + } - return Session.getInstance(props, loginAuthenticator); - } + /** + * The Subject option takes a string value which should be a the + * subject of the e-mail message. + */ + public void setSubject(String subject) { + this.subjectStr = subject; + } - /** - * Perform SMTPAppender specific appending actions, delegating some of them to - * a subclass and checking if the event triggers an e-mail to be sent. - */ - protected void append(E eventObject) { + /** + * Alias for smtpHost + * + * @param smtpHost + */ + public void setSMTPHost(String smtpHost) { + setSmtpHost(smtpHost); + } - if (!checkEntryConditions()) { - return; + /** + * The smtpHost option takes a string value which should be a the host + * name of the SMTP server that will send the e-mail message. + */ + public void setSmtpHost(String smtpHost) { + this.smtpHost = smtpHost; } - String key = discriminator.getDiscriminatingValue(eventObject); - long now = System.currentTimeMillis(); - final CyclicBuffer cb = cbTracker.getOrCreate(key, now); - subAppend(cb, eventObject); + /** + * Alias for getSmtpHost(). + */ + public String getSMTPHost() { + return getSmtpHost(); + } - try { - if (eventEvaluator.evaluate(eventObject)) { - // clone the CyclicBuffer before sending out asynchronously - CyclicBuffer cbClone = new CyclicBuffer(cb); - // see http://jira.qos.ch/browse/LBCLASSIC-221 - cb.clear(); + /** + * Returns value of the SMTPHost option. + */ + public String getSmtpHost() { + return smtpHost; + } - if (asynchronousSending) { - // perform actual sending asynchronously - SenderRunnable senderRunnable = new SenderRunnable(cbClone, eventObject); - context.getExecutorService().execute(senderRunnable); - } else { - // synchronous sending - sendBuffer(cbClone, eventObject); + /** + * Alias for {@link #setSmtpPort}. + * + * @param port + */ + public void setSMTPPort(int port) { + setSmtpPort(port); + } + + /** + * The port where the SMTP server is running. Default value is 25. + * + * @param port + */ + public void setSmtpPort(int port) { + this.smtpPort = port; + } + + /** + * Alias for {@link #getSmtpPort} + * + * @return + */ + public int getSMTPPort() { + return getSmtpPort(); + } + + /** + * See {@link #setSmtpPort} + * + * @return + */ + public int getSmtpPort() { + return smtpPort; + } + + public String getLocalhost() { + return localhost; + } + + /** + * Set the "mail.smtp.localhost" property to the value passed as parameter to + * this method. + *

+ *

Useful in case the hostname for the client host is not fully qualified + * and as a consequence the SMTP server rejects the clients HELO/EHLO command. + *

+ * + * @param localhost + */ + public void setLocalhost(String localhost) { + this.localhost = localhost; + } + + public CyclicBufferTracker getCyclicBufferTracker() { + return cbTracker; + } + + public void setCyclicBufferTracker(CyclicBufferTracker cbTracker) { + this.cbTracker = cbTracker; + } + + public Discriminator getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(Discriminator discriminator) { + this.discriminator = discriminator; + } + + public boolean isAsynchronousSending() { + return asynchronousSending; + } + + /** + * By default, SMTAppender transmits emails asynchronously. For synchronous email transmission set + * asynchronousSending to 'false'. + * + * @param asynchronousSending determines whether sending is done asynchronously or not + * @since 1.0.4 + */ + public void setAsynchronousSending(boolean asynchronousSending) { + this.asynchronousSending = asynchronousSending; + } + + public void addTo(String to) { + if (to == null || to.length() == 0) { + throw new IllegalArgumentException("Null or empty property"); } - } - } catch (EvaluationException ex) { - errorCount++; - if (errorCount < CoreConstants.MAX_ERROR_COUNT) { - addError("SMTPAppender's EventEvaluator threw an Exception-", ex); - } + PatternLayoutBase plb = makeNewToPatternLayout(to.trim()); + plb.setContext(context); + plb.start(); + this.toPatternLayoutList.add(plb); } - // immediately remove the buffer if asked by the user - if (eventMarksEndOfLife(eventObject)) { - cbTracker.endOfLife(key); + abstract protected PatternLayoutBase makeNewToPatternLayout(String toPattern); + + public List getToAsListOfString() { + List toList = new ArrayList(); + for (PatternLayoutBase plb : toPatternLayoutList) { + toList.add(plb.getPattern()); + } + return toList; + } + + public boolean isSTARTTLS() { + return starttls; + } + + public void setSTARTTLS(boolean startTLS) { + this.starttls = startTLS; + } + + public boolean isSSL() { + return ssl; + } + + public void setSSL(boolean ssl) { + this.ssl = ssl; + } + + /** + * The EventEvaluator option takes a string value representing the name + * of the class implementing the {@link EventEvaluator} interface. A + * corresponding object will be instantiated and assigned as the event + * evaluator for the SMTPAppender. + */ + public void setEvaluator(EventEvaluator eventEvaluator) { + this.eventEvaluator = eventEvaluator; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; } - cbTracker.removeStaleComponents(now); + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } - if (lastTrackerStatusPrint + delayBetweenStatusMessages < now) { - addInfo("SMTPAppender [" + name + "] is tracking [" + cbTracker.getComponentCount() + "] buffers"); - lastTrackerStatusPrint = now; - // quadruple 'delay' assuming less than max delay - if (delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES) { - delayBetweenStatusMessages *= 4; - } + /** + * @return the charset encoding value + * @see #setCharsetEncoding(String) + */ + public String getCharsetEncoding() { + return charsetEncoding; } - } - abstract protected boolean eventMarksEndOfLife(E eventObject); + public String getJndiLocation() { + return jndiLocation; + } - abstract protected void subAppend(CyclicBuffer cb, E eventObject); + /** + * Set the location where a {@link javax.mail.Session} resource is located in JNDI. Default value is + * "java:comp/env/mail/Session". + * + * @param jndiLocation + * @since 1.0.6 + */ + public void setJndiLocation(String jndiLocation) { + this.jndiLocation = jndiLocation; + } - /** - * This method determines if there is a sense in attempting to append. - *

- *

- * It checks whether there is a set output target and also if there is a set - * layout. If these checks fail, then the boolean value false is - * returned. - */ - public boolean checkEntryConditions() { - if (!this.started) { - addError("Attempting to append to a non-started appender: " - + this.getName()); - return false; + public boolean isSessionViaJNDI() { + return sessionViaJNDI; } - if (this.eventEvaluator == null) { - addError("No EventEvaluator is set for appender [" + name + "]."); - return false; + /** + * If set to true, a {@link javax.mail.Session} resource will be retrieved from JNDI. Default is false. + * + * @param sessionViaJNDI whether to obtain a javax.mail.Session by JNDI + * @since 1.0.6 + */ + public void setSessionViaJNDI(boolean sessionViaJNDI) { + this.sessionViaJNDI = sessionViaJNDI; } - if (this.layout == null) { - addError("No layout set for appender named [" - + name - + "]. For more information, please visit http://logback.qos.ch/codes.html#smtp_no_layout"); - return false; + /** + * Set the character set encoding of the outgoing email messages. The default + * encoding is "UTF-8" which usually works well for most purposes. + * + * @param charsetEncoding + */ + public void setCharsetEncoding(String charsetEncoding) { + this.charsetEncoding = charsetEncoding; } - return true; - } - synchronized public void stop() { - this.started = false; - } + public Layout getLayout() { + return layout; + } - InternetAddress getAddress(String addressStr) { - try { - return new InternetAddress(addressStr); - } catch (AddressException e) { - addError("Could not parse address [" + addressStr + "].", e); - return null; + public void setLayout(Layout layout) { + this.layout = layout; } - } - private List parseAddress(E event) { - int len = toPatternLayoutList.size(); + class SenderRunnable implements Runnable { - List iaList = new ArrayList(); + final CyclicBuffer cyclicBuffer; + final E e; - for (int i = 0; i < len; i++) { - try { - PatternLayoutBase emailPL = toPatternLayoutList.get(i); - String emailAdrr = emailPL.doLayout(event); - if (emailAdrr == null || emailAdrr.length() == 0) { - continue; + SenderRunnable(CyclicBuffer cyclicBuffer, E e) { + this.cyclicBuffer = cyclicBuffer; + this.e = e; } - InternetAddress[] tmp = InternetAddress.parse(emailAdrr, true); - iaList.addAll(Arrays.asList(tmp)); - } catch (AddressException e) { - addError("Could not parse email address for [" + toPatternLayoutList.get(i) + "] for event [" + event + "]", e); - return iaList; - } - } - - return iaList; - } - - /** - * Returns value of the toList option. - */ - public List> getToList() { - return toPatternLayoutList; - } - - /** - * Send the contents of the cyclic buffer as an e-mail message. - */ - protected void sendBuffer(CyclicBuffer cb, E lastEventObject) { - - // Note: this code already owns the monitor for this - // appender. This frees us from needing to synchronize on 'cb'. - try { - MimeBodyPart part = new MimeBodyPart(); - - StringBuffer sbuf = new StringBuffer(); - - String header = layout.getFileHeader(); - if (header != null) { - sbuf.append(header); - } - String presentationHeader = layout.getPresentationHeader(); - if (presentationHeader != null) { - sbuf.append(presentationHeader); - } - fillBuffer(cb, sbuf); - String presentationFooter = layout.getPresentationFooter(); - if (presentationFooter != null) { - sbuf.append(presentationFooter); - } - String footer = layout.getFileFooter(); - if (footer != null) { - sbuf.append(footer); - } - - String subjectStr = "Undefined subject"; - if (subjectLayout != null) { - subjectStr = subjectLayout.doLayout(lastEventObject); - - // The subject must not contain new-line characters, which cause - // an SMTP error (LOGBACK-865). Truncate the string at the first - // new-line character. - int newLinePos = (subjectStr != null) ? subjectStr.indexOf('\n') : -1; - if (newLinePos > -1) { - subjectStr = subjectStr.substring(0, newLinePos); + + public void run() { + sendBuffer(cyclicBuffer, e); } - } - - MimeMessage mimeMsg = new MimeMessage(session); - - if (from != null) { - mimeMsg.setFrom(getAddress(from)); - } else { - mimeMsg.setFrom(); - } - - mimeMsg.setSubject(subjectStr, charsetEncoding); - - List destinationAddresses = parseAddress(lastEventObject); - if (destinationAddresses.isEmpty()) { - addInfo("Empty destination address. Aborting email transmission"); - return; - } - - InternetAddress[] toAddressArray = destinationAddresses.toArray(EMPTY_IA_ARRAY); - mimeMsg.setRecipients(Message.RecipientType.TO, toAddressArray); - - String contentType = layout.getContentType(); - - if (ContentTypeUtil.isTextual(contentType)) { - part.setText(sbuf.toString(), charsetEncoding, ContentTypeUtil - .getSubType(contentType)); - } else { - part.setContent(sbuf.toString(), layout.getContentType()); - } - - Multipart mp = new MimeMultipart(); - mp.addBodyPart(part); - mimeMsg.setContent(mp); - - mimeMsg.setSentDate(new Date()); - addInfo("About to send out SMTP message \"" + subjectStr + "\" to " + Arrays.toString(toAddressArray)); - Transport.send(mimeMsg); - } catch (Exception e) { - addError("Error occurred while sending e-mail notification.", e); - } - } - - abstract protected void fillBuffer(CyclicBuffer cb, StringBuffer sbuf); - - /** - * Returns value of the From option. - */ - public String getFrom() { - return from; - } - - /** - * Returns value of the Subject option. - */ - public String getSubject() { - return subjectStr; - } - - /** - * The From option takes a string value which should be a e-mail - * address of the sender. - */ - public void setFrom(String from) { - this.from = from; - } - - /** - * The Subject option takes a string value which should be a the - * subject of the e-mail message. - */ - public void setSubject(String subject) { - this.subjectStr = subject; - } - - /** - * Alias for smtpHost - * - * @param smtpHost - */ - public void setSMTPHost(String smtpHost) { - setSmtpHost(smtpHost); - } - - /** - * The smtpHost option takes a string value which should be a the host - * name of the SMTP server that will send the e-mail message. - */ - public void setSmtpHost(String smtpHost) { - this.smtpHost = smtpHost; - } - - /** - * Alias for getSmtpHost(). - */ - public String getSMTPHost() { - return getSmtpHost(); - } - - /** - * Returns value of the SMTPHost option. - */ - public String getSmtpHost() { - return smtpHost; - } - - /** - * Alias for {@link #setSmtpPort}. - * - * @param port - */ - public void setSMTPPort(int port) { - setSmtpPort(port); - } - - /** - * The port where the SMTP server is running. Default value is 25. - * - * @param port - */ - public void setSmtpPort(int port) { - this.smtpPort = port; - } - - /** - * Alias for {@link #getSmtpPort} - * - * @return - */ - public int getSMTPPort() { - return getSmtpPort(); - } - - /** - * See {@link #setSmtpPort} - * - * @return - */ - public int getSmtpPort() { - return smtpPort; - } - - public String getLocalhost() { - return localhost; - } - - /** - * Set the "mail.smtp.localhost" property to the value passed as parameter to - * this method. - *

- *

Useful in case the hostname for the client host is not fully qualified - * and as a consequence the SMTP server rejects the clients HELO/EHLO command. - *

- * - * @param localhost - */ - public void setLocalhost(String localhost) { - this.localhost = localhost; - } - - public CyclicBufferTracker getCyclicBufferTracker() { - return cbTracker; - } - - public void setCyclicBufferTracker(CyclicBufferTracker cbTracker) { - this.cbTracker = cbTracker; - } - - public Discriminator getDiscriminator() { - return discriminator; - } - - public void setDiscriminator(Discriminator discriminator) { - this.discriminator = discriminator; - } - - public boolean isAsynchronousSending() { - return asynchronousSending; - } - - /** - * By default, SMTAppender transmits emails asynchronously. For synchronous email transmission set - * asynchronousSending to 'false'. - * - * @param asynchronousSending determines whether sending is done asynchronously or not - * @since 1.0.4 - */ - public void setAsynchronousSending(boolean asynchronousSending) { - this.asynchronousSending = asynchronousSending; - } - - public void addTo(String to) { - if (to == null || to.length() == 0) { - throw new IllegalArgumentException("Null or empty property"); - } - PatternLayoutBase plb = makeNewToPatternLayout(to.trim()); - plb.setContext(context); - plb.start(); - this.toPatternLayoutList.add(plb); - } - - abstract protected PatternLayoutBase makeNewToPatternLayout(String toPattern); - - public List getToAsListOfString() { - List toList = new ArrayList(); - for (PatternLayoutBase plb : toPatternLayoutList) { - toList.add(plb.getPattern()); - } - return toList; - } - - public boolean isSTARTTLS() { - return starttls; - } - - public void setSTARTTLS(boolean startTLS) { - this.starttls = startTLS; - } - - public boolean isSSL() { - return ssl; - } - - public void setSSL(boolean ssl) { - this.ssl = ssl; - } - - /** - * The EventEvaluator option takes a string value representing the name - * of the class implementing the {@link EventEvaluator} interface. A - * corresponding object will be instantiated and assigned as the event - * evaluator for the SMTPAppender. - */ - public void setEvaluator(EventEvaluator eventEvaluator) { - this.eventEvaluator = eventEvaluator; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the charset encoding value - * @see #setCharsetEncoding(String) - */ - public String getCharsetEncoding() { - return charsetEncoding; - } - - - public String getJndiLocation() { - return jndiLocation; - } - - /** - * Set the location where a {@link javax.mail.Session} resource is located in JNDI. Default value is - * "java:comp/env/mail/Session". - * - * @param jndiLocation - * @since 1.0.6 - */ - public void setJndiLocation(String jndiLocation) { - this.jndiLocation = jndiLocation; - } - - public boolean isSessionViaJNDI() { - return sessionViaJNDI; - } - - /** - * If set to true, a {@link javax.mail.Session} resource will be retrieved from JNDI. Default is false. - * - * @param sessionViaJNDI whether to obtain a javax.mail.Session by JNDI - * @since 1.0.6 - */ - public void setSessionViaJNDI(boolean sessionViaJNDI) { - this.sessionViaJNDI = sessionViaJNDI; - } - - /** - * Set the character set encoding of the outgoing email messages. The default - * encoding is "UTF-8" which usually works well for most purposes. - * - * @param charsetEncoding - */ - public void setCharsetEncoding(String charsetEncoding) { - this.charsetEncoding = charsetEncoding; - } - - public Layout getLayout() { - return layout; - } - - public void setLayout(Layout layout) { - this.layout = layout; - } - - class SenderRunnable implements Runnable { - - final CyclicBuffer cyclicBuffer; - final E e; - - SenderRunnable(CyclicBuffer cyclicBuffer, E e) { - this.cyclicBuffer = cyclicBuffer; - this.e = e; - } - - public void run() { - sendBuffer(cyclicBuffer, e); - } - } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/SocketConnector.java b/logback-core/src/main/java/ch/qos/logback/core/net/SocketConnector.java index 38a9f308a5f182311fcbeacdfadb3b9d9c28273e..b6e5cc0ef8d1189874129c7712851370d26e7859 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/SocketConnector.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/SocketConnector.java @@ -28,38 +28,38 @@ import javax.net.SocketFactory; */ public interface SocketConnector extends Callable { - /** - * An exception handler that is notified of all exceptions that occur - * during the (re)connection process. - */ - public interface ExceptionHandler { - void connectionFailed(SocketConnector connector, Exception ex); - } - - /** - * Blocks the calling thread until a connection is successfully - * established. - * @return the connected socket - * @throws InterruptedException - */ - Socket call() throws InterruptedException; + /** + * An exception handler that is notified of all exceptions that occur + * during the (re)connection process. + */ + public interface ExceptionHandler { + void connectionFailed(SocketConnector connector, Exception ex); + } + + /** + * Blocks the calling thread until a connection is successfully + * established. + * @return the connected socket + * @throws InterruptedException + */ + Socket call() throws InterruptedException; + + /** + * Sets the connector's exception handler. + *

+ * The handler must be set before the {@link #call()} method is invoked. + * @param exceptionHandler the handler to set + */ + void setExceptionHandler(ExceptionHandler exceptionHandler); + + /** + * Sets the connector's socket factory. + *

+ * If no factory is configured that connector will use the platform's + * default factory. + * + * @param socketFactory the factory to set + */ + void setSocketFactory(SocketFactory socketFactory); - /** - * Sets the connector's exception handler. - *

- * The handler must be set before the {@link #call()} method is invoked. - * @param exceptionHandler the handler to set - */ - void setExceptionHandler(ExceptionHandler exceptionHandler); - - /** - * Sets the connector's socket factory. - *

- * If no factory is configured that connector will use the platform's - * default factory. - * - * @param socketFactory the factory to set - */ - void setSocketFactory(SocketFactory socketFactory); - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogAppenderBase.java index a4335d192a4cea214e1621be61e43d51ae9bb5d5..43a2e857a382e1b5a2ee057afbc1769e868a2833 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogAppenderBase.java @@ -32,282 +32,277 @@ import ch.qos.logback.core.Layout; */ public abstract class SyslogAppenderBase extends AppenderBase { - final static String SYSLOG_LAYOUT_URL = CoreConstants.CODES_URL - + "#syslog_layout"; - final static int MAX_MESSAGE_SIZE_LIMIT = 65000; - - Layout layout; - String facilityStr; - String syslogHost; - protected String suffixPattern; - SyslogOutputStream sos; - int port = SyslogConstants.SYSLOG_PORT; - int maxMessageSize; - Charset charset; - - public void start() { - int errorCount = 0; - if (facilityStr == null) { - addError("The Facility option is mandatory"); - errorCount++; + final static String SYSLOG_LAYOUT_URL = CoreConstants.CODES_URL + "#syslog_layout"; + final static int MAX_MESSAGE_SIZE_LIMIT = 65000; + + Layout layout; + String facilityStr; + String syslogHost; + protected String suffixPattern; + SyslogOutputStream sos; + int port = SyslogConstants.SYSLOG_PORT; + int maxMessageSize; + Charset charset; + + public void start() { + int errorCount = 0; + if (facilityStr == null) { + addError("The Facility option is mandatory"); + errorCount++; + } + + if (charset == null) { + // Using defaultCharset() preserves the previous behavior when String.getBytes() was + // called without arguments + charset = Charset.defaultCharset(); + } + + try { + sos = createOutputStream(); + + final int systemDatagramSize = sos.getSendBufferSize(); + if (maxMessageSize == 0) { + maxMessageSize = Math.min(systemDatagramSize, MAX_MESSAGE_SIZE_LIMIT); + addInfo("Defaulting maxMessageSize to [" + maxMessageSize + "]"); + } else if (maxMessageSize > systemDatagramSize) { + addWarn("maxMessageSize of [" + maxMessageSize + "] is larger than the system defined datagram size of [" + systemDatagramSize + "]."); + addWarn("This may result in dropped logs."); + } + } catch (UnknownHostException e) { + addError("Could not create SyslogWriter", e); + errorCount++; + } catch (SocketException e) { + addWarn("Failed to bind to a random datagram socket. Will try to reconnect later.", e); + } + + if (layout == null) { + layout = buildLayout(); + } + + if (errorCount == 0) { + super.start(); + } } - if (charset == null) { - // Using defaultCharset() preserves the previous behavior when String.getBytes() was - // called without arguments - charset = Charset.defaultCharset(); + abstract public SyslogOutputStream createOutputStream() throws UnknownHostException, SocketException; + + abstract public Layout buildLayout(); + + abstract public int getSeverityForEvent(Object eventObject); + + @Override + protected void append(E eventObject) { + if (!isStarted()) { + return; + } + + try { + String msg = layout.doLayout(eventObject); + if (msg == null) { + return; + } + if (msg.length() > maxMessageSize) { + msg = msg.substring(0, maxMessageSize); + } + sos.write(msg.getBytes(charset)); + sos.flush(); + postProcess(eventObject, sos); + } catch (IOException ioe) { + addError("Failed to send diagram to " + syslogHost, ioe); + } } - try { - sos = createOutputStream(); - - final int systemDatagramSize = sos.getSendBufferSize(); - if (maxMessageSize == 0) { - maxMessageSize = Math.min(systemDatagramSize, MAX_MESSAGE_SIZE_LIMIT); - addInfo("Defaulting maxMessageSize to [" + maxMessageSize + "]"); - } else if (maxMessageSize > systemDatagramSize) { - addWarn("maxMessageSize of [" + maxMessageSize + "] is larger than the system defined datagram size of [" + systemDatagramSize + "]."); - addWarn("This may result in dropped logs."); - } - } catch (UnknownHostException e) { - addError("Could not create SyslogWriter", e); - errorCount++; - } catch (SocketException e) { - addWarn( - "Failed to bind to a random datagram socket. Will try to reconnect later.", - e); + protected void postProcess(Object event, OutputStream sw) { + } - if (layout == null) { - layout = buildLayout(); + /** + * Returns the integer value corresponding to the named syslog facility. + * + * @throws IllegalArgumentException + * if the facility string is not recognized + */ + static public int facilityStringToint(String facilityStr) { + if ("KERN".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_KERN; + } else if ("USER".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_USER; + } else if ("MAIL".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_MAIL; + } else if ("DAEMON".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_DAEMON; + } else if ("AUTH".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_AUTH; + } else if ("SYSLOG".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_SYSLOG; + } else if ("LPR".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LPR; + } else if ("NEWS".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_NEWS; + } else if ("UUCP".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_UUCP; + } else if ("CRON".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_CRON; + } else if ("AUTHPRIV".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_AUTHPRIV; + } else if ("FTP".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_FTP; + } else if ("NTP".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_NTP; + } else if ("AUDIT".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_AUDIT; + } else if ("ALERT".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_ALERT; + } else if ("CLOCK".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_CLOCK; + } else if ("LOCAL0".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL0; + } else if ("LOCAL1".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL1; + } else if ("LOCAL2".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL2; + } else if ("LOCAL3".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL3; + } else if ("LOCAL4".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL4; + } else if ("LOCAL5".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL5; + } else if ("LOCAL6".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL6; + } else if ("LOCAL7".equalsIgnoreCase(facilityStr)) { + return SyslogConstants.LOG_LOCAL7; + } else { + throw new IllegalArgumentException(facilityStr + " is not a valid syslog facility string"); + } } - if (errorCount == 0) { - super.start(); + /** + * Returns the value of the SyslogHost option. + */ + public String getSyslogHost() { + return syslogHost; } - } - abstract public SyslogOutputStream createOutputStream() throws UnknownHostException, SocketException; + /** + * The SyslogHost option is the name of the the syslog host where log + * output should go. + * + * WARNING If the SyslogHost is not set, then this appender will fail. + */ + public void setSyslogHost(String syslogHost) { + this.syslogHost = syslogHost; + } - abstract public Layout buildLayout(); + /** + * Returns the string value of the Facility option. + * + * See {@link #setFacility} for the set of allowed values. + */ + public String getFacility() { + return facilityStr; + } + + /** + * The Facility option must be set one of the strings KERN, USER, MAIL, + * DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, NTP, AUDIT, + * ALERT, CLOCK, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, + * LOCAL7. Case is not important. + * + *

+ * See {@link SyslogConstants} and RFC 3164 for more information about the + * Facility option. + */ + public void setFacility(String facilityStr) { + if (facilityStr != null) { + facilityStr = facilityStr.trim(); + } + this.facilityStr = facilityStr; + } - abstract public int getSeverityForEvent(Object eventObject); + /** + * + * @return + */ + public int getPort() { + return port; + } - @Override - protected void append(E eventObject) { - if (!isStarted()) { - return; + /** + * The port number on the syslog server to connect to. Normally, you would not + * want to change the default value, that is 514. + */ + public void setPort(int port) { + this.port = port; } - try { - String msg = layout.doLayout(eventObject); - if(msg == null) { - return; - } - if (msg.length() > maxMessageSize) { - msg = msg.substring(0, maxMessageSize); - } - sos.write(msg.getBytes(charset)); - sos.flush(); - postProcess(eventObject, sos); - } catch (IOException ioe) { - addError("Failed to send diagram to " + syslogHost, ioe); + /** + * + * @return + */ + public int getMaxMessageSize() { + return maxMessageSize; } - } - - protected void postProcess(Object event, OutputStream sw) { - - } - - /** - * Returns the integer value corresponding to the named syslog facility. - * - * @throws IllegalArgumentException - * if the facility string is not recognized - */ - static public int facilityStringToint(String facilityStr) { - if ("KERN".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_KERN; - } else if ("USER".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_USER; - } else if ("MAIL".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_MAIL; - } else if ("DAEMON".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_DAEMON; - } else if ("AUTH".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_AUTH; - } else if ("SYSLOG".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_SYSLOG; - } else if ("LPR".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LPR; - } else if ("NEWS".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_NEWS; - } else if ("UUCP".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_UUCP; - } else if ("CRON".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_CRON; - } else if ("AUTHPRIV".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_AUTHPRIV; - } else if ("FTP".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_FTP; - } else if ("NTP".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_NTP; - } else if ("AUDIT".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_AUDIT; - } else if ("ALERT".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_ALERT; - } else if ("CLOCK".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_CLOCK; - } else if ("LOCAL0".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL0; - } else if ("LOCAL1".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL1; - } else if ("LOCAL2".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL2; - } else if ("LOCAL3".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL3; - } else if ("LOCAL4".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL4; - } else if ("LOCAL5".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL5; - } else if ("LOCAL6".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL6; - } else if ("LOCAL7".equalsIgnoreCase(facilityStr)) { - return SyslogConstants.LOG_LOCAL7; - } else { - throw new IllegalArgumentException(facilityStr - + " is not a valid syslog facility string"); + + /** + * Maximum size for the syslog message (in characters); messages + * longer than this are truncated. The default value is 65400 (which + * is near the maximum for syslog-over-UDP). Note that the value is + * characters; the number of bytes may vary if non-ASCII characters + * are present. + */ + public void setMaxMessageSize(int maxMessageSize) { + this.maxMessageSize = maxMessageSize; } - } - - /** - * Returns the value of the SyslogHost option. - */ - public String getSyslogHost() { - return syslogHost; - } - - /** - * The SyslogHost option is the name of the the syslog host where log - * output should go. - * - * WARNING If the SyslogHost is not set, then this appender will fail. - */ - public void setSyslogHost(String syslogHost) { - this.syslogHost = syslogHost; - } - - /** - * Returns the string value of the Facility option. - * - * See {@link #setFacility} for the set of allowed values. - */ - public String getFacility() { - return facilityStr; - } - - /** - * The Facility option must be set one of the strings KERN, USER, MAIL, - * DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, NTP, AUDIT, - * ALERT, CLOCK, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, - * LOCAL7. Case is not important. - * - *

- * See {@link SyslogConstants} and RFC 3164 for more information about the - * Facility option. - */ - public void setFacility(String facilityStr) { - if (facilityStr != null) { - facilityStr = facilityStr.trim(); + + public Layout getLayout() { + return layout; } - this.facilityStr = facilityStr; - } - - /** - * - * @return - */ - public int getPort() { - return port; - } - - /** - * The port number on the syslog server to connect to. Normally, you would not - * want to change the default value, that is 514. - */ - public void setPort(int port) { - this.port = port; - } - - /** - * - * @return - */ - public int getMaxMessageSize() { - return maxMessageSize; - } - - /** - * Maximum size for the syslog message (in characters); messages - * longer than this are truncated. The default value is 65400 (which - * is near the maximum for syslog-over-UDP). Note that the value is - * characters; the number of bytes may vary if non-ASCII characters - * are present. - */ - public void setMaxMessageSize(int maxMessageSize) { - this.maxMessageSize = maxMessageSize; - } - - public Layout getLayout() { - return layout; - } - - public void setLayout(Layout layout) { - addWarn("The layout of a SyslogAppender cannot be set directly. See also " - + SYSLOG_LAYOUT_URL); - } - - @Override - public void stop() { - if (sos != null) { - sos.close(); + + public void setLayout(Layout layout) { + addWarn("The layout of a SyslogAppender cannot be set directly. See also " + SYSLOG_LAYOUT_URL); } - super.stop(); - } -/** - * See {@link #setSuffixPattern(String). - * - * @return - */ - public String getSuffixPattern() { - return suffixPattern; - } - - /** - * The suffixPattern option specifies the format of the - * non-standardized part of the message sent to the syslog server. - * - * @param suffixPattern - */ - public void setSuffixPattern(String suffixPattern) { - this.suffixPattern = suffixPattern; - } - - /** - * Returns the Charset used to encode String messages into byte sequences when writing to - * syslog. - */ - public Charset getCharset() { - return charset; - } - - /** - * The Charset to use when encoding messages into byte sequences. - * - * @param charset - */ - public void setCharset(Charset charset) { - this.charset = charset; - } + @Override + public void stop() { + if (sos != null) { + sos.close(); + } + super.stop(); + } + + /** + * See {@link #setSuffixPattern(String). + * + * @return + */ + public String getSuffixPattern() { + return suffixPattern; + } + + /** + * The suffixPattern option specifies the format of the + * non-standardized part of the message sent to the syslog server. + * + * @param suffixPattern + */ + public void setSuffixPattern(String suffixPattern) { + this.suffixPattern = suffixPattern; + } + + /** + * Returns the Charset used to encode String messages into byte sequences when writing to + * syslog. + */ + public Charset getCharset() { + return charset; + } + + /** + * The Charset to use when encoding messages into byte sequences. + * + * @param charset + */ + public void setCharset(Charset charset) { + this.charset = charset; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogConstants.java b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogConstants.java index 44549016a01e28a2eebe843dc11836e83c78bbf2..7d921978835d9dde49a9f7487cc693c6afb8508d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogConstants.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogConstants.java @@ -19,78 +19,76 @@ package ch.qos.logback.core.net; * @author Ceki Gülcü **/ public class SyslogConstants { - - static public final int SYSLOG_PORT = 514; - - - // Following constants extracted from RFC 3164, we multiply them by 8 - // in order to precompute the facility part of PRI. - // See RFC 3164, Section 4.1.1 for exact details. - /** Emergency: system is unusable */ - public static final int EMERGENCY_SEVERITY = 0; - /** Alert: action must be taken immediately */ - public static final int ALERT_SEVERITY = 1; - /** Critical: critical conditions */ - public static final int CRITICAL_SEVERITY = 2; - /** Error: error conditions */ - public static final int ERROR_SEVERITY = 3; - /** Warning: warning conditions */ - public static final int WARNING_SEVERITY = 4; - /** Notice: normal but significant condition */ - public static final int NOTICE_SEVERITY = 5; - /** Informational: informational messages */ - public static final int INFO_SEVERITY = 6; - /** Debug: debug-level messages */ - public static final int DEBUG_SEVERITY = 7; - - - /** kernel messages, numerical code 0. */ - public static final int LOG_KERN = 0; - /** user-level messages, numerical code 1. */ - public static final int LOG_USER = 1 << 3; - /** mail system, numerical code 2. */ - public static final int LOG_MAIL = 2 << 3; - /** system daemons, numerical code 3. */ - public static final int LOG_DAEMON = 3 << 3; - /** security/authorization messages, numerical code 4. */ - public static final int LOG_AUTH = 4 << 3; - /** messages generated internally by syslogd, numerical code 5. */ - public static final int LOG_SYSLOG = 5 << 3; - /** line printer subsystem, numerical code 6. */ - public static final int LOG_LPR = 6 << 3; - /** network news subsystem, numerical code 7. */ - public static final int LOG_NEWS = 7 << 3; - /** UUCP subsystem, numerical code 8 */ - public static final int LOG_UUCP = 8 << 3; - /** clock daemon, numerical code 9. */ - public static final int LOG_CRON = 9 << 3; - /** security/authorization messages, numerical code 10. */ - public static final int LOG_AUTHPRIV = 10 << 3; - /** ftp daemon, numerical code 11. */ - public static final int LOG_FTP = 11 << 3; - /** NTP subsystem, numerical code 12. */ - public static final int LOG_NTP = 12 << 3; - /** log audit, numerical code 13. */ - public static final int LOG_AUDIT = 13 << 3; - /** log alert, numerical code 14. */ - public static final int LOG_ALERT = 14 << 3; - /** clock daemon, numerical code 15. */ - public static final int LOG_CLOCK = 15 << 3; - /** reserved for local use, numerical code 16. */ - public static final int LOG_LOCAL0 = 16 << 3; - /** reserved for local use, numerical code 17. */ - public static final int LOG_LOCAL1 = 17 << 3; - /** reserved for local use, numerical code 18. */ - public static final int LOG_LOCAL2 = 18 << 3; - /** reserved for local use, numerical code 19. */ - public static final int LOG_LOCAL3 = 19 << 3; - /** reserved for local use, numerical code 20. */ - public static final int LOG_LOCAL4 = 20 << 3; - /** reserved for local use, numerical code 21. */ - public static final int LOG_LOCAL5 = 21 << 3; - /** reserved for local use, numerical code 22. */ - public static final int LOG_LOCAL6 = 22 << 3; - /** reserved for local use, numerical code 23.*/ - public static final int LOG_LOCAL7 = 23 << 3; + static public final int SYSLOG_PORT = 514; + + // Following constants extracted from RFC 3164, we multiply them by 8 + // in order to precompute the facility part of PRI. + // See RFC 3164, Section 4.1.1 for exact details. + + /** Emergency: system is unusable */ + public static final int EMERGENCY_SEVERITY = 0; + /** Alert: action must be taken immediately */ + public static final int ALERT_SEVERITY = 1; + /** Critical: critical conditions */ + public static final int CRITICAL_SEVERITY = 2; + /** Error: error conditions */ + public static final int ERROR_SEVERITY = 3; + /** Warning: warning conditions */ + public static final int WARNING_SEVERITY = 4; + /** Notice: normal but significant condition */ + public static final int NOTICE_SEVERITY = 5; + /** Informational: informational messages */ + public static final int INFO_SEVERITY = 6; + /** Debug: debug-level messages */ + public static final int DEBUG_SEVERITY = 7; + + /** kernel messages, numerical code 0. */ + public static final int LOG_KERN = 0; + /** user-level messages, numerical code 1. */ + public static final int LOG_USER = 1 << 3; + /** mail system, numerical code 2. */ + public static final int LOG_MAIL = 2 << 3; + /** system daemons, numerical code 3. */ + public static final int LOG_DAEMON = 3 << 3; + /** security/authorization messages, numerical code 4. */ + public static final int LOG_AUTH = 4 << 3; + /** messages generated internally by syslogd, numerical code 5. */ + public static final int LOG_SYSLOG = 5 << 3; + /** line printer subsystem, numerical code 6. */ + public static final int LOG_LPR = 6 << 3; + /** network news subsystem, numerical code 7. */ + public static final int LOG_NEWS = 7 << 3; + /** UUCP subsystem, numerical code 8 */ + public static final int LOG_UUCP = 8 << 3; + /** clock daemon, numerical code 9. */ + public static final int LOG_CRON = 9 << 3; + /** security/authorization messages, numerical code 10. */ + public static final int LOG_AUTHPRIV = 10 << 3; + /** ftp daemon, numerical code 11. */ + public static final int LOG_FTP = 11 << 3; + /** NTP subsystem, numerical code 12. */ + public static final int LOG_NTP = 12 << 3; + /** log audit, numerical code 13. */ + public static final int LOG_AUDIT = 13 << 3; + /** log alert, numerical code 14. */ + public static final int LOG_ALERT = 14 << 3; + /** clock daemon, numerical code 15. */ + public static final int LOG_CLOCK = 15 << 3; + /** reserved for local use, numerical code 16. */ + public static final int LOG_LOCAL0 = 16 << 3; + /** reserved for local use, numerical code 17. */ + public static final int LOG_LOCAL1 = 17 << 3; + /** reserved for local use, numerical code 18. */ + public static final int LOG_LOCAL2 = 18 << 3; + /** reserved for local use, numerical code 19. */ + public static final int LOG_LOCAL3 = 19 << 3; + /** reserved for local use, numerical code 20. */ + public static final int LOG_LOCAL4 = 20 << 3; + /** reserved for local use, numerical code 21. */ + public static final int LOG_LOCAL5 = 21 << 3; + /** reserved for local use, numerical code 22. */ + public static final int LOG_LOCAL6 = 22 << 3; + /** reserved for local use, numerical code 23.*/ + public static final int LOG_LOCAL7 = 23 << 3; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogOutputStream.java b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogOutputStream.java index 4309748e8fa359aca37190de7677846b36fa765b..f56da878cd9dc994b43bfeb73aea0e019508d942 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/SyslogOutputStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/SyslogOutputStream.java @@ -28,66 +28,64 @@ import java.net.UnknownHostException; */ public class SyslogOutputStream extends OutputStream { - /** - * The maximum length after which we discard the existing string buffer and - * start anew. - */ - private static final int MAX_LEN = 1024; + /** + * The maximum length after which we discard the existing string buffer and + * start anew. + */ + private static final int MAX_LEN = 1024; - private InetAddress address; - private DatagramSocket ds; - private ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final private int port; + private InetAddress address; + private DatagramSocket ds; + private ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final private int port; - public SyslogOutputStream(String syslogHost, int port) throws UnknownHostException, - SocketException { - this.address = InetAddress.getByName(syslogHost); - this.port = port; - this.ds = new DatagramSocket(); - } + public SyslogOutputStream(String syslogHost, int port) throws UnknownHostException, SocketException { + this.address = InetAddress.getByName(syslogHost); + this.port = port; + this.ds = new DatagramSocket(); + } - public void write(byte[] byteArray, int offset, int len) throws IOException { - baos.write(byteArray, offset, len); - } + public void write(byte[] byteArray, int offset, int len) throws IOException { + baos.write(byteArray, offset, len); + } - public void flush() throws IOException { - byte[] bytes = baos.toByteArray(); - DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, - port); + public void flush() throws IOException { + byte[] bytes = baos.toByteArray(); + DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port); + + // clean up for next round + if (baos.size() > MAX_LEN) { + baos = new ByteArrayOutputStream(); + } else { + baos.reset(); + } + + // after a failure, it can happen that bytes.length is zero + // in that case, there is no point in sending out an empty message/ + if (bytes.length == 0) { + return; + } + if (this.ds != null) { + ds.send(packet); + } - // clean up for next round - if (baos.size() > MAX_LEN) { - baos = new ByteArrayOutputStream(); - } else { - baos.reset(); - } - - // after a failure, it can happen that bytes.length is zero - // in that case, there is no point in sending out an empty message/ - if(bytes.length == 0) { - return; - } - if (this.ds != null) { - ds.send(packet); } - - } - public void close() { - address = null; - ds = null; - } + public void close() { + address = null; + ds = null; + } - public int getPort() { - return port; - } + public int getPort() { + return port; + } - @Override - public void write(int b) throws IOException { - baos.write(b); - } + @Override + public void write(int b) throws IOException { + baos.write(b); + } - int getSendBufferSize() throws SocketException { - return ds.getSendBufferSize(); - } + int getSendBufferSize() throws SocketException { + return ds.getSendBufferSize(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/AbstractServerSocketAppender.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/AbstractServerSocketAppender.java index 57a98f13fa80240c9e337911236ba71d356dd1b5..6540abed3a5b426b8c7af932ce09c464de2880da 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/AbstractServerSocketAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/AbstractServerSocketAppender.java @@ -35,184 +35,181 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public abstract class AbstractServerSocketAppender extends AppenderBase { - /** - * Default {@link ServerSocket} backlog - */ - public static final int DEFAULT_BACKLOG = 50; - - /** - * Default queue size used for each client - */ - public static final int DEFAULT_CLIENT_QUEUE_SIZE = 100; - - private int port = AbstractSocketAppender.DEFAULT_PORT; - private int backlog = DEFAULT_BACKLOG; - private int clientQueueSize = DEFAULT_CLIENT_QUEUE_SIZE; - - private String address; - - private ServerRunner runner; - - @Override - public void start() { - if (isStarted()) return; - try { - ServerSocket socket = getServerSocketFactory().createServerSocket( - getPort(), getBacklog(), getInetAddress()); - ServerListener listener = createServerListener(socket); - - runner = createServerRunner(listener, getContext().getExecutorService()); - runner.setContext(getContext()); - getContext().getExecutorService().execute(runner); - super.start(); - } catch (Exception ex) { - addError("server startup error: " + ex, ex); + /** + * Default {@link ServerSocket} backlog + */ + public static final int DEFAULT_BACKLOG = 50; + + /** + * Default queue size used for each client + */ + public static final int DEFAULT_CLIENT_QUEUE_SIZE = 100; + + private int port = AbstractSocketAppender.DEFAULT_PORT; + private int backlog = DEFAULT_BACKLOG; + private int clientQueueSize = DEFAULT_CLIENT_QUEUE_SIZE; + + private String address; + + private ServerRunner runner; + + @Override + public void start() { + if (isStarted()) + return; + try { + ServerSocket socket = getServerSocketFactory().createServerSocket(getPort(), getBacklog(), getInetAddress()); + ServerListener listener = createServerListener(socket); + + runner = createServerRunner(listener, getContext().getExecutorService()); + runner.setContext(getContext()); + getContext().getExecutorService().execute(runner); + super.start(); + } catch (Exception ex) { + addError("server startup error: " + ex, ex); + } } - } - - protected ServerListener createServerListener( - ServerSocket socket) { - return new RemoteReceiverServerListener(socket); - } - - protected ServerRunner createServerRunner( - ServerListener listener, - Executor executor) { - return new RemoteReceiverServerRunner(listener, executor, - getClientQueueSize()); - } - - @Override - public void stop() { - if (!isStarted()) return; - try { - runner.stop(); - super.stop(); + + protected ServerListener createServerListener(ServerSocket socket) { + return new RemoteReceiverServerListener(socket); } - catch (IOException ex) { - addError("server shutdown error: " + ex, ex); + + protected ServerRunner createServerRunner(ServerListener listener, Executor executor) { + return new RemoteReceiverServerRunner(listener, executor, getClientQueueSize()); } - } - - @Override - protected void append(E event) { - if (event == null) return; - postProcessEvent(event); - final Serializable serEvent = getPST().transform(event); - runner.accept(new ClientVisitor() { - public void visit(RemoteReceiverClient client) { - client.offer(serEvent); - } - }); - } - - /** - * Post process an event received via {@link #append(E)}. - * @param event - */ - protected abstract void postProcessEvent(E event); - - /** - * Gets a transformer that will be used to convert a received event - * to a {@link Serializable} form. - * @return - */ - protected abstract PreSerializationTransformer getPST(); - - /** - * Gets the factory used to create {@link ServerSocket} objects. - *

- * The default implementation delegates to - * {@link ServerSocketFactory#getDefault()}. Subclasses may override to - * private a different socket factory implementation. - * - * @return socket factory. - */ - protected ServerSocketFactory getServerSocketFactory() throws Exception { - return ServerSocketFactory.getDefault(); - } - - /** - * Gets the local address for the listener. - * @return an {@link InetAddress} representation of the local address. - * @throws UnknownHostException - */ - protected InetAddress getInetAddress() throws UnknownHostException { - if (getAddress() == null) return null; - return InetAddress.getByName(getAddress()); - } - - /** - * Gets the local port for the listener. - * @return local port - */ - public int getPort() { - return port; - } - - /** - * Sets the local port for the listener. - * @param port the local port to set - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Gets the listener queue depth. - *

- * This represents the number of connected clients whose connections - * have not yet been accepted. - * @return queue depth - * @see java.net.ServerSocket - */ - public int getBacklog() { - return backlog; - } - - /** - * Sets the listener queue depth. - *

- * This represents the number of connected clients whose connections - * have not yet been accepted. - * @param backlog the queue depth to set - * @see java.net.ServerSocket - */ - public void setBacklog(int backlog) { - this.backlog = backlog; - } - - /** - * Gets the local address for the listener. - * @return a string representation of the local address - */ - public String getAddress() { - return address; - } - - /** - * Sets the local address for the listener. - * @param address a host name or a string representation of an IP address - */ - public void setAddress(String address) { - this.address = address; - } - - /** - * Gets the event queue size used for each client connection. - * @return queue size - */ - public int getClientQueueSize() { - return clientQueueSize; - } - - /** - * Sets the event queue size used for each client connection. - * @param clientQueueSize the queue size to set - */ - public void setClientQueueSize(int clientQueueSize) { - this.clientQueueSize = clientQueueSize; - } -} + @Override + public void stop() { + if (!isStarted()) + return; + try { + runner.stop(); + super.stop(); + } catch (IOException ex) { + addError("server shutdown error: " + ex, ex); + } + } + + @Override + protected void append(E event) { + if (event == null) + return; + postProcessEvent(event); + final Serializable serEvent = getPST().transform(event); + runner.accept(new ClientVisitor() { + public void visit(RemoteReceiverClient client) { + client.offer(serEvent); + } + }); + } + + /** + * Post process an event received via {@link #append(E)}. + * @param event + */ + protected abstract void postProcessEvent(E event); + + /** + * Gets a transformer that will be used to convert a received event + * to a {@link Serializable} form. + * @return + */ + protected abstract PreSerializationTransformer getPST(); + + /** + * Gets the factory used to create {@link ServerSocket} objects. + *

+ * The default implementation delegates to + * {@link ServerSocketFactory#getDefault()}. Subclasses may override to + * private a different socket factory implementation. + * + * @return socket factory. + */ + protected ServerSocketFactory getServerSocketFactory() throws Exception { + return ServerSocketFactory.getDefault(); + } + + /** + * Gets the local address for the listener. + * @return an {@link InetAddress} representation of the local address. + * @throws UnknownHostException + */ + protected InetAddress getInetAddress() throws UnknownHostException { + if (getAddress() == null) + return null; + return InetAddress.getByName(getAddress()); + } + + /** + * Gets the local port for the listener. + * @return local port + */ + public int getPort() { + return port; + } + + /** + * Sets the local port for the listener. + * @param port the local port to set + */ + public void setPort(int port) { + this.port = port; + } + /** + * Gets the listener queue depth. + *

+ * This represents the number of connected clients whose connections + * have not yet been accepted. + * @return queue depth + * @see java.net.ServerSocket + */ + public int getBacklog() { + return backlog; + } + + /** + * Sets the listener queue depth. + *

+ * This represents the number of connected clients whose connections + * have not yet been accepted. + * @param backlog the queue depth to set + * @see java.net.ServerSocket + */ + public void setBacklog(int backlog) { + this.backlog = backlog; + } + + /** + * Gets the local address for the listener. + * @return a string representation of the local address + */ + public String getAddress() { + return address; + } + + /** + * Sets the local address for the listener. + * @param address a host name or a string representation of an IP address + */ + public void setAddress(String address) { + this.address = address; + } + + /** + * Gets the event queue size used for each client connection. + * @return queue size + */ + public int getClientQueueSize() { + return clientQueueSize; + } + + /** + * Sets the event queue size used for each client connection. + * @param clientQueueSize the queue size to set + */ + public void setClientQueueSize(int clientQueueSize) { + this.clientQueueSize = clientQueueSize; + } + +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/Client.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/Client.java index 5b6555b67677bf5fce0c56eed80d98c7a5e8a874..72f217ccd19ca3759127bd6de64465fe7a9b1a03 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/Client.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/Client.java @@ -37,21 +37,21 @@ import java.io.IOException; */ public interface Client extends Runnable, Closeable { - /** - * Closes any resources that are held by the client. - *

- * Note that (as described in Doug Lea's discussion about interrupting I/O - * operations in "Concurrent Programming in Java" (Addison-Wesley - * Professional, 2nd edition, 1999) this method is used to interrupt - * any blocked I/O operation in the client when the server is shutting - * down. The client implementation must anticipate this potential, - * and gracefully exit when the blocked I/O operation throws the - * relevant {@link IOException} subclass. - *

- * Note also, that unlike {@link Closeable#close()} this method is not - * permitted to propagate any {@link IOException} that occurs when closing - * the underlying resource(s). - */ - void close(); - + /** + * Closes any resources that are held by the client. + *

+ * Note that (as described in Doug Lea's discussion about interrupting I/O + * operations in "Concurrent Programming in Java" (Addison-Wesley + * Professional, 2nd edition, 1999) this method is used to interrupt + * any blocked I/O operation in the client when the server is shutting + * down. The client implementation must anticipate this potential, + * and gracefully exit when the blocked I/O operation throws the + * relevant {@link IOException} subclass. + *

+ * Note also, that unlike {@link Closeable#close()} this method is not + * permitted to propagate any {@link IOException} that occurs when closing + * the underlying resource(s). + */ + void close(); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/ClientVisitor.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/ClientVisitor.java index 5c601c0ed2fee664828b91b231711db5322f583c..0563ee935cfa3db746d54cc5a88cb35f9722f893 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/ClientVisitor.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/ClientVisitor.java @@ -20,6 +20,6 @@ package ch.qos.logback.core.net.server; */ public interface ClientVisitor { - void visit(T client); - + void visit(T client); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/ConcurrentServerRunner.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/ConcurrentServerRunner.java index afb1bd60bf0a90eaef194073f2f9a82b3bb17ee9..21ecb79046d3bdf3416f3beb47ea5a4fc436ecf9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/ConcurrentServerRunner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/ConcurrentServerRunner.java @@ -44,188 +44,178 @@ import ch.qos.logback.core.spi.ContextAwareBase; * * @author Carl Harris */ -public abstract class ConcurrentServerRunner - extends ContextAwareBase - implements Runnable, ServerRunner { - - private final Lock clientsLock = new ReentrantLock(); - - private final Collection clients = new ArrayList(); - - private final ServerListener listener; - private final Executor executor; - - private boolean running; - - /** - * Constructs a new server runner. - * @param listener the listener from which the server will accept new - * clients - * @param executor a executor that will facilitate execution of the - * listening and client-handling tasks; while any {@link Executor} - * is allowed here, outside of unit testing the only reasonable choice - * is a bounded thread pool of some kind. - */ - public ConcurrentServerRunner(ServerListener listener, Executor executor) { - this.listener = listener; - this.executor = executor; - } - - /** - * {@inheritDoc} - */ - public boolean isRunning() { - return running; - } - - protected void setRunning(boolean running) { - this.running = running; - } - - /** - * {@inheritDoc} - */ - public void stop() throws IOException { - listener.close(); - accept(new ClientVisitor() { - public void visit(T client) { - client.close(); - } - }); - } - - /** - * {@inheritDoc} - */ - public void accept(ClientVisitor visitor) { - Collection clients = copyClients(); - for (T client : clients) { - try { - visitor.visit(client); - } - catch (RuntimeException ex) { - addError(client + ": " + ex); - } +public abstract class ConcurrentServerRunner extends ContextAwareBase implements Runnable, ServerRunner { + + private final Lock clientsLock = new ReentrantLock(); + + private final Collection clients = new ArrayList(); + + private final ServerListener listener; + private final Executor executor; + + private boolean running; + + /** + * Constructs a new server runner. + * @param listener the listener from which the server will accept new + * clients + * @param executor a executor that will facilitate execution of the + * listening and client-handling tasks; while any {@link Executor} + * is allowed here, outside of unit testing the only reasonable choice + * is a bounded thread pool of some kind. + */ + public ConcurrentServerRunner(ServerListener listener, Executor executor) { + this.listener = listener; + this.executor = executor; } - } - - /** - * Creates a copy of the collection of all clients that are presently - * being tracked by the server. - * @return collection of client objects - */ - private Collection copyClients() { - clientsLock.lock(); - try { - Collection copy = new ArrayList(clients); - return copy; + + /** + * {@inheritDoc} + */ + public boolean isRunning() { + return running; } - finally { - clientsLock.unlock(); + + protected void setRunning(boolean running) { + this.running = running; } - } - - /** - * {@inheritDoc} - */ - public void run() { - setRunning(true); - try { - addInfo("listening on " + listener); - while (!Thread.currentThread().isInterrupted()) { - T client = listener.acceptClient(); - if (!configureClient(client)) { - addError(client + ": connection dropped"); - client.close(); - continue; + + /** + * {@inheritDoc} + */ + public void stop() throws IOException { + listener.close(); + accept(new ClientVisitor() { + public void visit(T client) { + client.close(); + } + }); + } + + /** + * {@inheritDoc} + */ + public void accept(ClientVisitor visitor) { + Collection clients = copyClients(); + for (T client : clients) { + try { + visitor.visit(client); + } catch (RuntimeException ex) { + addError(client + ": " + ex); + } } + } + + /** + * Creates a copy of the collection of all clients that are presently + * being tracked by the server. + * @return collection of client objects + */ + private Collection copyClients() { + clientsLock.lock(); try { - executor.execute(new ClientWrapper(client)); - } - catch (RejectedExecutionException ex) { - addError(client + ": connection dropped"); - client.close(); + Collection copy = new ArrayList(clients); + return copy; + } finally { + clientsLock.unlock(); } - } - } - catch (InterruptedException ex) { - assert true; // ok... we'll shut down - } - catch (Exception ex) { - addError("listener: " + ex); } - setRunning(false); - addInfo("shutting down"); - listener.close(); - } - - /** - * Configures a connected client. - *

- * A subclass implements this method to perform any necessary configuration - * of the client object before its {@link Client#run()} method is invoked. - * - * @param client the subject client - * @return {@code true} if configuration was successful; if the return - * value is {@code false} the client connection will be dropped - */ - protected abstract boolean configureClient(T client); - - /** - * Adds a client to the collection of those being tracked by the server. - * @param client the client to add - */ - private void addClient(T client) { - clientsLock.lock(); - try { - clients.add(client); - } - finally { - clientsLock.unlock(); - } - } - - /** - * Removes a client from the collection of those being tracked by the server. - * @param client the client to remote - */ - private void removeClient(T client) { - clientsLock.lock(); - try { - clients.remove(client); - } - finally { - clientsLock.unlock(); + /** + * {@inheritDoc} + */ + public void run() { + setRunning(true); + try { + addInfo("listening on " + listener); + while (!Thread.currentThread().isInterrupted()) { + T client = listener.acceptClient(); + if (!configureClient(client)) { + addError(client + ": connection dropped"); + client.close(); + continue; + } + try { + executor.execute(new ClientWrapper(client)); + } catch (RejectedExecutionException ex) { + addError(client + ": connection dropped"); + client.close(); + } + } + } catch (InterruptedException ex) { + assert true; // ok... we'll shut down + } catch (Exception ex) { + addError("listener: " + ex); + } + + setRunning(false); + addInfo("shutting down"); + listener.close(); } - } - - /** - * A wrapper for a {@link Client} responsible for ensuring that client - * tracking is performed properly. - */ - private class ClientWrapper implements Client { - - private final T delegate; - - public ClientWrapper(T client) { - this.delegate = client; + + /** + * Configures a connected client. + *

+ * A subclass implements this method to perform any necessary configuration + * of the client object before its {@link Client#run()} method is invoked. + * + * @param client the subject client + * @return {@code true} if configuration was successful; if the return + * value is {@code false} the client connection will be dropped + */ + protected abstract boolean configureClient(T client); + + /** + * Adds a client to the collection of those being tracked by the server. + * @param client the client to add + */ + private void addClient(T client) { + clientsLock.lock(); + try { + clients.add(client); + } finally { + clientsLock.unlock(); + } } - public void run() { - addClient(delegate); - try { - delegate.run(); - } - finally { - removeClient(delegate); - } + /** + * Removes a client from the collection of those being tracked by the server. + * @param client the client to remote + */ + private void removeClient(T client) { + clientsLock.lock(); + try { + clients.remove(client); + } finally { + clientsLock.unlock(); + } } - public void close() { - delegate.close(); + /** + * A wrapper for a {@link Client} responsible for ensuring that client + * tracking is performed properly. + */ + private class ClientWrapper implements Client { + + private final T delegate; + + public ClientWrapper(T client) { + this.delegate = client; + } + + public void run() { + addClient(delegate); + try { + delegate.run(); + } finally { + removeClient(delegate); + } + } + + public void close() { + delegate.close(); + } + } - - } - + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverClient.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverClient.java index 5833c6226d29c01bf132e74841435cee7e77d9c7..9af5cee2247cf02ed4dd55b2773dfe764ca54e46 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverClient.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverClient.java @@ -18,7 +18,6 @@ import java.util.concurrent.BlockingQueue; import ch.qos.logback.core.spi.ContextAware; - /** * A client of a {@link ServerRunner} that receives events from a local * appender and logs them according to local policy. @@ -27,20 +26,20 @@ import ch.qos.logback.core.spi.ContextAware; */ interface RemoteReceiverClient extends Client, ContextAware { - /** - * Sets the client's event queue. - *

- * This method must be invoked before the {@link #run()} method is invoked. - * @param queue the queue to set - */ - void setQueue(BlockingQueue queue); - - /** - * Offers an event to the client. - * @param event the subject event - * @return {@code true} if the client's queue accepted the event, - * {@code false} if the client's queue is full - */ - boolean offer(Serializable event); - + /** + * Sets the client's event queue. + *

+ * This method must be invoked before the {@link #run()} method is invoked. + * @param queue the queue to set + */ + void setQueue(BlockingQueue queue); + + /** + * Offers an event to the client. + * @param event the subject event + * @return {@code true} if the client's queue accepted the event, + * {@code false} if the client's queue is full + */ + boolean offer(Serializable event); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerListener.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerListener.java index f6ad600deffa68b834585e726afbed691e876644..3bac12447bc3744e7e918630dc6abc9865ca332d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerListener.java @@ -23,25 +23,23 @@ import java.net.Socket; * * @author Carl Harris */ -class RemoteReceiverServerListener - extends ServerSocketListener { +class RemoteReceiverServerListener extends ServerSocketListener { - /** - * Constructs a new listener. - * @param serverSocket server socket from which new client connections - * will be accepted - */ - public RemoteReceiverServerListener(ServerSocket serverSocket) { - super(serverSocket); - } + /** + * Constructs a new listener. + * @param serverSocket server socket from which new client connections + * will be accepted + */ + public RemoteReceiverServerListener(ServerSocket serverSocket) { + super(serverSocket); + } - /** - * {@inheritDoc} - */ - @Override - protected RemoteReceiverClient createClient(String id, Socket socket) - throws IOException { - return new RemoteReceiverStreamClient(id, socket); - } + /** + * {@inheritDoc} + */ + @Override + protected RemoteReceiverClient createClient(String id, Socket socket) throws IOException { + return new RemoteReceiverStreamClient(id, socket); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerRunner.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerRunner.java index 64117a255b24295b015f9ddc9aa5145250340892..da97a69ffa898e0c864a4e051ea79f7f7c3164ec 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerRunner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverServerRunner.java @@ -23,35 +23,32 @@ import java.util.concurrent.Executor; * * @author Carl Harris */ -class RemoteReceiverServerRunner - extends ConcurrentServerRunner { +class RemoteReceiverServerRunner extends ConcurrentServerRunner { - private final int clientQueueSize; - - /** - * Constructs a new server runner. - * @param listener the listener from which the server will accept new - * clients - * @param executor that will be used to execute asynchronous tasks - * on behalf of the runner. - * @param queueSize size of the event queue that will be maintained for - * each client - */ - public RemoteReceiverServerRunner( - ServerListener listener, Executor executor, - int clientQueueSize) { - super(listener, executor); - this.clientQueueSize = clientQueueSize; - } + private final int clientQueueSize; - /** - * {@inheritDoc} - */ - @Override - protected boolean configureClient(RemoteReceiverClient client) { - client.setContext(getContext()); - client.setQueue(new ArrayBlockingQueue(clientQueueSize)); - return true; - } + /** + * Constructs a new server runner. + * @param listener the listener from which the server will accept new + * clients + * @param executor that will be used to execute asynchronous tasks + * on behalf of the runner. + * @param queueSize size of the event queue that will be maintained for + * each client + */ + public RemoteReceiverServerRunner(ServerListener listener, Executor executor, int clientQueueSize) { + super(listener, executor); + this.clientQueueSize = clientQueueSize; + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean configureClient(RemoteReceiverClient client) { + client.setContext(getContext()); + client.setQueue(new ArrayBlockingQueue(clientQueueSize)); + return true; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClient.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClient.java index a6a1f9179c5659e778e5c96320687d35182de58d..5a27af2894ed70aa310f9a054d7827c42ee51222 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClient.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClient.java @@ -31,115 +31,110 @@ import ch.qos.logback.core.util.CloseUtil; * * @author Carl Harris */ -class RemoteReceiverStreamClient - extends ContextAwareBase implements RemoteReceiverClient { +class RemoteReceiverStreamClient extends ContextAwareBase implements RemoteReceiverClient { - private final String clientId; - private final Socket socket; - private final OutputStream outputStream; - - private BlockingQueue queue; - - /** - * Constructs a new client. - * @param id identifier string for the client - * @param socket socket to which logging events will be written - */ - public RemoteReceiverStreamClient(String id, Socket socket) { - this.clientId = "client " + id + ": "; - this.socket = socket; - this.outputStream = null; - } + private final String clientId; + private final Socket socket; + private final OutputStream outputStream; - /** - * Constructs a new client. - *

- * This constructor exists primarily to support unit tests where it - * is inconvenient to have to create a socket for the test. - * - * @param id identifier string for the client - * @param outputStream output stream to which logging Events will be written - */ - RemoteReceiverStreamClient(String id, OutputStream outputStream) { - this.clientId = "client " + id + ": "; - this.socket = null; - this.outputStream = outputStream; - } - - /** - * {@inheritDoc} - */ - public void setQueue(BlockingQueue queue) { - this.queue = queue; - } + private BlockingQueue queue; - /** - * {@inheritDoc} - */ - public boolean offer(Serializable event) { - if (queue == null) { - throw new IllegalStateException("client has no event queue"); + /** + * Constructs a new client. + * @param id identifier string for the client + * @param socket socket to which logging events will be written + */ + public RemoteReceiverStreamClient(String id, Socket socket) { + this.clientId = "client " + id + ": "; + this.socket = socket; + this.outputStream = null; } - return queue.offer(event); - } - /** - * {@inheritDoc} - */ - public void close() { - if (socket == null) return; - CloseUtil.closeQuietly(socket); - } + /** + * Constructs a new client. + *

+ * This constructor exists primarily to support unit tests where it + * is inconvenient to have to create a socket for the test. + * + * @param id identifier string for the client + * @param outputStream output stream to which logging Events will be written + */ + RemoteReceiverStreamClient(String id, OutputStream outputStream) { + this.clientId = "client " + id + ": "; + this.socket = null; + this.outputStream = outputStream; + } - /** - * {@inheritDoc} - */ - public void run() { - addInfo(clientId + "connected"); + /** + * {@inheritDoc} + */ + public void setQueue(BlockingQueue queue) { + this.queue = queue; + } - ObjectOutputStream oos = null; - try { - int counter = 0; - oos = createObjectOutputStream(); - while (!Thread.currentThread().isInterrupted()) { - try { - Serializable event = queue.take(); - oos.writeObject(event); - oos.flush(); - if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) { - // failing to reset the stream periodically will result in a - // serious memory leak (as noted in AbstractSocketAppender) - counter = 0; - oos.reset(); - } + /** + * {@inheritDoc} + */ + public boolean offer(Serializable event) { + if (queue == null) { + throw new IllegalStateException("client has no event queue"); } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } - } - } - catch (SocketException ex) { - addInfo(clientId + ex); - } - catch (IOException ex) { - addError(clientId + ex); + return queue.offer(event); } - catch (RuntimeException ex) { - addError(clientId + ex); + + /** + * {@inheritDoc} + */ + public void close() { + if (socket == null) + return; + CloseUtil.closeQuietly(socket); } - finally { - if (oos != null) { - CloseUtil.closeQuietly(oos); - } - close(); - addInfo(clientId + "connection closed"); + + /** + * {@inheritDoc} + */ + public void run() { + addInfo(clientId + "connected"); + + ObjectOutputStream oos = null; + try { + int counter = 0; + oos = createObjectOutputStream(); + while (!Thread.currentThread().isInterrupted()) { + try { + Serializable event = queue.take(); + oos.writeObject(event); + oos.flush(); + if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) { + // failing to reset the stream periodically will result in a + // serious memory leak (as noted in AbstractSocketAppender) + counter = 0; + oos.reset(); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + } catch (SocketException ex) { + addInfo(clientId + ex); + } catch (IOException ex) { + addError(clientId + ex); + } catch (RuntimeException ex) { + addError(clientId + ex); + } finally { + if (oos != null) { + CloseUtil.closeQuietly(oos); + } + close(); + addInfo(clientId + "connection closed"); + } } - } - private ObjectOutputStream createObjectOutputStream() throws IOException { - if (socket == null) { - return new ObjectOutputStream(outputStream); + private ObjectOutputStream createObjectOutputStream() throws IOException { + if (socket == null) { + return new ObjectOutputStream(outputStream); + } + return new ObjectOutputStream(socket.getOutputStream()); } - return new ObjectOutputStream(socket.getOutputStream()); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBase.java index c4ecffd35d3decc3dcb7e986d11244788aa47fa4..f93deacf599ab28180e04b46d3e92e44b5fee943 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBase.java @@ -28,53 +28,50 @@ import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; * * @author Carl Harris */ -public abstract class SSLServerSocketAppenderBase - extends AbstractServerSocketAppender implements SSLComponent { +public abstract class SSLServerSocketAppenderBase extends AbstractServerSocketAppender implements SSLComponent { - private SSLConfiguration ssl; - private ServerSocketFactory socketFactory; - - @Override - protected ServerSocketFactory getServerSocketFactory() { - return socketFactory; - } + private SSLConfiguration ssl; + private ServerSocketFactory socketFactory; - /** - * {@inheritDoc} - */ - @Override - public void start() { - try { - SSLContext sslContext = getSsl().createContext(this); - SSLParametersConfiguration parameters = getSsl().getParameters(); - parameters.setContext(getContext()); - socketFactory = new ConfigurableSSLServerSocketFactory(parameters, - sslContext.getServerSocketFactory()); - super.start(); + @Override + protected ServerSocketFactory getServerSocketFactory() { + return socketFactory; } - catch (Exception ex) { - addError(ex.getMessage(), ex); + + /** + * {@inheritDoc} + */ + @Override + public void start() { + try { + SSLContext sslContext = getSsl().createContext(this); + SSLParametersConfiguration parameters = getSsl().getParameters(); + parameters.setContext(getContext()); + socketFactory = new ConfigurableSSLServerSocketFactory(parameters, sslContext.getServerSocketFactory()); + super.start(); + } catch (Exception ex) { + addError(ex.getMessage(), ex); + } + } + + /** + * Gets the SSL configuration. + * @return SSL configuration; if no configuration has been set, a + * default configuration is returned + */ + public SSLConfiguration getSsl() { + if (ssl == null) { + ssl = new SSLConfiguration(); + } + return ssl; } - } - /** - * Gets the SSL configuration. - * @return SSL configuration; if no configuration has been set, a - * default configuration is returned - */ - public SSLConfiguration getSsl() { - if (ssl == null) { - ssl = new SSLConfiguration(); + /** + * Sets the SSL configuration. + * @param ssl the SSL configuration to set + */ + public void setSsl(SSLConfiguration ssl) { + this.ssl = ssl; } - return ssl; - } - /** - * Sets the SSL configuration. - * @param ssl the SSL configuration to set - */ - public void setSsl(SSLConfiguration ssl) { - this.ssl = ssl; - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerListener.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerListener.java index 7df2a123837b2a034b284dac162d53069d9ea1e0..376ac284610617272123185ee3fac407af683921 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerListener.java @@ -34,34 +34,34 @@ import java.io.IOException; */ public interface ServerListener extends Closeable { - /** - * Accepts the next client that appears on this listener. - *

- * An implementation of this method is expected to block the calling thread - * and not return until either a client appears or an exception occurs. - * - * @return client object - * @throws IOException - * @throws InterruptedException - */ - T acceptClient() throws IOException, InterruptedException; - - /** - * Closes any underlying {@link Closeable} resources associated with this - * listener. - *

- * Note that (as described in Doug Lea's discussion about interrupting I/O - * operations in "Concurrent Programming in Java" (Addison-Wesley - * Professional, 2nd edition, 1999) this method is used to interrupt - * any blocked I/O operation in the client when the server is shutting - * down. The client implementation must anticipate this potential, - * and gracefully exit when the blocked I/O operation throws the - * relevant {@link IOException} subclass. - *

- * Note also, that unlike {@link Closeable#close()} this method is not - * permitted to propagate any {@link IOException} that occurs when closing - * the underlying resource(s). - */ - void close(); - + /** + * Accepts the next client that appears on this listener. + *

+ * An implementation of this method is expected to block the calling thread + * and not return until either a client appears or an exception occurs. + * + * @return client object + * @throws IOException + * @throws InterruptedException + */ + T acceptClient() throws IOException, InterruptedException; + + /** + * Closes any underlying {@link Closeable} resources associated with this + * listener. + *

+ * Note that (as described in Doug Lea's discussion about interrupting I/O + * operations in "Concurrent Programming in Java" (Addison-Wesley + * Professional, 2nd edition, 1999) this method is used to interrupt + * any blocked I/O operation in the client when the server is shutting + * down. The client implementation must anticipate this potential, + * and gracefully exit when the blocked I/O operation throws the + * relevant {@link IOException} subclass. + *

+ * Note also, that unlike {@link Closeable#close()} this method is not + * permitted to propagate any {@link IOException} that occurs when closing + * the underlying resource(s). + */ + void close(); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerRunner.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerRunner.java index 3c59f1ecf50558fa8bbf0a6aca5e3153ed86d7fc..07993ab998999f160293868c0448969da856fae2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerRunner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerRunner.java @@ -28,26 +28,26 @@ import ch.qos.logback.core.spi.ContextAware; */ public interface ServerRunner extends ContextAware, Runnable { - /** - * Gets a flag indicating whether the server is currently running. - * @return flag state - */ - boolean isRunning(); - - /** - * Stops execution of the runner. - *

- * This method must cause all I/O and thread resources associated with - * the runner to be released. If the receiver has not been started, this - * method must have no effect. - * @throws IOException - */ - void stop() throws IOException; + /** + * Gets a flag indicating whether the server is currently running. + * @return flag state + */ + boolean isRunning(); + + /** + * Stops execution of the runner. + *

+ * This method must cause all I/O and thread resources associated with + * the runner to be released. If the receiver has not been started, this + * method must have no effect. + * @throws IOException + */ + void stop() throws IOException; + + /** + * Presents each connected client to the given visitor. + * @param visitor the subject visitor + */ + void accept(ClientVisitor visitor); - /** - * Presents each connected client to the given visitor. - * @param visitor the subject visitor - */ - void accept(ClientVisitor visitor); - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerSocketListener.java b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerSocketListener.java index 808c651eede60491acf87cfa6cdf149bf055ca73..8f260aac71d95ea5e50070d2cf555909833a71dd 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerSocketListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/server/ServerSocketListener.java @@ -25,65 +25,62 @@ import ch.qos.logback.core.util.CloseUtil; * * @author Carl Harris */ -public abstract class ServerSocketListener - implements ServerListener { +public abstract class ServerSocketListener implements ServerListener { - private final ServerSocket serverSocket; + private final ServerSocket serverSocket; - /** - * Constructs a new listener. - * @param serverSocket server socket delegate - */ - public ServerSocketListener(ServerSocket serverSocket) { - this.serverSocket = serverSocket; - } + /** + * Constructs a new listener. + * @param serverSocket server socket delegate + */ + public ServerSocketListener(ServerSocket serverSocket) { + this.serverSocket = serverSocket; + } - /** - * {@inheritDoc} - */ - public T acceptClient() throws IOException { - Socket socket = serverSocket.accept(); - return createClient( - socketAddressToString(socket.getRemoteSocketAddress()), socket); - } + /** + * {@inheritDoc} + */ + public T acceptClient() throws IOException { + Socket socket = serverSocket.accept(); + return createClient(socketAddressToString(socket.getRemoteSocketAddress()), socket); + } - /** - * Creates the client object for a new socket connection - * @param id identifier string for the client - * @param socket client's socket connection - * @return client object - * @throws IOException - */ - protected abstract T createClient(String id, Socket socket) - throws IOException; - - /** - * {@inheritDoc} - */ - public void close() { - CloseUtil.closeQuietly(serverSocket); - } + /** + * Creates the client object for a new socket connection + * @param id identifier string for the client + * @param socket client's socket connection + * @return client object + * @throws IOException + */ + protected abstract T createClient(String id, Socket socket) throws IOException; - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return socketAddressToString(serverSocket.getLocalSocketAddress()); - } + /** + * {@inheritDoc} + */ + public void close() { + CloseUtil.closeQuietly(serverSocket); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return socketAddressToString(serverSocket.getLocalSocketAddress()); + } - /** - * Converts a socket address to a reasonable display string. - * @param address the subject socket address - * @return display string - */ - private String socketAddressToString(SocketAddress address) { - String addr = address.toString(); - int i = addr.indexOf("/"); - if (i >= 0) { - addr = addr.substring(i + 1); + /** + * Converts a socket address to a reasonable display string. + * @param address the subject socket address + * @return display string + */ + private String socketAddressToString(SocketAddress address) { + String addr = address.toString(); + int i = addr.indexOf("/"); + if (i >= 0) { + addr = addr.substring(i + 1); + } + return addr; } - return addr; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLServerSocketFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLServerSocketFactory.java index 837fb459964d2ca375bab8af01089bd5d4d45d58..8ad96f35b403ad2d9fa4d583f42db99d4a241065 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLServerSocketFactory.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLServerSocketFactory.java @@ -35,55 +35,49 @@ import javax.net.ssl.SSLServerSocketFactory; */ public class ConfigurableSSLServerSocketFactory extends ServerSocketFactory { - private final SSLParametersConfiguration parameters; - private final SSLServerSocketFactory delegate; + private final SSLParametersConfiguration parameters; + private final SSLServerSocketFactory delegate; - /** - * Creates a new factory. - * @param parameters parameters that will be configured on each - * socket created by the factory - * @param delegate socket factory that will be called upon to create - * server sockets before configuration - */ - public ConfigurableSSLServerSocketFactory( - SSLParametersConfiguration parameters, SSLServerSocketFactory delegate) { - this.parameters = parameters; - this.delegate = delegate; - } + /** + * Creates a new factory. + * @param parameters parameters that will be configured on each + * socket created by the factory + * @param delegate socket factory that will be called upon to create + * server sockets before configuration + */ + public ConfigurableSSLServerSocketFactory(SSLParametersConfiguration parameters, SSLServerSocketFactory delegate) { + this.parameters = parameters; + this.delegate = delegate; + } - /** - * {@inheritDoc} - */ - @Override - public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) - throws IOException { - SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket( - port, backlog, ifAddress); - parameters.configure(new SSLConfigurableServerSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { + SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket(port, backlog, ifAddress); + parameters.configure(new SSLConfigurableServerSocket(socket)); + return socket; + } - /** - * {@inheritDoc} - */ - @Override - public ServerSocket createServerSocket(int port, int backlog) - throws IOException { - SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket( - port, backlog); - parameters.configure(new SSLConfigurableServerSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public ServerSocket createServerSocket(int port, int backlog) throws IOException { + SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket(port, backlog); + parameters.configure(new SSLConfigurableServerSocket(socket)); + return socket; + } - /** - * {@inheritDoc} - */ - @Override - public ServerSocket createServerSocket(int port) throws IOException { - SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket( - port); - parameters.configure(new SSLConfigurableServerSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public ServerSocket createServerSocket(int port) throws IOException { + SSLServerSocket socket = (SSLServerSocket) delegate.createServerSocket(port); + parameters.configure(new SSLConfigurableServerSocket(socket)); + return socket; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLSocketFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLSocketFactory.java index c3d3c9b27a649ed8d7c5cec415f468fad124e2b4..289f37719acd75548500bf8eaf1731c8a270f904 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLSocketFactory.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/ConfigurableSSLSocketFactory.java @@ -36,65 +36,59 @@ import javax.net.ssl.SSLSocketFactory; */ public class ConfigurableSSLSocketFactory extends SocketFactory { - private final SSLParametersConfiguration parameters; - private final SSLSocketFactory delegate; + private final SSLParametersConfiguration parameters; + private final SSLSocketFactory delegate; - /** - * Creates a new factory. - * @param parameters parameters that will be configured on each - * socket created by the factory - * @param delegate socket factory that will be called upon to create - * sockets before configuration - */ - public ConfigurableSSLSocketFactory(SSLParametersConfiguration parameters, - SSLSocketFactory delegate) { - this.parameters = parameters; - this.delegate = delegate; - } + /** + * Creates a new factory. + * @param parameters parameters that will be configured on each + * socket created by the factory + * @param delegate socket factory that will be called upon to create + * sockets before configuration + */ + public ConfigurableSSLSocketFactory(SSLParametersConfiguration parameters, SSLSocketFactory delegate) { + this.parameters = parameters; + this.delegate = delegate; + } - /** - * {@inheritDoc} - */ - @Override - public Socket createSocket(InetAddress address, int port, - InetAddress localAddress, int localPort) throws IOException { - SSLSocket socket = (SSLSocket) delegate.createSocket(address, port, - localAddress, localPort); - parameters.configure(new SSLConfigurableSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { + SSLSocket socket = (SSLSocket) delegate.createSocket(address, port, localAddress, localPort); + parameters.configure(new SSLConfigurableSocket(socket)); + return socket; + } - /** - * {@inheritDoc} - */ - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - SSLSocket socket = (SSLSocket) delegate.createSocket(host, port); - parameters.configure(new SSLConfigurableSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public Socket createSocket(InetAddress host, int port) throws IOException { + SSLSocket socket = (SSLSocket) delegate.createSocket(host, port); + parameters.configure(new SSLConfigurableSocket(socket)); + return socket; + } - /** - * {@inheritDoc} - */ - @Override - public Socket createSocket(String host, int port, InetAddress localHost, - int localPort) throws IOException, UnknownHostException { - SSLSocket socket = (SSLSocket) delegate.createSocket(host, port, - localHost, localPort); - parameters.configure(new SSLConfigurableSocket(socket)); - return socket; - } + /** + * {@inheritDoc} + */ + @Override + public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { + SSLSocket socket = (SSLSocket) delegate.createSocket(host, port, localHost, localPort); + parameters.configure(new SSLConfigurableSocket(socket)); + return socket; + } + + /** + * {@inheritDoc} + */ + @Override + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + SSLSocket socket = (SSLSocket) delegate.createSocket(host, port); + parameters.configure(new SSLConfigurableSocket(socket)); + return socket; + } - /** - * {@inheritDoc} - */ - @Override - public Socket createSocket(String host, int port) throws IOException, - UnknownHostException { - SSLSocket socket = (SSLSocket) delegate.createSocket(host, port); - parameters.configure(new SSLConfigurableSocket(socket)); - return socket; - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBean.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBean.java index 100332de2efd8605d49c27d843e90931c40fe207..ee6923f74efc79d87f7056a78be9fa3ca96bbcec 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBean.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBean.java @@ -28,64 +28,61 @@ import javax.net.ssl.KeyManagerFactory; */ public class KeyManagerFactoryFactoryBean { - private String algorithm; - private String provider; + private String algorithm; + private String provider; - /** - * Creates a {@link KeyManagerFactory} using the receiver's configuration. - * @return factory object - * @throws NoSuchProviderException if the provider specified by - * {@link #setProvider(String)} is not known to the platform - * @throws NoSuchAlgorithmException if the algorithm specified by - * {@link #setAlgorithm(String)} is not known to the specified provider - * (or to the default platform provider if no provider is specified) - */ - public KeyManagerFactory createKeyManagerFactory() - throws NoSuchProviderException, NoSuchAlgorithmException { - - return getProvider() != null ? - KeyManagerFactory.getInstance(getAlgorithm(), getProvider()) - : KeyManagerFactory.getInstance(getAlgorithm()); - } - - /** - * Gets the algorithm name for the key manager factory. - * @return algorithm name (e.g. {@code SunX509}); the default algorithm - * (obtained from {@link KeyManagerFactory#getDefaultAlgorithm()}) - * is returned if no algorithm has been configured - */ - public String getAlgorithm() { - if (algorithm == null) { - return KeyManagerFactory.getDefaultAlgorithm(); + /** + * Creates a {@link KeyManagerFactory} using the receiver's configuration. + * @return factory object + * @throws NoSuchProviderException if the provider specified by + * {@link #setProvider(String)} is not known to the platform + * @throws NoSuchAlgorithmException if the algorithm specified by + * {@link #setAlgorithm(String)} is not known to the specified provider + * (or to the default platform provider if no provider is specified) + */ + public KeyManagerFactory createKeyManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException { + + return getProvider() != null ? KeyManagerFactory.getInstance(getAlgorithm(), getProvider()) : KeyManagerFactory.getInstance(getAlgorithm()); + } + + /** + * Gets the algorithm name for the key manager factory. + * @return algorithm name (e.g. {@code SunX509}); the default algorithm + * (obtained from {@link KeyManagerFactory#getDefaultAlgorithm()}) + * is returned if no algorithm has been configured + */ + public String getAlgorithm() { + if (algorithm == null) { + return KeyManagerFactory.getDefaultAlgorithm(); + } + return algorithm; } - return algorithm; - } - /** - * Sets the algorithm name for the key manager factory. - * @param algorithm an algorithm name, which must be recognized by the - * provider specified by {@link #setProvider(String)} or by the - * platform's default provider if no provider is specified. - */ - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } + /** + * Sets the algorithm name for the key manager factory. + * @param algorithm an algorithm name, which must be recognized by the + * provider specified by {@link #setProvider(String)} or by the + * platform's default provider if no provider is specified. + */ + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } - /** - * Gets the JSSE provider name for the key manager factory. - * @return provider name - */ - public String getProvider() { - return provider; - } + /** + * Gets the JSSE provider name for the key manager factory. + * @return provider name + */ + public String getProvider() { + return provider; + } - /** - * Sets the JSSE provider name for the key manager factory. - * @param provider name of the JSSE provider to utilize in creating the - * key manager factory - */ - public void setProvider(String provider) { - this.provider = provider; - } + /** + * Sets the JSSE provider name for the key manager factory. + * @param provider name of the JSSE provider to utilize in creating the + * key manager factory + */ + public void setProvider(String provider) { + this.provider = provider; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBean.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBean.java index 1c2f49811ae9fbe0e1d3c41f80e4cc373357cece..0f0b72a5fd0fc7c72a40520f94ced276f1a632f9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBean.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBean.java @@ -24,7 +24,6 @@ import java.security.NoSuchProviderException; import ch.qos.logback.core.util.LocationUtil; - /** * A factory bean for a JCA {@link KeyStore}. *

@@ -35,152 +34,140 @@ import ch.qos.logback.core.util.LocationUtil; */ public class KeyStoreFactoryBean { - private String location; - private String provider; - private String type; - private String password; - - /** - * Creates a new {@link KeyStore} using the receiver's configuration. - * @return key store - * @throws NoSuchProviderException if the provider specified by - * {@link #setProvider(String)} is not known to the platform - * @throws NoSuchAlgorithmException if the key store type specified by - * {@link #setType(String)} is not known to the specified provider - * (or the platform's default provider if the provider isn't specified) - * @throws KeyStoreException if some other error occurs in loading - * the key store from the resource specified by - * {@link #setLocation(String)} - */ - public KeyStore createKeyStore() throws NoSuchProviderException, - NoSuchAlgorithmException, KeyStoreException { - - if (getLocation() == null) { - throw new IllegalArgumentException("location is required"); + private String location; + private String provider; + private String type; + private String password; + + /** + * Creates a new {@link KeyStore} using the receiver's configuration. + * @return key store + * @throws NoSuchProviderException if the provider specified by + * {@link #setProvider(String)} is not known to the platform + * @throws NoSuchAlgorithmException if the key store type specified by + * {@link #setType(String)} is not known to the specified provider + * (or the platform's default provider if the provider isn't specified) + * @throws KeyStoreException if some other error occurs in loading + * the key store from the resource specified by + * {@link #setLocation(String)} + */ + public KeyStore createKeyStore() throws NoSuchProviderException, NoSuchAlgorithmException, KeyStoreException { + + if (getLocation() == null) { + throw new IllegalArgumentException("location is required"); + } + + InputStream inputStream = null; + try { + URL url = LocationUtil.urlForResource(getLocation()); + inputStream = url.openStream(); + KeyStore keyStore = newKeyStore(); + keyStore.load(inputStream, getPassword().toCharArray()); + return keyStore; + } catch (NoSuchProviderException ex) { + throw new NoSuchProviderException("no such keystore provider: " + getProvider()); + } catch (NoSuchAlgorithmException ex) { + throw new NoSuchAlgorithmException("no such keystore type: " + getType()); + } catch (FileNotFoundException ex) { + throw new KeyStoreException(getLocation() + ": file not found"); + } catch (Exception ex) { + throw new KeyStoreException(getLocation() + ": " + ex.getMessage(), ex); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException ex) { + ex.printStackTrace(System.err); + } + } + } + + /** + * Invokes the appropriate JCE factory method to obtain a new + * {@link KeyStore} object. + */ + private KeyStore newKeyStore() throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException { + + return getProvider() != null ? KeyStore.getInstance(getType(), getProvider()) : KeyStore.getInstance(getType()); + } + + /** + * Gets the location of the key store resource. + * @return a String containing a URL for the resource + */ + public String getLocation() { + return location; } - - InputStream inputStream = null; - try { - URL url = LocationUtil.urlForResource(getLocation()); - inputStream = url.openStream(); - KeyStore keyStore = newKeyStore(); - keyStore.load(inputStream, getPassword().toCharArray()); - return keyStore; + + /** + * Sets the location of the key store resource. + * @param location a String containing a URL for the resource; if the + * URL string isn't prefixed by a scheme, the path is assumed to be + * relative to the root of the classpath. + */ + public void setLocation(String location) { + this.location = location; } - catch (NoSuchProviderException ex) { - throw new NoSuchProviderException("no such keystore provider: " - + getProvider()); + + /** + * Gets the type of key store to load. + * @return a key store type name (e.g. {@code JKS}); the + * {@link SSL#DEFAULT_KEYSTORE_TYPE} is returned if no type has been configured + */ + public String getType() { + if (type == null) { + return SSL.DEFAULT_KEYSTORE_TYPE; + } + return type; } - catch (NoSuchAlgorithmException ex) { - throw new NoSuchAlgorithmException("no such keystore type: " - + getType()); + + /** + * Sets the type of key store to load. + * @param type a key store type name (e.g. {@code JKS}, {@code PKCS12}); + * the type specified must be supported by the provider specified by + * {@link #setProvider(String)} or by the platform's default provider + * if no provider is specified + */ + public void setType(String type) { + this.type = type; } - catch (FileNotFoundException ex) { - throw new KeyStoreException(getLocation() + ": file not found"); + + /** + * Gets the JCA key store provider name. + * @return provider name or {@code null} if no provider has been configured + */ + public String getProvider() { + return provider; } - catch (Exception ex) { - throw new KeyStoreException(getLocation() + ": " + ex.getMessage(), ex); + + /** + * Sets the JCA key store provider name. + * @param provider name of the JCA provider to utilize in creating the + * key store + */ + public void setProvider(String provider) { + this.provider = provider; } - finally { - try { - if (inputStream != null) { - inputStream.close(); + + /** + * Gets the password to use to access the key store. + * @return password string; the {@link SSL#DEFAULT_KEYSTORE_PASSWORD} is returned + * if no password has been configured + */ + public String getPassword() { + if (password == null) { + return SSL.DEFAULT_KEYSTORE_PASSWORD; } - } - catch (IOException ex) { - ex.printStackTrace(System.err); - } + return password; } - } - - /** - * Invokes the appropriate JCE factory method to obtain a new - * {@link KeyStore} object. - */ - private KeyStore newKeyStore() throws NoSuchAlgorithmException, - NoSuchProviderException, KeyStoreException { - - return getProvider() != null ? - KeyStore.getInstance(getType(), getProvider()) - : KeyStore.getInstance(getType()); - } - - /** - * Gets the location of the key store resource. - * @return a String containing a URL for the resource - */ - public String getLocation() { - return location; - } - - /** - * Sets the location of the key store resource. - * @param location a String containing a URL for the resource; if the - * URL string isn't prefixed by a scheme, the path is assumed to be - * relative to the root of the classpath. - */ - public void setLocation(String location) { - this.location = location; - } - - /** - * Gets the type of key store to load. - * @return a key store type name (e.g. {@code JKS}); the - * {@link SSL#DEFAULT_KEYSTORE_TYPE} is returned if no type has been configured - */ - public String getType() { - if (type == null) { - return SSL.DEFAULT_KEYSTORE_TYPE; - } - return type; - } - - /** - * Sets the type of key store to load. - * @param type a key store type name (e.g. {@code JKS}, {@code PKCS12}); - * the type specified must be supported by the provider specified by - * {@link #setProvider(String)} or by the platform's default provider - * if no provider is specified - */ - public void setType(String type) { - this.type = type; - } - - /** - * Gets the JCA key store provider name. - * @return provider name or {@code null} if no provider has been configured - */ - public String getProvider() { - return provider; - } - - /** - * Sets the JCA key store provider name. - * @param provider name of the JCA provider to utilize in creating the - * key store - */ - public void setProvider(String provider) { - this.provider = provider; - } - - /** - * Gets the password to use to access the key store. - * @return password string; the {@link SSL#DEFAULT_KEYSTORE_PASSWORD} is returned - * if no password has been configured - */ - public String getPassword() { - if (password == null) { - return SSL.DEFAULT_KEYSTORE_PASSWORD; + + /** + * Sets the password to use to access the keystore. + * @param password the password to set + */ + public void setPassword(String password) { + this.password = password; } - return password; - } - - /** - * Sets the password to use to access the keystore. - * @param password the password to set - */ - public void setPassword(String password) { - this.password = password; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSL.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSL.java index ccd824d5af35b91fced558660db9cf58f6bf1817..c2df583fb30332035db8052ae30c35fb3028c4b2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSL.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSL.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.net.ssl; - /** * Various constants used by the SSL implementation. * @@ -21,16 +20,16 @@ package ch.qos.logback.core.net.ssl; */ public interface SSL { - /** Default secure transport protocol */ - String DEFAULT_PROTOCOL = "SSL"; - - /** Default key store type */ - String DEFAULT_KEYSTORE_TYPE = "JKS"; - - /** Default key store passphrase */ - String DEFAULT_KEYSTORE_PASSWORD = "changeit"; + /** Default secure transport protocol */ + String DEFAULT_PROTOCOL = "SSL"; + + /** Default key store type */ + String DEFAULT_KEYSTORE_TYPE = "JKS"; + + /** Default key store passphrase */ + String DEFAULT_KEYSTORE_PASSWORD = "changeit"; + + /** Default secure random generator algorithm */ + String DEFAULT_SECURE_RANDOM_ALGORITHM = "SHA1PRNG"; - /** Default secure random generator algorithm */ - String DEFAULT_SECURE_RANDOM_ALGORITHM = "SHA1PRNG"; - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLComponent.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLComponent.java index 4e2e8dea159f27382539ccad40390da80e254ad1..05f94753425884ba8bbd4c63f4a4feda6166373d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLComponent.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLComponent.java @@ -20,8 +20,8 @@ package ch.qos.logback.core.net.ssl; */ public interface SSLComponent { - SSLConfiguration getSsl(); - - void setSsl(SSLConfiguration ssl); - + SSLConfiguration getSsl(); + + void setSsl(SSLConfiguration ssl); + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurable.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurable.java index aabec57444bcf4fec82895e0d000bc373e685d08..519297485eddbca63911a67043fb815d374f7518 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurable.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurable.java @@ -24,62 +24,62 @@ package ch.qos.logback.core.net.ssl; */ public interface SSLConfigurable { - /** - * Gets the set of protocols that the SSL component enables by default. - * - * @return protocols (generally a subset of the set returned by - * {@link #getSupportedProtocols()}); the return value may be - * an empty array but must never be {@code null}. - */ - String[] getDefaultProtocols(); + /** + * Gets the set of protocols that the SSL component enables by default. + * + * @return protocols (generally a subset of the set returned by + * {@link #getSupportedProtocols()}); the return value may be + * an empty array but must never be {@code null}. + */ + String[] getDefaultProtocols(); - /** - * Gets the set of protocols that the SSL component supports. - * @return protocols supported protocols; the return value may be - * an empty array but must never be {@code null}. - */ - String[] getSupportedProtocols(); + /** + * Gets the set of protocols that the SSL component supports. + * @return protocols supported protocols; the return value may be + * an empty array but must never be {@code null}. + */ + String[] getSupportedProtocols(); - /** - * Sets the enabled protocols on the SSL component. - * @param cipherSuites the protocols to enable - */ - void setEnabledProtocols(String[] protocols); + /** + * Sets the enabled protocols on the SSL component. + * @param cipherSuites the protocols to enable + */ + void setEnabledProtocols(String[] protocols); + + /** + * Gets the set of cipher suites that the SSL component enables by default. + * + * @return cipher suites (generally a subset of the set returned by + * {@link #getSupportedCipherSuites()}); the return value may be + * an empty array but must never be {@code null} + */ + String[] getDefaultCipherSuites(); + + /** + * Gets the set of cipher suites that the SSL component supports. + * @return supported cipher suites; the return value may be + * an empty array but must never be {@code null} + */ + String[] getSupportedCipherSuites(); + + /** + * Sets the enabled cipher suites on the SSL component. + * @param cipherSuites the cipher suites to enable + */ + void setEnabledCipherSuites(String[] cipherSuites); + + /** + * Sets a flag indicating whether the SSL component should require + * client authentication. + * @param state the flag state to set + */ + void setNeedClientAuth(boolean state); + + /** + * Sets a flag indicating whether the SSL component should request + * client authentication. + * @param state the flag state to set + */ + void setWantClientAuth(boolean state); - /** - * Gets the set of cipher suites that the SSL component enables by default. - * - * @return cipher suites (generally a subset of the set returned by - * {@link #getSupportedCipherSuites()}); the return value may be - * an empty array but must never be {@code null} - */ - String[] getDefaultCipherSuites(); - - /** - * Gets the set of cipher suites that the SSL component supports. - * @return supported cipher suites; the return value may be - * an empty array but must never be {@code null} - */ - String[] getSupportedCipherSuites(); - - /** - * Sets the enabled cipher suites on the SSL component. - * @param cipherSuites the cipher suites to enable - */ - void setEnabledCipherSuites(String[] cipherSuites); - - /** - * Sets a flag indicating whether the SSL component should require - * client authentication. - * @param state the flag state to set - */ - void setNeedClientAuth(boolean state); - - /** - * Sets a flag indicating whether the SSL component should request - * client authentication. - * @param state the flag state to set - */ - void setWantClientAuth(boolean state); - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableServerSocket.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableServerSocket.java index 23524e3ffbbd695c9f9a20808410242c71e5b9ec..fa5af3f676399f7a593b5fe036bbb93f0e1792cc 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableServerSocket.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableServerSocket.java @@ -22,42 +22,42 @@ import javax.net.ssl.SSLServerSocket; */ public class SSLConfigurableServerSocket implements SSLConfigurable { - private final SSLServerSocket delegate; + private final SSLServerSocket delegate; - public SSLConfigurableServerSocket(SSLServerSocket delegate) { - this.delegate = delegate; - } + public SSLConfigurableServerSocket(SSLServerSocket delegate) { + this.delegate = delegate; + } - public String[] getDefaultProtocols() { - return delegate.getEnabledProtocols(); - } + public String[] getDefaultProtocols() { + return delegate.getEnabledProtocols(); + } - public String[] getSupportedProtocols() { - return delegate.getSupportedProtocols(); - } + public String[] getSupportedProtocols() { + return delegate.getSupportedProtocols(); + } - public void setEnabledProtocols(String[] protocols) { - delegate.setEnabledProtocols(protocols); - } + public void setEnabledProtocols(String[] protocols) { + delegate.setEnabledProtocols(protocols); + } - public String[] getDefaultCipherSuites() { - return delegate.getEnabledCipherSuites(); - } + public String[] getDefaultCipherSuites() { + return delegate.getEnabledCipherSuites(); + } - public String[] getSupportedCipherSuites() { - return delegate.getSupportedCipherSuites(); - } + public String[] getSupportedCipherSuites() { + return delegate.getSupportedCipherSuites(); + } - public void setEnabledCipherSuites(String[] suites) { - delegate.setEnabledCipherSuites(suites); - } + public void setEnabledCipherSuites(String[] suites) { + delegate.setEnabledCipherSuites(suites); + } - public void setNeedClientAuth(boolean state) { - delegate.setNeedClientAuth(state); - } + public void setNeedClientAuth(boolean state) { + delegate.setNeedClientAuth(state); + } + + public void setWantClientAuth(boolean state) { + delegate.setWantClientAuth(state); + } - public void setWantClientAuth(boolean state) { - delegate.setWantClientAuth(state); - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableSocket.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableSocket.java index fc62c6f745fe078f172383d0be836fa52d3273ba..2628718926cdfa5b1608bae5ae4cdc3c3e84a690 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableSocket.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfigurableSocket.java @@ -22,42 +22,42 @@ import javax.net.ssl.SSLSocket; */ public class SSLConfigurableSocket implements SSLConfigurable { - private final SSLSocket delegate; + private final SSLSocket delegate; - public SSLConfigurableSocket(SSLSocket delegate) { - this.delegate = delegate; - } + public SSLConfigurableSocket(SSLSocket delegate) { + this.delegate = delegate; + } - public String[] getDefaultProtocols() { - return delegate.getEnabledProtocols(); - } + public String[] getDefaultProtocols() { + return delegate.getEnabledProtocols(); + } - public String[] getSupportedProtocols() { - return delegate.getSupportedProtocols(); - } + public String[] getSupportedProtocols() { + return delegate.getSupportedProtocols(); + } - public void setEnabledProtocols(String[] protocols) { - delegate.setEnabledProtocols(protocols); - } + public void setEnabledProtocols(String[] protocols) { + delegate.setEnabledProtocols(protocols); + } - public String[] getDefaultCipherSuites() { - return delegate.getEnabledCipherSuites(); - } + public String[] getDefaultCipherSuites() { + return delegate.getEnabledCipherSuites(); + } - public String[] getSupportedCipherSuites() { - return delegate.getSupportedCipherSuites(); - } + public String[] getSupportedCipherSuites() { + return delegate.getSupportedCipherSuites(); + } - public void setEnabledCipherSuites(String[] suites) { - delegate.setEnabledCipherSuites(suites); - } + public void setEnabledCipherSuites(String[] suites) { + delegate.setEnabledCipherSuites(suites); + } - public void setNeedClientAuth(boolean state) { - delegate.setNeedClientAuth(state); - } + public void setNeedClientAuth(boolean state) { + delegate.setNeedClientAuth(state); + } + + public void setWantClientAuth(boolean state) { + delegate.setWantClientAuth(state); + } - public void setWantClientAuth(boolean state) { - delegate.setWantClientAuth(state); - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfiguration.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfiguration.java index 7aebfa577c317a6135f3aa3f64c7384b69e03526..d196b8d9685bae10834ddaca9f94f765ca14387f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfiguration.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLConfiguration.java @@ -23,26 +23,26 @@ import javax.net.ssl.SSLContext; */ public class SSLConfiguration extends SSLContextFactoryBean { - private SSLParametersConfiguration parameters; + private SSLParametersConfiguration parameters; - /** - * Gets the SSL parameters configuration. - * @return parameters configuration; if no parameters object was - * configured, a default parameters object is returned - */ - public SSLParametersConfiguration getParameters() { - if (parameters == null) { - parameters = new SSLParametersConfiguration(); + /** + * Gets the SSL parameters configuration. + * @return parameters configuration; if no parameters object was + * configured, a default parameters object is returned + */ + public SSLParametersConfiguration getParameters() { + if (parameters == null) { + parameters = new SSLParametersConfiguration(); + } + return parameters; } - return parameters; - } - /** - * Sets the SSL parameters configuration. - * @param parameters the parameters configuration to set - */ - public void setParameters(SSLParametersConfiguration parameters) { - this.parameters = parameters; - } + /** + * Sets the SSL parameters configuration. + * @param parameters the parameters configuration to set + */ + public void setParameters(SSLParametersConfiguration parameters) { + this.parameters = parameters; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBean.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBean.java index f2ec9903e89e1660282828153764d170d6e47b32..9f7f0786042860a6ad94073b516191a283b20fb3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBean.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBean.java @@ -39,303 +39,286 @@ import ch.qos.logback.core.spi.ContextAware; * @author Carl Harris */ public class SSLContextFactoryBean { - - private static final String JSSE_KEY_STORE_PROPERTY = "javax.net.ssl.keyStore"; - private static final String JSSE_TRUST_STORE_PROPERTY = "javax.net.ssl.trustStore"; - - private KeyStoreFactoryBean keyStore; - private KeyStoreFactoryBean trustStore; - private SecureRandomFactoryBean secureRandom; - private KeyManagerFactoryFactoryBean keyManagerFactory; - private TrustManagerFactoryFactoryBean trustManagerFactory; - private String protocol; - private String provider; - - /** - * Creates a new {@link SSLContext} using the receiver's configuration. - * @param context context for status messages - * @return {@link SSLContext} object - * @throws NoSuchProviderException if a provider specified for one of the - * JCA or JSSE components utilized in creating the context is not - * known to the platform - * @throws NoSuchAlgorithmException if a JCA or JSSE algorithm, protocol, - * or type name specified for one of the context's components is not - * known to a given provider (or platform default provider for the - * component) - * @throws KeyManagementException if an error occurs in creating a - * {@link KeyManager} for the context - * @throws UnrecoverableKeyException if a private key needed by a - * {@link KeyManager} cannot be obtained from a key store - * @throws KeyStoreException if an error occurs in reading the - * contents of a key store - * @throws CertificateException if an error occurs in reading the - * contents of a certificate - */ - public SSLContext createContext(ContextAware context) throws NoSuchProviderException, - NoSuchAlgorithmException, KeyManagementException, - UnrecoverableKeyException, KeyStoreException, CertificateException { - - SSLContext sslContext = getProvider() != null ? - SSLContext.getInstance(getProtocol(), getProvider()) - : SSLContext.getInstance(getProtocol()); - - context.addInfo("SSL protocol '" + sslContext.getProtocol() - + "' provider '" + sslContext.getProvider() + "'"); - - KeyManager[] keyManagers = createKeyManagers(context); - TrustManager[] trustManagers = createTrustManagers(context); - SecureRandom secureRandom = createSecureRandom(context); - sslContext.init(keyManagers, trustManagers, secureRandom); - return sslContext; - } - - /** - * Creates key managers using the receiver's key store configuration. - * @param context context for status messages - * @return an array of key managers or {@code null} if no key store - * configuration was provided - * @throws NoSuchProviderException if a provider specified for one - * of the key manager components is not known to the platform - * @throws NoSuchAlgorithmException if an algorithm specified for - * one of the key manager components is not known to the relevant - * provider - * @throws KeyStoreException if an error occurs in reading a key store - */ - private KeyManager[] createKeyManagers(ContextAware context) - throws NoSuchProviderException, NoSuchAlgorithmException, - UnrecoverableKeyException, KeyStoreException { - - if (getKeyStore() == null) return null; - - KeyStore keyStore = getKeyStore().createKeyStore(); - context.addInfo( - "key store of type '" + keyStore.getType() - + "' provider '" + keyStore.getProvider() - + "': " + getKeyStore().getLocation()); - - KeyManagerFactory kmf = getKeyManagerFactory().createKeyManagerFactory(); - context.addInfo("key manager algorithm '" + kmf.getAlgorithm() - + "' provider '" + kmf.getProvider() + "'"); - - char[] passphrase = getKeyStore().getPassword().toCharArray(); - kmf.init(keyStore, passphrase); - return kmf.getKeyManagers(); - } - - /** - * Creates trust managers using the receiver's trust store configuration. - * @param context context for status messages - * @return an array of trust managers or {@code null} if no trust store - * configuration was provided - * @throws NoSuchProviderException if a provider specified for one - * of the trust manager components is not known to the platform - * @throws NoSuchAlgorithmException if an algorithm specified for - * one of the trust manager components is not known to the relevant - * provider - * @throws KeyStoreException if an error occurs in reading a key - * store containing trust anchors - */ - private TrustManager[] createTrustManagers(ContextAware context) - throws NoSuchProviderException, NoSuchAlgorithmException, - KeyStoreException { - - if (getTrustStore() == null) return null; - - KeyStore trustStore = getTrustStore().createKeyStore(); - context.addInfo( - "trust store of type '" + trustStore.getType() - + "' provider '" + trustStore.getProvider() - + "': " + getTrustStore().getLocation()); - - TrustManagerFactory tmf = getTrustManagerFactory() - .createTrustManagerFactory(); - context.addInfo("trust manager algorithm '" + tmf.getAlgorithm() - + "' provider '" + tmf.getProvider() + "'"); - - tmf.init(trustStore); - return tmf.getTrustManagers(); - } - - private SecureRandom createSecureRandom(ContextAware context) - throws NoSuchProviderException, NoSuchAlgorithmException { - - SecureRandom secureRandom = getSecureRandom().createSecureRandom(); - context.addInfo("secure random algorithm '" + secureRandom.getAlgorithm() - + "' provider '" + secureRandom.getProvider() + "'"); - - return secureRandom; - } - - /** - * Gets the key store configuration. - * @return key store factory bean or {@code null} if no key store - * configuration was provided - */ - public KeyStoreFactoryBean getKeyStore() { - if (keyStore == null) { - keyStore = keyStoreFromSystemProperties(JSSE_KEY_STORE_PROPERTY); + + private static final String JSSE_KEY_STORE_PROPERTY = "javax.net.ssl.keyStore"; + private static final String JSSE_TRUST_STORE_PROPERTY = "javax.net.ssl.trustStore"; + + private KeyStoreFactoryBean keyStore; + private KeyStoreFactoryBean trustStore; + private SecureRandomFactoryBean secureRandom; + private KeyManagerFactoryFactoryBean keyManagerFactory; + private TrustManagerFactoryFactoryBean trustManagerFactory; + private String protocol; + private String provider; + + /** + * Creates a new {@link SSLContext} using the receiver's configuration. + * @param context context for status messages + * @return {@link SSLContext} object + * @throws NoSuchProviderException if a provider specified for one of the + * JCA or JSSE components utilized in creating the context is not + * known to the platform + * @throws NoSuchAlgorithmException if a JCA or JSSE algorithm, protocol, + * or type name specified for one of the context's components is not + * known to a given provider (or platform default provider for the + * component) + * @throws KeyManagementException if an error occurs in creating a + * {@link KeyManager} for the context + * @throws UnrecoverableKeyException if a private key needed by a + * {@link KeyManager} cannot be obtained from a key store + * @throws KeyStoreException if an error occurs in reading the + * contents of a key store + * @throws CertificateException if an error occurs in reading the + * contents of a certificate + */ + public SSLContext createContext(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException, + UnrecoverableKeyException, KeyStoreException, CertificateException { + + SSLContext sslContext = getProvider() != null ? SSLContext.getInstance(getProtocol(), getProvider()) : SSLContext.getInstance(getProtocol()); + + context.addInfo("SSL protocol '" + sslContext.getProtocol() + "' provider '" + sslContext.getProvider() + "'"); + + KeyManager[] keyManagers = createKeyManagers(context); + TrustManager[] trustManagers = createTrustManagers(context); + SecureRandom secureRandom = createSecureRandom(context); + sslContext.init(keyManagers, trustManagers, secureRandom); + return sslContext; + } + + /** + * Creates key managers using the receiver's key store configuration. + * @param context context for status messages + * @return an array of key managers or {@code null} if no key store + * configuration was provided + * @throws NoSuchProviderException if a provider specified for one + * of the key manager components is not known to the platform + * @throws NoSuchAlgorithmException if an algorithm specified for + * one of the key manager components is not known to the relevant + * provider + * @throws KeyStoreException if an error occurs in reading a key store + */ + private KeyManager[] createKeyManagers(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException, UnrecoverableKeyException, + KeyStoreException { + + if (getKeyStore() == null) + return null; + + KeyStore keyStore = getKeyStore().createKeyStore(); + context.addInfo("key store of type '" + keyStore.getType() + "' provider '" + keyStore.getProvider() + "': " + getKeyStore().getLocation()); + + KeyManagerFactory kmf = getKeyManagerFactory().createKeyManagerFactory(); + context.addInfo("key manager algorithm '" + kmf.getAlgorithm() + "' provider '" + kmf.getProvider() + "'"); + + char[] passphrase = getKeyStore().getPassword().toCharArray(); + kmf.init(keyStore, passphrase); + return kmf.getKeyManagers(); + } + + /** + * Creates trust managers using the receiver's trust store configuration. + * @param context context for status messages + * @return an array of trust managers or {@code null} if no trust store + * configuration was provided + * @throws NoSuchProviderException if a provider specified for one + * of the trust manager components is not known to the platform + * @throws NoSuchAlgorithmException if an algorithm specified for + * one of the trust manager components is not known to the relevant + * provider + * @throws KeyStoreException if an error occurs in reading a key + * store containing trust anchors + */ + private TrustManager[] createTrustManagers(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException, KeyStoreException { + + if (getTrustStore() == null) + return null; + + KeyStore trustStore = getTrustStore().createKeyStore(); + context.addInfo("trust store of type '" + trustStore.getType() + "' provider '" + trustStore.getProvider() + "': " + getTrustStore().getLocation()); + + TrustManagerFactory tmf = getTrustManagerFactory().createTrustManagerFactory(); + context.addInfo("trust manager algorithm '" + tmf.getAlgorithm() + "' provider '" + tmf.getProvider() + "'"); + + tmf.init(trustStore); + return tmf.getTrustManagers(); + } + + private SecureRandom createSecureRandom(ContextAware context) throws NoSuchProviderException, NoSuchAlgorithmException { + + SecureRandom secureRandom = getSecureRandom().createSecureRandom(); + context.addInfo("secure random algorithm '" + secureRandom.getAlgorithm() + "' provider '" + secureRandom.getProvider() + "'"); + + return secureRandom; + } + + /** + * Gets the key store configuration. + * @return key store factory bean or {@code null} if no key store + * configuration was provided + */ + public KeyStoreFactoryBean getKeyStore() { + if (keyStore == null) { + keyStore = keyStoreFromSystemProperties(JSSE_KEY_STORE_PROPERTY); + } + return keyStore; } - return keyStore; - } - - /** - * Sets the key store configuration. - * @param keyStore the key store factory bean to set - */ - public void setKeyStore(KeyStoreFactoryBean keyStore) { - this.keyStore = keyStore; - } - - /** - * Gets the trust store configuration. - * @return trust store factory bean or {@code null} if no trust store - * configuration was provided - */ - public KeyStoreFactoryBean getTrustStore() { - if (trustStore == null) { - trustStore = keyStoreFromSystemProperties(JSSE_TRUST_STORE_PROPERTY); + + /** + * Sets the key store configuration. + * @param keyStore the key store factory bean to set + */ + public void setKeyStore(KeyStoreFactoryBean keyStore) { + this.keyStore = keyStore; + } + + /** + * Gets the trust store configuration. + * @return trust store factory bean or {@code null} if no trust store + * configuration was provided + */ + public KeyStoreFactoryBean getTrustStore() { + if (trustStore == null) { + trustStore = keyStoreFromSystemProperties(JSSE_TRUST_STORE_PROPERTY); + } + return trustStore; + } + + /** + * Sets the trust store configuration. + * @param trustStore the trust store factory bean to set + */ + public void setTrustStore(KeyStoreFactoryBean trustStore) { + this.trustStore = trustStore; + } + + /** + * Constructs a key store factory bean using JSSE system properties. + * @param property base property name (e.g. {@code javax.net.ssl.keyStore}) + * @return key store or {@code null} if no value is defined for the + * base system property name + */ + private KeyStoreFactoryBean keyStoreFromSystemProperties(String property) { + if (System.getProperty(property) == null) + return null; + KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean(); + keyStore.setLocation(locationFromSystemProperty(property)); + keyStore.setProvider(System.getProperty(property + "Provider")); + keyStore.setPassword(System.getProperty(property + "Password")); + keyStore.setType(System.getProperty(property + "Type")); + return keyStore; + } + + /** + * Constructs a resource location from a JSSE system property. + * @param name property name (e.g. {@code javax.net.ssl.keyStore}) + * @return URL for the location specified in the property or {@code null} + * if no value is defined for the property + */ + private String locationFromSystemProperty(String name) { + String location = System.getProperty(name); + if (location != null && !location.startsWith("file:")) { + location = "file:" + location; + } + return location; + } + + /** + * Gets the secure random generator configuration. + * @return secure random factory bean; if no secure random generator + * configuration has been set, a default factory bean is returned + */ + public SecureRandomFactoryBean getSecureRandom() { + if (secureRandom == null) { + return new SecureRandomFactoryBean(); + } + return secureRandom; + } + + /** + * Sets the secure random generator configuration. + * @param secureRandom the secure random factory bean to set + */ + public void setSecureRandom(SecureRandomFactoryBean secureRandom) { + this.secureRandom = secureRandom; + } + + /** + * Gets the key manager factory configuration. + * @return factory bean; if no key manager factory + * configuration has been set, a default factory bean is returned + */ + public KeyManagerFactoryFactoryBean getKeyManagerFactory() { + if (keyManagerFactory == null) { + return new KeyManagerFactoryFactoryBean(); + } + return keyManagerFactory; + } + + /** + * Sets the key manager factory configuration. + * @param keyManagerFactory the key manager factory factory bean to set + */ + public void setKeyManagerFactory(KeyManagerFactoryFactoryBean keyManagerFactory) { + this.keyManagerFactory = keyManagerFactory; + } + + /** + * Gets the trust manager factory configuration. + * @return factory bean; if no trust manager factory + * configuration has been set, a default factory bean is returned + */ + public TrustManagerFactoryFactoryBean getTrustManagerFactory() { + if (trustManagerFactory == null) { + return new TrustManagerFactoryFactoryBean(); + } + return trustManagerFactory; } - return trustStore; - } - - /** - * Sets the trust store configuration. - * @param trustStore the trust store factory bean to set - */ - public void setTrustStore(KeyStoreFactoryBean trustStore) { - this.trustStore = trustStore; - } - - /** - * Constructs a key store factory bean using JSSE system properties. - * @param property base property name (e.g. {@code javax.net.ssl.keyStore}) - * @return key store or {@code null} if no value is defined for the - * base system property name - */ - private KeyStoreFactoryBean keyStoreFromSystemProperties(String property) { - if (System.getProperty(property) == null) return null; - KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean(); - keyStore.setLocation(locationFromSystemProperty(property)); - keyStore.setProvider(System.getProperty(property + "Provider")); - keyStore.setPassword(System.getProperty(property + "Password")); - keyStore.setType(System.getProperty(property + "Type")); - return keyStore; - } - - /** - * Constructs a resource location from a JSSE system property. - * @param name property name (e.g. {@code javax.net.ssl.keyStore}) - * @return URL for the location specified in the property or {@code null} - * if no value is defined for the property - */ - private String locationFromSystemProperty(String name) { - String location = System.getProperty(name); - if (location != null && !location.startsWith("file:")) { - location = "file:" + location; + + /** + * Sets the trust manager factory configuration. + * @param trustManagerFactory the factory bean to set + */ + public void setTrustManagerFactory(TrustManagerFactoryFactoryBean trustManagerFactory) { + this.trustManagerFactory = trustManagerFactory; } - return location; - } - - /** - * Gets the secure random generator configuration. - * @return secure random factory bean; if no secure random generator - * configuration has been set, a default factory bean is returned - */ - public SecureRandomFactoryBean getSecureRandom() { - if (secureRandom == null) { - return new SecureRandomFactoryBean(); + + /** + * Gets the secure transport protocol name. + * @return protocol name (e.g. {@code SSL}, {@code TLS}); the + * {@link SSL#DEFAULT_PROTOCOL} is returned if no protocol has been + * configured + */ + public String getProtocol() { + if (protocol == null) { + return SSL.DEFAULT_PROTOCOL; + } + return protocol; } - return secureRandom; - } - - /** - * Sets the secure random generator configuration. - * @param secureRandom the secure random factory bean to set - */ - public void setSecureRandom(SecureRandomFactoryBean secureRandom) { - this.secureRandom = secureRandom; - } - - /** - * Gets the key manager factory configuration. - * @return factory bean; if no key manager factory - * configuration has been set, a default factory bean is returned - */ - public KeyManagerFactoryFactoryBean getKeyManagerFactory() { - if (keyManagerFactory == null) { - return new KeyManagerFactoryFactoryBean(); + + /** + * Sets the secure transport protocol name. + * @param protocol a protocol name, which must be recognized by the provider + * specified by {@link #setProvider(String)} or by the platform's + * default provider if no platform was specified. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; } - return keyManagerFactory; - } - - /** - * Sets the key manager factory configuration. - * @param keyManagerFactory the key manager factory factory bean to set - */ - public void setKeyManagerFactory( - KeyManagerFactoryFactoryBean keyManagerFactory) { - this.keyManagerFactory = keyManagerFactory; - } - - /** - * Gets the trust manager factory configuration. - * @return factory bean; if no trust manager factory - * configuration has been set, a default factory bean is returned - */ - public TrustManagerFactoryFactoryBean getTrustManagerFactory() { - if (trustManagerFactory == null) { - return new TrustManagerFactoryFactoryBean(); + + /** + * Gets the JSSE provider name for the SSL context. + * @return JSSE provider name + */ + public String getProvider() { + return provider; } - return trustManagerFactory; - } - - /** - * Sets the trust manager factory configuration. - * @param trustManagerFactory the factory bean to set - */ - public void setTrustManagerFactory( - TrustManagerFactoryFactoryBean trustManagerFactory) { - this.trustManagerFactory = trustManagerFactory; - } - - /** - * Gets the secure transport protocol name. - * @return protocol name (e.g. {@code SSL}, {@code TLS}); the - * {@link SSL#DEFAULT_PROTOCOL} is returned if no protocol has been - * configured - */ - public String getProtocol() { - if (protocol == null) { - return SSL.DEFAULT_PROTOCOL; + + /** + * Sets the JSSE provider name for the SSL context. + * @param provider name of the JSSE provider to use in creating the + * SSL context + */ + public void setProvider(String provider) { + this.provider = provider; } - return protocol; - } - - /** - * Sets the secure transport protocol name. - * @param protocol a protocol name, which must be recognized by the provider - * specified by {@link #setProvider(String)} or by the platform's - * default provider if no platform was specified. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * Gets the JSSE provider name for the SSL context. - * @return JSSE provider name - */ - public String getProvider() { - return provider; - } - - /** - * Sets the JSSE provider name for the SSL context. - * @param provider name of the JSSE provider to use in creating the - * SSL context - */ - public void setProvider(String provider) { - this.provider = provider; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLNestedComponentRegistryRules.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLNestedComponentRegistryRules.java index cb577f55286a0e11b67ca4ed0cf107c46e772806..abd86101bf118a4d47d37104ee7ac179e4046f7c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLNestedComponentRegistryRules.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLNestedComponentRegistryRules.java @@ -23,21 +23,14 @@ import ch.qos.logback.core.joran.spi.DefaultNestedComponentRegistry; */ public class SSLNestedComponentRegistryRules { - static public void addDefaultNestedComponentRegistryRules( - DefaultNestedComponentRegistry registry) { - registry.add(SSLComponent.class, "ssl", SSLConfiguration.class); - registry.add(SSLConfiguration.class, "parameters", - SSLParametersConfiguration.class); - registry.add(SSLConfiguration.class, "keyStore", - KeyStoreFactoryBean.class); - registry.add(SSLConfiguration.class, "trustStore", - KeyStoreFactoryBean.class); - registry.add(SSLConfiguration.class, "keyManagerFactory", - KeyManagerFactoryFactoryBean.class); - registry.add(SSLConfiguration.class, "trustManagerFactory", - TrustManagerFactoryFactoryBean.class); - registry.add(SSLConfiguration.class, "secureRandom", - SecureRandomFactoryBean.class); - } + static public void addDefaultNestedComponentRegistryRules(DefaultNestedComponentRegistry registry) { + registry.add(SSLComponent.class, "ssl", SSLConfiguration.class); + registry.add(SSLConfiguration.class, "parameters", SSLParametersConfiguration.class); + registry.add(SSLConfiguration.class, "keyStore", KeyStoreFactoryBean.class); + registry.add(SSLConfiguration.class, "trustStore", KeyStoreFactoryBean.class); + registry.add(SSLConfiguration.class, "keyManagerFactory", KeyManagerFactoryFactoryBean.class); + registry.add(SSLConfiguration.class, "trustManagerFactory", TrustManagerFactoryFactoryBean.class); + registry.add(SSLConfiguration.class, "secureRandom", SecureRandomFactoryBean.class); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLParametersConfiguration.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLParametersConfiguration.java index 45671ca46cb782b06908837180a530888b44fb6c..1f874e9da591fb32b3a6749ecaaff36b1b78d67e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLParametersConfiguration.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SSLParametersConfiguration.java @@ -25,7 +25,6 @@ import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.OptionHelper; import ch.qos.logback.core.util.StringCollectionUtil; - /** * A configuration of SSL parameters for an {@link SSLEngine}. * @@ -33,224 +32,211 @@ import ch.qos.logback.core.util.StringCollectionUtil; */ public class SSLParametersConfiguration extends ContextAwareBase { - private String includedProtocols; - private String excludedProtocols; - private String includedCipherSuites; - private String excludedCipherSuites; - private Boolean needClientAuth; - private Boolean wantClientAuth; - private String[] enabledProtocols; - private String[] enabledCipherSuites; - - /** - * Configures SSL parameters on an {@link SSLConfigurable}. - * @param socket the subject configurable - */ - public void configure(SSLConfigurable socket) { - socket.setEnabledProtocols(enabledProtocols( - socket.getSupportedProtocols(), socket.getDefaultProtocols())); - socket.setEnabledCipherSuites(enabledCipherSuites( - socket.getSupportedCipherSuites(), socket.getDefaultCipherSuites())); - if (isNeedClientAuth() != null) { - socket.setNeedClientAuth(isNeedClientAuth()); + private String includedProtocols; + private String excludedProtocols; + private String includedCipherSuites; + private String excludedCipherSuites; + private Boolean needClientAuth; + private Boolean wantClientAuth; + private String[] enabledProtocols; + private String[] enabledCipherSuites; + + /** + * Configures SSL parameters on an {@link SSLConfigurable}. + * @param socket the subject configurable + */ + public void configure(SSLConfigurable socket) { + socket.setEnabledProtocols(enabledProtocols(socket.getSupportedProtocols(), socket.getDefaultProtocols())); + socket.setEnabledCipherSuites(enabledCipherSuites(socket.getSupportedCipherSuites(), socket.getDefaultCipherSuites())); + if (isNeedClientAuth() != null) { + socket.setNeedClientAuth(isNeedClientAuth()); + } + if (isWantClientAuth() != null) { + socket.setWantClientAuth(isWantClientAuth()); + } } - if (isWantClientAuth() != null) { - socket.setWantClientAuth(isWantClientAuth()); + + /** + * Gets the set of enabled protocols based on the configuration. + * @param supportedProtocols protocols supported by the SSL engine + * @param defaultProtocols default protocols enabled by the SSL engine + * @return enabled protocols + */ + private String[] enabledProtocols(String[] supportedProtocols, String[] defaultProtocols) { + if (enabledProtocols == null) { + // we're assuming that the same engine is used for all configurables + // so once we determine the enabled set, we won't do it again + if (OptionHelper.isEmpty(getIncludedProtocols()) && OptionHelper.isEmpty(getExcludedProtocols())) { + enabledProtocols = Arrays.copyOf(defaultProtocols, defaultProtocols.length); + } else { + enabledProtocols = includedStrings(supportedProtocols, getIncludedProtocols(), getExcludedProtocols()); + } + for (String protocol : enabledProtocols) { + addInfo("enabled protocol: " + protocol); + } + } + return enabledProtocols; } - } - - /** - * Gets the set of enabled protocols based on the configuration. - * @param supportedProtocols protocols supported by the SSL engine - * @param defaultProtocols default protocols enabled by the SSL engine - * @return enabled protocols - */ - private String[] enabledProtocols(String[] supportedProtocols, - String[] defaultProtocols) { - if (enabledProtocols == null) { - // we're assuming that the same engine is used for all configurables - // so once we determine the enabled set, we won't do it again - if (OptionHelper.isEmpty(getIncludedProtocols()) - && OptionHelper.isEmpty(getExcludedProtocols())) { - enabledProtocols = Arrays.copyOf(defaultProtocols, - defaultProtocols.length); - } - else { - enabledProtocols = includedStrings(supportedProtocols, - getIncludedProtocols(), getExcludedProtocols()); - } - for (String protocol : enabledProtocols) { - addInfo("enabled protocol: " + protocol); - } + + /** + * Gets the set of enabled cipher suites based on the configuration. + * @param supportedCipherSuites cipher suites supported by the SSL engine + * @param defaultCipherSuites default cipher suites enabled by the SSL engine + * @return enabled cipher suites + */ + private String[] enabledCipherSuites(String[] supportedCipherSuites, String[] defaultCipherSuites) { + if (enabledCipherSuites == null) { + // we're assuming that the same engine is used for all configurables + // so once we determine the enabled set, we won't do it again + if (OptionHelper.isEmpty(getIncludedCipherSuites()) && OptionHelper.isEmpty(getExcludedCipherSuites())) { + enabledCipherSuites = Arrays.copyOf(defaultCipherSuites, defaultCipherSuites.length); + } else { + enabledCipherSuites = includedStrings(supportedCipherSuites, getIncludedCipherSuites(), getExcludedCipherSuites()); + } + for (String cipherSuite : enabledCipherSuites) { + addInfo("enabled cipher suite: " + cipherSuite); + } + } + return enabledCipherSuites; } - return enabledProtocols; - } - - /** - * Gets the set of enabled cipher suites based on the configuration. - * @param supportedCipherSuites cipher suites supported by the SSL engine - * @param defaultCipherSuites default cipher suites enabled by the SSL engine - * @return enabled cipher suites - */ - private String[] enabledCipherSuites(String[] supportedCipherSuites, - String[] defaultCipherSuites) { - if (enabledCipherSuites == null) { - // we're assuming that the same engine is used for all configurables - // so once we determine the enabled set, we won't do it again - if (OptionHelper.isEmpty(getIncludedCipherSuites()) - && OptionHelper.isEmpty(getExcludedCipherSuites())) { - enabledCipherSuites = Arrays.copyOf(defaultCipherSuites, - defaultCipherSuites.length); - } - else { - enabledCipherSuites = includedStrings(supportedCipherSuites, - getIncludedCipherSuites(), getExcludedCipherSuites()); - } - for (String cipherSuite : enabledCipherSuites) { - addInfo("enabled cipher suite: " + cipherSuite); - } + + /** + * Applies include and exclude patterns to an array of default string values + * to produce an array of strings included by the patterns. + * @param defaults default list of string values + * @param included comma-separated patterns that identity values to include + * @param excluded comma-separated patterns that identity string to exclude + * @return an array of strings containing those strings from {@code defaults} + * that match at least one pattern in {@code included} that are not + * matched by any pattern in {@code excluded} + */ + private String[] includedStrings(String[] defaults, String included, String excluded) { + List values = new ArrayList(defaults.length); + values.addAll(Arrays.asList(defaults)); + if (included != null) { + StringCollectionUtil.retainMatching(values, stringToArray(included)); + } + if (excluded != null) { + StringCollectionUtil.removeMatching(values, stringToArray(excluded)); + } + return values.toArray(new String[values.size()]); } - return enabledCipherSuites; - } - - /** - * Applies include and exclude patterns to an array of default string values - * to produce an array of strings included by the patterns. - * @param defaults default list of string values - * @param included comma-separated patterns that identity values to include - * @param excluded comma-separated patterns that identity string to exclude - * @return an array of strings containing those strings from {@code defaults} - * that match at least one pattern in {@code included} that are not - * matched by any pattern in {@code excluded} - */ - private String[] includedStrings(String[] defaults, String included, - String excluded) { - List values = new ArrayList(defaults.length); - values.addAll(Arrays.asList(defaults)); - if (included != null) { - StringCollectionUtil.retainMatching(values, stringToArray(included)); + + /** + * Splits a string containing comma-separated values into an array. + * @param s the subject string + * @return array of values contained in {@code s} + */ + private String[] stringToArray(String s) { + return s.split("\\s*,\\s*"); } - if (excluded != null) { - StringCollectionUtil.removeMatching(values, stringToArray(excluded)); + + /** + * Gets the JSSE secure transport protocols to include. + * @return a string containing comma-separated JSSE secure transport + * protocol names (e.g. {@code TLSv1}) + */ + public String getIncludedProtocols() { + return includedProtocols; } - return values.toArray(new String[values.size()]); - } - - /** - * Splits a string containing comma-separated values into an array. - * @param s the subject string - * @return array of values contained in {@code s} - */ - private String[] stringToArray(String s) { - return s.split("\\s*,\\s*"); - } - - /** - * Gets the JSSE secure transport protocols to include. - * @return a string containing comma-separated JSSE secure transport - * protocol names (e.g. {@code TLSv1}) - */ - public String getIncludedProtocols() { - return includedProtocols; - } - /** - * Sets the JSSE secure transport protocols to include. - * @param protocols a string containing comma-separated JSSE secure - * transport protocol names - * @see Java Cryptography Architecture Standard Algorithm Name Documentation - */ - public void setIncludedProtocols(String protocols) { - this.includedProtocols = protocols; - } + /** + * Sets the JSSE secure transport protocols to include. + * @param protocols a string containing comma-separated JSSE secure + * transport protocol names + * @see Java Cryptography Architecture Standard Algorithm Name Documentation + */ + public void setIncludedProtocols(String protocols) { + this.includedProtocols = protocols; + } - /** - * Gets the JSSE secure transport protocols to exclude. - * @return a string containing comma-separated JSSE secure transport - * protocol names (e.g. {@code TLSv1}) - */ - public String getExcludedProtocols() { - return excludedProtocols; - } + /** + * Gets the JSSE secure transport protocols to exclude. + * @return a string containing comma-separated JSSE secure transport + * protocol names (e.g. {@code TLSv1}) + */ + public String getExcludedProtocols() { + return excludedProtocols; + } - /** - * Sets the JSSE secure transport protocols to exclude. - * @param protocols a string containing comma-separated JSSE secure - * transport protocol names - * @see Java Cryptography Architecture Standard Algorithm Name Documentation - */ - public void setExcludedProtocols(String protocols) { - this.excludedProtocols = protocols; - } + /** + * Sets the JSSE secure transport protocols to exclude. + * @param protocols a string containing comma-separated JSSE secure + * transport protocol names + * @see Java Cryptography Architecture Standard Algorithm Name Documentation + */ + public void setExcludedProtocols(String protocols) { + this.excludedProtocols = protocols; + } - /** - * Gets the JSSE cipher suite names to include. - * @return a string containing comma-separated JSSE cipher suite names - * (e.g. {@code TLS_DHE_RSA_WITH_AES_256_CBC_SHA}) - */ - public String getIncludedCipherSuites() { - return includedCipherSuites; - } + /** + * Gets the JSSE cipher suite names to include. + * @return a string containing comma-separated JSSE cipher suite names + * (e.g. {@code TLS_DHE_RSA_WITH_AES_256_CBC_SHA}) + */ + public String getIncludedCipherSuites() { + return includedCipherSuites; + } - /** - * Sets the JSSE cipher suite names to include. - * @param cipherSuites a string containing comma-separated JSSE cipher - * suite names - * @see Java Cryptography Architecture Standard Algorithm Name Documentation - */ - public void setIncludedCipherSuites(String cipherSuites) { - this.includedCipherSuites = cipherSuites; - } + /** + * Sets the JSSE cipher suite names to include. + * @param cipherSuites a string containing comma-separated JSSE cipher + * suite names + * @see Java Cryptography Architecture Standard Algorithm Name Documentation + */ + public void setIncludedCipherSuites(String cipherSuites) { + this.includedCipherSuites = cipherSuites; + } - /** - * Gets the JSSE cipher suite names to exclude. - * @return a string containing comma-separated JSSE cipher suite names - * (e.g. {@code TLS_DHE_RSA_WITH_AES_256_CBC_SHA}) - */ - public String getExcludedCipherSuites() { - return excludedCipherSuites; - } + /** + * Gets the JSSE cipher suite names to exclude. + * @return a string containing comma-separated JSSE cipher suite names + * (e.g. {@code TLS_DHE_RSA_WITH_AES_256_CBC_SHA}) + */ + public String getExcludedCipherSuites() { + return excludedCipherSuites; + } - /** - * Sets the JSSE cipher suite names to exclude. - * @param cipherSuites a string containing comma-separated JSSE cipher - * suite names - * @see Java Cryptography Architecture Standard Algorithm Name Documentation - */ - public void setExcludedCipherSuites(String cipherSuites) { - this.excludedCipherSuites = cipherSuites; - } + /** + * Sets the JSSE cipher suite names to exclude. + * @param cipherSuites a string containing comma-separated JSSE cipher + * suite names + * @see Java Cryptography Architecture Standard Algorithm Name Documentation + */ + public void setExcludedCipherSuites(String cipherSuites) { + this.excludedCipherSuites = cipherSuites; + } - /** - * Gets a flag indicating whether client authentication is required. - * @return flag state - */ - public Boolean isNeedClientAuth() { - return needClientAuth; - } + /** + * Gets a flag indicating whether client authentication is required. + * @return flag state + */ + public Boolean isNeedClientAuth() { + return needClientAuth; + } - /** - * Sets a flag indicating whether client authentication is required. - * @param needClientAuth the flag state to set - */ - public void setNeedClientAuth(Boolean needClientAuth) { - this.needClientAuth = needClientAuth; - } + /** + * Sets a flag indicating whether client authentication is required. + * @param needClientAuth the flag state to set + */ + public void setNeedClientAuth(Boolean needClientAuth) { + this.needClientAuth = needClientAuth; + } - /** - * Gets a flag indicating whether client authentication is desired. - * @return flag state - */ - public Boolean isWantClientAuth() { - return wantClientAuth; - } + /** + * Gets a flag indicating whether client authentication is desired. + * @return flag state + */ + public Boolean isWantClientAuth() { + return wantClientAuth; + } - /** - * Sets a flag indicating whether client authentication is desired. - * @param wantClientAuth the flag state to set - */ - public void setWantClientAuth(Boolean wantClientAuth) { - this.wantClientAuth = wantClientAuth; - } + /** + * Sets a flag indicating whether client authentication is desired. + * @param wantClientAuth the flag state to set + */ + public void setWantClientAuth(Boolean wantClientAuth) { + this.wantClientAuth = wantClientAuth; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBean.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBean.java index d2198708f38147772387829fd361b5a5daabf941..65a26d11e672bdbf33f0669398002a77b8c4d6cf 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBean.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBean.java @@ -27,75 +27,68 @@ import java.security.SecureRandom; */ public class SecureRandomFactoryBean { - private String algorithm; - private String provider; + private String algorithm; + private String provider; - /** - * Creates a new {@link SecureRandom} generator using the receiver's - * configuration. - * @return secure random generator instance - * @throws NoSuchProviderException if the provider name specified by - * {@link #setProvider(String)} is not known to the platform - * @throws NoSuchAlgorithmException if the algorithm name specified by - * {@link #setAlgorithm(String)} is not recognized by the specified - * provider (or the platform's default provider if the provider isn't - * specified) - */ - public SecureRandom createSecureRandom() throws NoSuchProviderException, - NoSuchAlgorithmException { - try { - return getProvider() != null ? - SecureRandom.getInstance(getAlgorithm(), getProvider()) - : SecureRandom.getInstance(getAlgorithm()); + /** + * Creates a new {@link SecureRandom} generator using the receiver's + * configuration. + * @return secure random generator instance + * @throws NoSuchProviderException if the provider name specified by + * {@link #setProvider(String)} is not known to the platform + * @throws NoSuchAlgorithmException if the algorithm name specified by + * {@link #setAlgorithm(String)} is not recognized by the specified + * provider (or the platform's default provider if the provider isn't + * specified) + */ + public SecureRandom createSecureRandom() throws NoSuchProviderException, NoSuchAlgorithmException { + try { + return getProvider() != null ? SecureRandom.getInstance(getAlgorithm(), getProvider()) : SecureRandom.getInstance(getAlgorithm()); + } catch (NoSuchProviderException ex) { + throw new NoSuchProviderException("no such secure random provider: " + getProvider()); + } catch (NoSuchAlgorithmException ex) { + throw new NoSuchAlgorithmException("no such secure random algorithm: " + getAlgorithm()); + } } - catch (NoSuchProviderException ex) { - throw new NoSuchProviderException("no such secure random provider: " - + getProvider()); - } - catch (NoSuchAlgorithmException ex) { - throw new NoSuchAlgorithmException("no such secure random algorithm: " - + getAlgorithm()); - } - } - - /** - * Gets the secure random generator algorithm name. - * @return an algorithm name (e.g. {@code SHA1PRNG}); the - * {@link SSL#DEFAULT_SECURE_RANDOM_ALGORITHM} is returned if no algorithm has been - * specified - */ - public String getAlgorithm() { - if (algorithm == null) { - return SSL.DEFAULT_SECURE_RANDOM_ALGORITHM; + + /** + * Gets the secure random generator algorithm name. + * @return an algorithm name (e.g. {@code SHA1PRNG}); the + * {@link SSL#DEFAULT_SECURE_RANDOM_ALGORITHM} is returned if no algorithm has been + * specified + */ + public String getAlgorithm() { + if (algorithm == null) { + return SSL.DEFAULT_SECURE_RANDOM_ALGORITHM; + } + return algorithm; } - return algorithm; - } - /** - * Sets the secure random generator algorithm name. - * @param algorithm an algorithm name, which must be recognized by the - * provider specified via {@link #setProvider(String)} or by the - * platform's default provider if no provider is specified. - */ - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } + /** + * Sets the secure random generator algorithm name. + * @param algorithm an algorithm name, which must be recognized by the + * provider specified via {@link #setProvider(String)} or by the + * platform's default provider if no provider is specified. + */ + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } - /** - * Gets the JCA provider name for the secure random generator. - * @return provider name - */ - public String getProvider() { - return provider; - } + /** + * Gets the JCA provider name for the secure random generator. + * @return provider name + */ + public String getProvider() { + return provider; + } - /** - * Sets the JCA provider name for the secure random generator. - * @param provider name of the JCA provider to utilize in creating the - * secure random generator - */ - public void setProvider(String provider) { - this.provider = provider; - } + /** + * Sets the JCA provider name for the secure random generator. + * @param provider name of the JCA provider to utilize in creating the + * secure random generator + */ + public void setProvider(String provider) { + this.provider = provider; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBean.java b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBean.java index b3456033654f5d505324c3ff1da97196f32c82ab..3e9f143fdf7fe13f9d544b2c98cfce5d4530da13 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBean.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBean.java @@ -28,64 +28,61 @@ import javax.net.ssl.TrustManagerFactory; */ public class TrustManagerFactoryFactoryBean { - private String algorithm; - private String provider; + private String algorithm; + private String provider; - /** - * Creates a {@link TrustManagerFactory} using the receiver's configuration. - * @return factory object - * @throws NoSuchProviderException if the provider specified by - * {@link #setProvider(String)} is not known to the platform - * @throws NoSuchAlgorithmException if the algorithm specified by - * {@link #setAlgorithm(String)} is not known to the specified provider - * (or to the default platform provider if no provider is specified) - */ - public TrustManagerFactory createTrustManagerFactory() - throws NoSuchProviderException, NoSuchAlgorithmException { - - return getProvider() != null ? - TrustManagerFactory.getInstance(getAlgorithm(), getProvider()) - : TrustManagerFactory.getInstance(getAlgorithm()); - } - - /** - * Gets the algorithm name for the trust manager factory. - * @return algorithm name (e.g. {@code PKIX}); the default algorithm - * (obtained from {@link TrustManagerFactory#getDefaultAlgorithm()}) - * is returned if no algorithm has been configured - */ - public String getAlgorithm() { - if (algorithm == null) { - return TrustManagerFactory.getDefaultAlgorithm(); + /** + * Creates a {@link TrustManagerFactory} using the receiver's configuration. + * @return factory object + * @throws NoSuchProviderException if the provider specified by + * {@link #setProvider(String)} is not known to the platform + * @throws NoSuchAlgorithmException if the algorithm specified by + * {@link #setAlgorithm(String)} is not known to the specified provider + * (or to the default platform provider if no provider is specified) + */ + public TrustManagerFactory createTrustManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException { + + return getProvider() != null ? TrustManagerFactory.getInstance(getAlgorithm(), getProvider()) : TrustManagerFactory.getInstance(getAlgorithm()); + } + + /** + * Gets the algorithm name for the trust manager factory. + * @return algorithm name (e.g. {@code PKIX}); the default algorithm + * (obtained from {@link TrustManagerFactory#getDefaultAlgorithm()}) + * is returned if no algorithm has been configured + */ + public String getAlgorithm() { + if (algorithm == null) { + return TrustManagerFactory.getDefaultAlgorithm(); + } + return algorithm; } - return algorithm; - } - /** - * Sets the algorithm name for the trust manager factory. - * @param algorithm an algorithm name, which must be recognized by the - * provider specified by {@link #setProvider(String)} or by the - * platform's default provider if no provider is specified. - */ - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } + /** + * Sets the algorithm name for the trust manager factory. + * @param algorithm an algorithm name, which must be recognized by the + * provider specified by {@link #setProvider(String)} or by the + * platform's default provider if no provider is specified. + */ + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } - /** - * Gets the JSSE provider name for the trust manager factory. - * @return provider name - */ - public String getProvider() { - return provider; - } + /** + * Gets the JSSE provider name for the trust manager factory. + * @return provider name + */ + public String getProvider() { + return provider; + } - /** - * Sets the JSSE provider name for the trust manager factory. - * @param provider name of the JSSE provider to utilize in creating the - * trust manager factory - */ - public void setProvider(String provider) { - this.provider = provider; - } + /** + * Sets the JSSE provider name for the trust manager factory. + * @param provider name of the JSSE provider to utilize in creating the + * trust manager factory + */ + public void setProvider(String provider) { + this.provider = provider; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/CompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/CompositeConverter.java index ca16afad34d39a6be0460bd7ec7fd9732d66b6b5..61faf52b5ab2bcb39906dee7cc2ed7811ce2b105 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/CompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/CompositeConverter.java @@ -15,39 +15,39 @@ package ch.qos.logback.core.pattern; abstract public class CompositeConverter extends DynamicConverter { - Converter childConverter; + Converter childConverter; - public String convert(E event) { - StringBuilder buf = new StringBuilder(); + public String convert(E event) { + StringBuilder buf = new StringBuilder(); - for (Converter c = childConverter; c != null; c = c.next) { - c.write(buf, event); + for (Converter c = childConverter; c != null; c = c.next) { + c.write(buf, event); + } + String intermediary = buf.toString(); + return transform(event, intermediary); } - String intermediary = buf.toString(); - return transform(event, intermediary); - } - abstract protected String transform(E event, String in); + abstract protected String transform(E event, String in); - public Converter getChildConverter() { - return childConverter; - } + public Converter getChildConverter() { + return childConverter; + } - public void setChildConverter(Converter child) { - childConverter = child; - } + public void setChildConverter(Converter child) { + childConverter = child; + } - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("CompositeConverter<"); + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append("CompositeConverter<"); - if (formattingInfo != null) - buf.append(formattingInfo); + if (formattingInfo != null) + buf.append(formattingInfo); - if (childConverter != null) { - buf.append(", children: ").append(childConverter); + if (childConverter != null) { + buf.append(", children: ").append(childConverter); + } + buf.append(">"); + return buf.toString(); } - buf.append(">"); - return buf.toString(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/Converter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/Converter.java index 0e538930dd2197fc65ccd5e9aa5236d1d7330421..b8cace7f9de8774d856d9cd7b4b198bb0f87b92e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/Converter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/Converter.java @@ -20,36 +20,36 @@ package ch.qos.logback.core.pattern; * @author ceki */ abstract public class Converter { - - Converter next; - /** - * The convert method is responsible for extracting data from the event and - * storing it for later use by the write method. - * - * @param event - */ - public abstract String convert(E event); + Converter next; - /** - * In its simplest incarnation, a convert simply appends the data extracted from - * the event to the buffer passed as parameter. - * - * @param buf The input buffer where data is appended - * @param event The event from where data is extracted - */ - public void write(StringBuilder buf, E event) { - buf.append(convert(event)); - } - - public final void setNext(Converter next) { - if (this.next != null) { - throw new IllegalStateException("Next converter has been already set"); + /** + * The convert method is responsible for extracting data from the event and + * storing it for later use by the write method. + * + * @param event + */ + public abstract String convert(E event); + + /** + * In its simplest incarnation, a convert simply appends the data extracted from + * the event to the buffer passed as parameter. + * + * @param buf The input buffer where data is appended + * @param event The event from where data is extracted + */ + public void write(StringBuilder buf, E event) { + buf.append(convert(event)); + } + + public final void setNext(Converter next) { + if (this.next != null) { + throw new IllegalStateException("Next converter has been already set"); + } + this.next = next; } - this.next = next; - } - public final Converter getNext() { - return next; - } + public final Converter getNext() { + return next; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/ConverterUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/ConverterUtil.java index c3cf3c11bfd5107d061a603cea810d3e13104ca4..e0c4b982d41604674c5eff07cbff48b5b8d35cfd 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/ConverterUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/ConverterUtil.java @@ -18,49 +18,48 @@ import ch.qos.logback.core.spi.ContextAware; public class ConverterUtil { - /** - * Start converters in the chain of converters. - * - * @param head - */ - public static void startConverters(Converter head) { - Converter c = head; - while (c != null) { - // CompositeConverter is a subclass of DynamicConverter - if (c instanceof CompositeConverter) { - CompositeConverter cc = (CompositeConverter) c; - Converter childConverter = cc.childConverter; - startConverters(childConverter); - cc.start(); - } else if (c instanceof DynamicConverter) { - DynamicConverter dc = (DynamicConverter) c; - dc.start(); - } - c = c.getNext(); + /** + * Start converters in the chain of converters. + * + * @param head + */ + public static void startConverters(Converter head) { + Converter c = head; + while (c != null) { + // CompositeConverter is a subclass of DynamicConverter + if (c instanceof CompositeConverter) { + CompositeConverter cc = (CompositeConverter) c; + Converter childConverter = cc.childConverter; + startConverters(childConverter); + cc.start(); + } else if (c instanceof DynamicConverter) { + DynamicConverter dc = (DynamicConverter) c; + dc.start(); + } + c = c.getNext(); + } } - } - - public static Converter findTail(Converter head) { - Converter p = head; - while (p != null) { - Converter next = p.getNext(); - if (next == null) { - break; - } else { - p = next; - } + public static Converter findTail(Converter head) { + Converter p = head; + while (p != null) { + Converter next = p.getNext(); + if (next == null) { + break; + } else { + p = next; + } + } + return p; } - return p; - } - public static void setContextForConverters(Context context, Converter head) { - Converter c = head; - while (c != null) { - if (c instanceof ContextAware) { - ((ContextAware) c).setContext(context); - } - c = c.getNext(); + public static void setContextForConverters(Context context, Converter head) { + Converter c = head; + while (c != null) { + if (c instanceof ContextAware) { + ((ContextAware) c).setContext(context); + } + c = c.getNext(); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/DynamicConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/DynamicConverter.java index 5d729cac30e03cfc50460e898815859a5adcb9c3..80f65c638816b9a8cd111a6b5a034e68282f9f5e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/DynamicConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/DynamicConverter.java @@ -21,92 +21,91 @@ import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.LifeCycle; import ch.qos.logback.core.status.Status; -abstract public class DynamicConverter extends FormattingConverter - implements LifeCycle, ContextAware { - - ContextAwareBase cab = new ContextAwareBase(this); - - // Contains a list of option Strings. - private List optionList; - - /** - * Is this component active? - */ - protected boolean started = false; - - /** - * Components that depend on options passed during configuration can override - * this method in order to make appropriate use of those options. For simpler - * components, the trivial implementation found in this abstract class will be - * sufficient. - */ - public void start() { - started = true; - } - - public void stop() { - started = false; - } - - public boolean isStarted() { - return started; - } - - public void setOptionList(List optionList) { - this.optionList = optionList; - } - - /** - * Return the first option passed to this component. The returned value may be - * null if there are no options. - * - * @return First option, may be null. - */ - public String getFirstOption() { - if (optionList == null || optionList.size() == 0) { - return null; - } else { - return optionList.get(0); +abstract public class DynamicConverter extends FormattingConverter implements LifeCycle, ContextAware { + + ContextAwareBase cab = new ContextAwareBase(this); + + // Contains a list of option Strings. + private List optionList; + + /** + * Is this component active? + */ + protected boolean started = false; + + /** + * Components that depend on options passed during configuration can override + * this method in order to make appropriate use of those options. For simpler + * components, the trivial implementation found in this abstract class will be + * sufficient. + */ + public void start() { + started = true; } - } - protected List getOptionList() { - return optionList; - } + public void stop() { + started = false; + } + + public boolean isStarted() { + return started; + } + + public void setOptionList(List optionList) { + this.optionList = optionList; + } + + /** + * Return the first option passed to this component. The returned value may be + * null if there are no options. + * + * @return First option, may be null. + */ + public String getFirstOption() { + if (optionList == null || optionList.size() == 0) { + return null; + } else { + return optionList.get(0); + } + } + + protected List getOptionList() { + return optionList; + } - public void setContext(Context context) { - cab.setContext(context); - } + public void setContext(Context context) { + cab.setContext(context); + } - public Context getContext() { - return cab.getContext(); - } + public Context getContext() { + return cab.getContext(); + } - public void addStatus(Status status) { - cab.addStatus(status); - } + public void addStatus(Status status) { + cab.addStatus(status); + } - public void addInfo(String msg) { - cab.addInfo(msg); - } + public void addInfo(String msg) { + cab.addInfo(msg); + } - public void addInfo(String msg, Throwable ex) { - cab.addInfo(msg, ex); - } + public void addInfo(String msg, Throwable ex) { + cab.addInfo(msg, ex); + } - public void addWarn(String msg) { - cab.addWarn(msg); - } + public void addWarn(String msg) { + cab.addWarn(msg); + } - public void addWarn(String msg, Throwable ex) { - cab.addWarn(msg, ex); - } + public void addWarn(String msg, Throwable ex) { + cab.addWarn(msg, ex); + } - public void addError(String msg) { - cab.addError(msg); - } + public void addError(String msg) { + cab.addError(msg); + } - public void addError(String msg, Throwable ex) { - cab.addError(msg, ex); - } + public void addError(String msg, Throwable ex) { + cab.addError(msg, ex); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/FormatInfo.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/FormatInfo.java index 1fd220bcaec1177b9851932bd6c5c697b8c7ee7e..91b015bd0f8d76f2a35ed44d8a6abceea8f89ea1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/FormatInfo.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/FormatInfo.java @@ -20,136 +20,133 @@ package ch.qos.logback.core.pattern; * @author Ceki Gülcü */ public class FormatInfo { - private int min = Integer.MIN_VALUE; - private int max = Integer.MAX_VALUE; - private boolean leftPad = true; - private boolean leftTruncate = true; - - public FormatInfo() { - } - - public FormatInfo(int min, int max) { - this.min = min; - this.max = max; - } - - public FormatInfo(int min, int max, boolean leftPad, boolean leftTruncate) { - this.min = min; - this.max = max; - this.leftPad = leftPad; - this.leftTruncate = leftTruncate; - } - - /** - * This method is used to parse a string such as "5", ".7", "5.7" or "-5.7" into - * a FormatInfo. - * - * @param str A String to convert into a FormatInfo object - * @return A newly created and appropriately initialized FormatInfo object. - * @throws IllegalArgumentException - */ - public static FormatInfo valueOf(String str) throws IllegalArgumentException { - if (str == null) { - throw new NullPointerException("Argument cannot be null"); + private int min = Integer.MIN_VALUE; + private int max = Integer.MAX_VALUE; + private boolean leftPad = true; + private boolean leftTruncate = true; + + public FormatInfo() { } - FormatInfo fi = new FormatInfo(); - - int indexOfDot = str.indexOf('.'); - String minPart = null; - String maxPart = null; - if (indexOfDot != -1) { - minPart = str.substring(0, indexOfDot); - if (indexOfDot + 1 == str.length()) { - throw new IllegalArgumentException("Formatting string [" + str - + "] should not end with '.'"); - } else { - maxPart = str.substring(indexOfDot + 1); - } - } else { - minPart = str; + public FormatInfo(int min, int max) { + this.min = min; + this.max = max; } - if (minPart != null && minPart.length() > 0) { - int min = Integer.parseInt(minPart); - if (min >= 0) { - fi.min = min; - } else { - fi.min = -min; - fi.leftPad = false; - } + public FormatInfo(int min, int max, boolean leftPad, boolean leftTruncate) { + this.min = min; + this.max = max; + this.leftPad = leftPad; + this.leftTruncate = leftTruncate; } - if (maxPart != null && maxPart.length() > 0) { - int max = Integer.parseInt(maxPart); - if (max >= 0) { - fi.max = max; - } else { - fi.max = -max; - fi.leftTruncate = false; - } + /** + * This method is used to parse a string such as "5", ".7", "5.7" or "-5.7" into + * a FormatInfo. + * + * @param str A String to convert into a FormatInfo object + * @return A newly created and appropriately initialized FormatInfo object. + * @throws IllegalArgumentException + */ + public static FormatInfo valueOf(String str) throws IllegalArgumentException { + if (str == null) { + throw new NullPointerException("Argument cannot be null"); + } + + FormatInfo fi = new FormatInfo(); + + int indexOfDot = str.indexOf('.'); + String minPart = null; + String maxPart = null; + if (indexOfDot != -1) { + minPart = str.substring(0, indexOfDot); + if (indexOfDot + 1 == str.length()) { + throw new IllegalArgumentException("Formatting string [" + str + "] should not end with '.'"); + } else { + maxPart = str.substring(indexOfDot + 1); + } + } else { + minPart = str; + } + + if (minPart != null && minPart.length() > 0) { + int min = Integer.parseInt(minPart); + if (min >= 0) { + fi.min = min; + } else { + fi.min = -min; + fi.leftPad = false; + } + } + + if (maxPart != null && maxPart.length() > 0) { + int max = Integer.parseInt(maxPart); + if (max >= 0) { + fi.max = max; + } else { + fi.max = -max; + fi.leftTruncate = false; + } + } + + return fi; + } - return fi; + public boolean isLeftPad() { + return leftPad; + } - } + public void setLeftPad(boolean leftAlign) { + this.leftPad = leftAlign; + } - public boolean isLeftPad() { - return leftPad; - } + public int getMax() { + return max; + } - public void setLeftPad(boolean leftAlign) { - this.leftPad = leftAlign; - } + public void setMax(int max) { + this.max = max; + } - public int getMax() { - return max; - } + public int getMin() { + return min; + } - public void setMax(int max) { - this.max = max; - } + public void setMin(int min) { + this.min = min; + } - public int getMin() { - return min; - } + public boolean isLeftTruncate() { + return leftTruncate; + } - public void setMin(int min) { - this.min = min; - } + public void setLeftTruncate(boolean leftTruncate) { + this.leftTruncate = leftTruncate; + } - public boolean isLeftTruncate() { - return leftTruncate; - } + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FormatInfo)) { + return false; + } + FormatInfo r = (FormatInfo) o; - public void setLeftTruncate(boolean leftTruncate) { - this.leftTruncate = leftTruncate; - } + return (min == r.min) && (max == r.max) && (leftPad == r.leftPad) && (leftTruncate == r.leftTruncate); + } - public boolean equals(Object o) { - if (this == o) { - return true; + @Override + public int hashCode() { + int result = min; + result = 31 * result + max; + result = 31 * result + (leftPad ? 1 : 0); + result = 31 * result + (leftTruncate ? 1 : 0); + return result; } - if (!(o instanceof FormatInfo)) { - return false; + + public String toString() { + return "FormatInfo(" + min + ", " + max + ", " + leftPad + ", " + leftTruncate + ")"; } - FormatInfo r = (FormatInfo) o; - - return (min == r.min) && (max == r.max) && (leftPad == r.leftPad) - && (leftTruncate == r.leftTruncate); - } - - @Override - public int hashCode() { - int result = min; - result = 31 * result + max; - result = 31 * result + (leftPad ? 1 : 0); - result = 31 * result + (leftTruncate ? 1 : 0); - return result; - } - - public String toString() { - return "FormatInfo(" + min + ", " + max + ", " + leftPad + ", " - + leftTruncate + ")"; - } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/FormattingConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/FormattingConverter.java index a40b5dcb6bbad1f4c63abd9961132ed7d6090044..668cc8938b0a0cc3ec507881130643f421f325b4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/FormattingConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/FormattingConverter.java @@ -15,58 +15,56 @@ package ch.qos.logback.core.pattern; abstract public class FormattingConverter extends Converter { - static final int INITIAL_BUF_SIZE = 256; - static final int MAX_CAPACITY = 1024; + static final int INITIAL_BUF_SIZE = 256; + static final int MAX_CAPACITY = 1024; - - FormatInfo formattingInfo; + FormatInfo formattingInfo; - final public FormatInfo getFormattingInfo() { - return formattingInfo; - } - - final public void setFormattingInfo(FormatInfo formattingInfo) { - if (this.formattingInfo != null) { - throw new IllegalStateException("FormattingInfo has been already set"); + final public FormatInfo getFormattingInfo() { + return formattingInfo; } - this.formattingInfo = formattingInfo; - } - @Override - final public void write(StringBuilder buf, E event) { - String s = convert(event); - - if(formattingInfo == null) { - buf.append(s); - return; + final public void setFormattingInfo(FormatInfo formattingInfo) { + if (this.formattingInfo != null) { + throw new IllegalStateException("FormattingInfo has been already set"); + } + this.formattingInfo = formattingInfo; } - - int min = formattingInfo.getMin(); - int max = formattingInfo.getMax(); + @Override + final public void write(StringBuilder buf, E event) { + String s = convert(event); - if (s == null) { - if (0 < min) - SpacePadder.spacePad(buf, min); - return; - } + if (formattingInfo == null) { + buf.append(s); + return; + } + + int min = formattingInfo.getMin(); + int max = formattingInfo.getMax(); + + if (s == null) { + if (0 < min) + SpacePadder.spacePad(buf, min); + return; + } - int len = s.length(); + int len = s.length(); - if (len > max) { - if(formattingInfo.isLeftTruncate()) { - buf.append(s.substring(len - max)); - } else { - buf.append(s.substring(0, max)); - } - } else if (len < min) { - if (formattingInfo.isLeftPad()) { - SpacePadder.leftPad(buf, s, min); - } else { - SpacePadder.rightPad(buf, s, min); - } - } else { - buf.append(s); + if (len > max) { + if (formattingInfo.isLeftTruncate()) { + buf.append(s.substring(len - max)); + } else { + buf.append(s.substring(0, max)); + } + } else if (len < min) { + if (formattingInfo.isLeftPad()) { + SpacePadder.leftPad(buf, s, min); + } else { + SpacePadder.rightPad(buf, s, min); + } + } else { + buf.append(s); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/IdentityCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/IdentityCompositeConverter.java index 71b3bf55b0f8e08504a9f9aae3f7664e75f4388a..e9d67aa54d143bfa7db88059bafe8547b3fa32d7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/IdentityCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/IdentityCompositeConverter.java @@ -15,8 +15,8 @@ package ch.qos.logback.core.pattern; public class IdentityCompositeConverter extends CompositeConverter { - @Override - protected String transform(E event, String in) { - return in; - } + @Override + protected String transform(E event, String in) { + return in; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/LiteralConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/LiteralConverter.java index cb449112de772c31df867b4abc464138634dc5e6..4369fe5a584c1cdf986f6a707e7b2f0749745530 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/LiteralConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/LiteralConverter.java @@ -15,15 +15,14 @@ package ch.qos.logback.core.pattern; public final class LiteralConverter extends Converter { - String literal; + String literal; - public LiteralConverter(String literal) { - this.literal = literal; - } + public LiteralConverter(String literal) { + this.literal = literal; + } + + public String convert(E o) { + return literal; + } - public String convert(E o) { - return literal; - } - - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutBase.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutBase.java index 63499dee400783c5e314f7aed341281eeaddfe5a..5002241324077a807ef78e381ae583b3a8987f74 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutBase.java @@ -25,137 +25,131 @@ import ch.qos.logback.core.status.StatusManager; import java.util.HashMap; import java.util.Map; - abstract public class PatternLayoutBase extends LayoutBase { - Converter head; - String pattern; - protected PostCompileProcessor postCompileProcessor; - - - Map instanceConverterMap = new HashMap(); - protected boolean outputPatternAsHeader = false; - - /** - * Concrete implementations of this class are responsible for elaborating the - * mapping between pattern words and converters. - * - * @return A map associating pattern words to the names of converter classes - */ - abstract public Map getDefaultConverterMap(); - - /** - * Returns a map where the default converter map is merged with the map - * contained in the context. - */ - public Map getEffectiveConverterMap() { - Map effectiveMap = new HashMap(); - - // add the least specific map fist - Map defaultMap = getDefaultConverterMap(); - if (defaultMap != null) { - effectiveMap.putAll(defaultMap); + Converter head; + String pattern; + protected PostCompileProcessor postCompileProcessor; + + Map instanceConverterMap = new HashMap(); + protected boolean outputPatternAsHeader = false; + + /** + * Concrete implementations of this class are responsible for elaborating the + * mapping between pattern words and converters. + * + * @return A map associating pattern words to the names of converter classes + */ + abstract public Map getDefaultConverterMap(); + + /** + * Returns a map where the default converter map is merged with the map + * contained in the context. + */ + public Map getEffectiveConverterMap() { + Map effectiveMap = new HashMap(); + + // add the least specific map fist + Map defaultMap = getDefaultConverterMap(); + if (defaultMap != null) { + effectiveMap.putAll(defaultMap); + } + + // contextMap is more specific than the default map + Context context = getContext(); + if (context != null) { + @SuppressWarnings("unchecked") + Map contextMap = (Map) context.getObject(CoreConstants.PATTERN_RULE_REGISTRY); + if (contextMap != null) { + effectiveMap.putAll(contextMap); + } + } + // set the most specific map last + effectiveMap.putAll(instanceConverterMap); + return effectiveMap; + } + + public void start() { + if (pattern == null || pattern.length() == 0) { + addError("Empty or null pattern."); + return; + } + try { + Parser p = new Parser(pattern); + if (getContext() != null) { + p.setContext(getContext()); + } + Node t = p.parse(); + this.head = p.compile(t, getEffectiveConverterMap()); + if (postCompileProcessor != null) { + postCompileProcessor.process(context, head); + } + ConverterUtil.setContextForConverters(getContext(), head); + ConverterUtil.startConverters(this.head); + super.start(); + } catch (ScanException sce) { + StatusManager sm = getContext().getStatusManager(); + sm.add(new ErrorStatus("Failed to parse pattern \"" + getPattern() + "\".", this, sce)); + } + } + + public void setPostCompileProcessor(PostCompileProcessor postCompileProcessor) { + this.postCompileProcessor = postCompileProcessor; + } + + /** + * + * @param head + * @deprecated Use {@link ConverterUtil#setContextForConverters} instead. This method will + * be removed in future releases. + */ + protected void setContextForConverters(Converter head) { + ConverterUtil.setContextForConverters(getContext(), head); + } + + protected String writeLoopOnConverters(E event) { + StringBuilder buf = new StringBuilder(128); + Converter c = head; + while (c != null) { + c.write(buf, event); + c = c.getNext(); + } + return buf.toString(); + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public String toString() { + return this.getClass().getName() + "(\"" + getPattern() + "\")"; } - // contextMap is more specific than the default map - Context context = getContext(); - if (context != null) { - @SuppressWarnings("unchecked") - Map contextMap = (Map) context - .getObject(CoreConstants.PATTERN_RULE_REGISTRY); - if (contextMap != null) { - effectiveMap.putAll(contextMap); - } + public Map getInstanceConverterMap() { + return instanceConverterMap; } - // set the most specific map last - effectiveMap.putAll(instanceConverterMap); - return effectiveMap; - } - - public void start() { - if(pattern == null || pattern.length() == 0) { - addError("Empty or null pattern."); - return; + + protected String getPresentationHeaderPrefix() { + return CoreConstants.EMPTY_STRING; } - try { - Parser p = new Parser(pattern); - if (getContext() != null) { - p.setContext(getContext()); - } - Node t = p.parse(); - this.head = p.compile(t, getEffectiveConverterMap()); - if (postCompileProcessor != null) { - postCompileProcessor.process(context, head); - } - ConverterUtil.setContextForConverters(getContext(), head); - ConverterUtil.startConverters(this.head); - super.start(); - } catch (ScanException sce) { - StatusManager sm = getContext().getStatusManager(); - sm.add(new ErrorStatus("Failed to parse pattern \"" + getPattern() - + "\".", this, sce)); + + public boolean isOutputPatternAsHeader() { + return outputPatternAsHeader; } - } - - public void setPostCompileProcessor( - PostCompileProcessor postCompileProcessor) { - this.postCompileProcessor = postCompileProcessor; - } - - /** - * - * @param head - * @deprecated Use {@link ConverterUtil#setContextForConverters} instead. This method will - * be removed in future releases. - */ - protected void setContextForConverters(Converter head) { - ConverterUtil.setContextForConverters(getContext(), head); - } - - protected String writeLoopOnConverters(E event) { - StringBuilder buf = new StringBuilder(128); - Converter c = head; - while (c != null) { - c.write(buf, event); - c = c.getNext(); + + public void setOutputPatternAsHeader(boolean outputPatternAsHeader) { + this.outputPatternAsHeader = outputPatternAsHeader; + } + + @Override + public String getPresentationHeader() { + if (outputPatternAsHeader) + return getPresentationHeaderPrefix() + pattern; + else + return super.getPresentationHeader(); } - return buf.toString(); - } - - public String getPattern() { - return pattern; - } - - public void setPattern(String pattern) { - this.pattern = pattern; - } - - public String toString() { - return this.getClass().getName() + "(\"" + getPattern() + "\")"; - } - - public Map getInstanceConverterMap() { - return instanceConverterMap; - } - - - protected String getPresentationHeaderPrefix() { - return CoreConstants.EMPTY_STRING; - } - - public boolean isOutputPatternAsHeader() { - return outputPatternAsHeader; - } - - public void setOutputPatternAsHeader(boolean outputPatternAsHeader) { - this.outputPatternAsHeader = outputPatternAsHeader; - } - - @Override - public String getPresentationHeader() { - if(outputPatternAsHeader) - return getPresentationHeaderPrefix()+pattern; - else - return super.getPresentationHeader(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutEncoderBase.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutEncoderBase.java index ba3e20e70468d81b927b476076e8f6513e7554be..062d085d02276640049e495baca63362e44e55e2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutEncoderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/PatternLayoutEncoderBase.java @@ -18,51 +18,48 @@ import ch.qos.logback.core.encoder.LayoutWrappingEncoder; public class PatternLayoutEncoderBase extends LayoutWrappingEncoder { - String pattern; + String pattern; - // due to popular demand outputPatternAsHeader is set to false by default - protected boolean outputPatternAsHeader = false; + // due to popular demand outputPatternAsHeader is set to false by default + protected boolean outputPatternAsHeader = false; - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String pattern) { - this.pattern = pattern; - } + public void setPattern(String pattern) { + this.pattern = pattern; + } - public boolean isOutputPatternAsHeader() { - return outputPatternAsHeader; - } + public boolean isOutputPatternAsHeader() { + return outputPatternAsHeader; + } + /** + * Print the pattern string as a header in log files + * + * @param outputPatternAsHeader + * @since 1.0.3 + */ + public void setOutputPatternAsHeader(boolean outputPatternAsHeader) { + this.outputPatternAsHeader = outputPatternAsHeader; + } - /** - * Print the pattern string as a header in log files - * - * @param outputPatternAsHeader - * @since 1.0.3 - */ - public void setOutputPatternAsHeader(boolean outputPatternAsHeader) { - this.outputPatternAsHeader = outputPatternAsHeader; - } + public boolean isOutputPatternAsPresentationHeader() { + return outputPatternAsHeader; + } + /** + * @deprecated replaced by {@link #setOutputPatternAsHeader(boolean)} + */ + public void setOutputPatternAsPresentationHeader(boolean outputPatternAsHeader) { + addWarn("[outputPatternAsPresentationHeader] property is deprecated. Please use [outputPatternAsHeader] option instead."); + this.outputPatternAsHeader = outputPatternAsHeader; + } - public boolean isOutputPatternAsPresentationHeader() { - return outputPatternAsHeader; - } - - /** - * @deprecated replaced by {@link #setOutputPatternAsHeader(boolean)} - */ - public void setOutputPatternAsPresentationHeader(boolean outputPatternAsHeader) { - addWarn("[outputPatternAsPresentationHeader] property is deprecated. Please use [outputPatternAsHeader] option instead."); - this.outputPatternAsHeader = outputPatternAsHeader; - } - - @Override - public void setLayout(Layout layout) { - throw new UnsupportedOperationException("one cannot set the layout of " - + this.getClass().getName()); - } + @Override + public void setLayout(Layout layout) { + throw new UnsupportedOperationException("one cannot set the layout of " + this.getClass().getName()); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/PostCompileProcessor.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/PostCompileProcessor.java index 4683d1f53ef1f45088486556d4e2bc42e40cf6ba..5966d49c5b0a89de4905d580f46bc16cf5864e30 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/PostCompileProcessor.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/PostCompileProcessor.java @@ -15,7 +15,6 @@ package ch.qos.logback.core.pattern; import ch.qos.logback.core.Context; - /** * Implements this to perform post compile processing for a PatternLayout. * @@ -26,11 +25,11 @@ import ch.qos.logback.core.Context; */ public interface PostCompileProcessor { - /** - * Post compile processing of the converter chain. - * - * @param head - * The first converter in the chain - */ - void process(Context context, Converter head); + /** + * Post compile processing of the converter chain. + * + * @param head + * The first converter in the chain + */ + void process(Context context, Converter head); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/ReplacingCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/ReplacingCompositeConverter.java index 2db2f4dedb1dd54c714147c7632c5a9b076e46c2..6c79044e176ef4629f8d1ff0a19ee148278be4b6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/ReplacingCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/ReplacingCompositeConverter.java @@ -18,33 +18,33 @@ import java.util.regex.Pattern; public class ReplacingCompositeConverter extends CompositeConverter { - Pattern pattern; - String regex; - String replacement; + Pattern pattern; + String regex; + String replacement; - public void start() { - final List optionList = getOptionList(); - if (optionList == null) { - addError("at least two options are expected whereas you have declared none"); - return; - } + public void start() { + final List optionList = getOptionList(); + if (optionList == null) { + addError("at least two options are expected whereas you have declared none"); + return; + } - int numOpts = optionList.size(); + int numOpts = optionList.size(); - if (numOpts < 2) { - addError("at least two options are expected whereas you have declared only " + numOpts + "as [" + optionList + "]"); - return; + if (numOpts < 2) { + addError("at least two options are expected whereas you have declared only " + numOpts + "as [" + optionList + "]"); + return; + } + regex = optionList.get(0); + pattern = Pattern.compile(regex); + replacement = optionList.get(1); + super.start(); } - regex = optionList.get(0); - pattern = Pattern.compile(regex); - replacement = optionList.get(1); - super.start(); - } - @Override - protected String transform(E event, String in) { - if (!started) - return in; - return pattern.matcher(in).replaceAll(replacement); - } + @Override + protected String transform(E event, String in) { + if (!started) + return in; + return pattern.matcher(in).replaceAll(replacement); + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/SpacePadder.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/SpacePadder.java index 0c0c143d63cb8992e72233139eb7a4eaea731af7..1d83e0b396304d053ca3412b62c55e668e1068eb 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/SpacePadder.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/SpacePadder.java @@ -15,50 +15,50 @@ package ch.qos.logback.core.pattern; public class SpacePadder { - final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 - // spaces - " ", // 16 spaces - " " }; // 32 spaces + final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 + // spaces + " ", // 16 spaces + " " }; // 32 spaces - final static public void leftPad(StringBuilder buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); + final static public void leftPad(StringBuilder buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } + if (s != null) { + buf.append(s); + } } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - if (s != null) { - buf.append(s); - } - } - final static public void rightPad(StringBuilder buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); - } - if (s != null) { - buf.append(s); - } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - } - - /** - * Fast space padding method. - */ - final static public void spacePad(StringBuilder sbuf, int length) { - while (length >= 32) { - sbuf.append(SPACES[5]); - length -= 32; + final static public void rightPad(StringBuilder buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (s != null) { + buf.append(s); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } } - for (int i = 4; i >= 0; i--) { - if ((length & (1 << i)) != 0) { - sbuf.append(SPACES[i]); - } + /** + * Fast space padding method. + */ + final static public void spacePad(StringBuilder sbuf, int length) { + while (length >= 32) { + sbuf.append(SPACES[5]); + length -= 32; + } + + for (int i = 4; i >= 0; i--) { + if ((length & (1 << i)) != 0) { + sbuf.append(SPACES[i]); + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ANSIConstants.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ANSIConstants.java index 1cba59049a3ef472bde23a4f373a8ebf0931e180..c67168feb084b3f991c7c35f6f4b6b67b2297340 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ANSIConstants.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ANSIConstants.java @@ -15,19 +15,18 @@ package ch.qos.logback.core.pattern.color; public class ANSIConstants { - public final static String ESC_START = "\033["; - public final static String ESC_END = "m"; - public final static String BOLD = "1;"; - - public final static String BLACK_FG = "30"; - public final static String RED_FG = "31"; - public final static String GREEN_FG = "32"; - public final static String YELLOW_FG = "33"; - public final static String BLUE_FG = "34"; - public final static String MAGENTA_FG = "35"; - public final static String CYAN_FG = "36"; - public final static String WHITE_FG = "37"; - public final static String DEFAULT_FG = "39"; + public final static String ESC_START = "\033["; + public final static String ESC_END = "m"; + public final static String BOLD = "1;"; + public final static String BLACK_FG = "30"; + public final static String RED_FG = "31"; + public final static String GREEN_FG = "32"; + public final static String YELLOW_FG = "33"; + public final static String BLUE_FG = "34"; + public final static String MAGENTA_FG = "35"; + public final static String CYAN_FG = "36"; + public final static String WHITE_FG = "37"; + public final static String DEFAULT_FG = "39"; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlackCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlackCompositeConverter.java index d34f1da50ef4a7c0d4f517b33a8e32d8b15d1caf..16069544eb7ddcb9c57deb19112b2c5b590b0040 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlackCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlackCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class BlackCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.BLACK_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.BLACK_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlueCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlueCompositeConverter.java index 11a6eba6dbe891a46f5e468a6b8237120fdaabaf..8f227b75de9cc8045e487ddb1fe0650910df6f8d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlueCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BlueCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class BlueCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.BLUE_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.BLUE_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldBlueCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldBlueCompositeConverter.java index 63ec274f3e8c34bc52896b9643775db682a84158..e9100e7c37ffeeb31cece5edd66bafb60ea26532 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldBlueCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldBlueCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.BOLD; */ public class BoldBlueCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + BLUE_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + BLUE_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldCyanCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldCyanCompositeConverter.java index ad3983d6a4d92b3707a7b230446311668b3ee7cd..327b4f720e34a4fb6795895dbf76aa00308dea06 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldCyanCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldCyanCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.CYAN_FG; */ public class BoldCyanCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + CYAN_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + CYAN_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldGreenCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldGreenCompositeConverter.java index bdc6fc03f0c5959d3b99fc632a07c77ef2239eae..23e2677f1be1ac3afe23850f0ef5cc58dc94ad4a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldGreenCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldGreenCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.GREEN_FG; */ public class BoldGreenCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + GREEN_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + GREEN_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldMagentaCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldMagentaCompositeConverter.java index 03d6edae5b863641e455675e6f1420b9acc63f94..2d0751d21fa7e542ae888987a8bdf1f9f373e8b5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldMagentaCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldMagentaCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.MAGENTA_FG; */ public class BoldMagentaCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + MAGENTA_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + MAGENTA_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldRedCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldRedCompositeConverter.java index 59579f48fb55aba4f775af513ed00077cb87f22c..3edc98e2ad1aa1550eafc4482b99b5b533fca82c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldRedCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldRedCompositeConverter.java @@ -21,10 +21,10 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.*; * @author Ceki Gülcü * @since 1.0.5 */ -public class BoldRedCompositeConverter extends ForegroundCompositeConverterBase { +public class BoldRedCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD+RED_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + RED_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldWhiteCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldWhiteCompositeConverter.java index e98208d8359431c871087dabe487fa08df8e195b..75bb915b220cedc0622c2b9d36641eb76ba45ed2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldWhiteCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldWhiteCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.WHITE_FG; */ public class BoldWhiteCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + WHITE_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + WHITE_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldYellowCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldYellowCompositeConverter.java index 8cc55a0b24330ea295639db5b184cacb437535ed..c11603c942c235d260270d1359318964197a92d3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldYellowCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/BoldYellowCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.YELLOW_FG; */ public class BoldYellowCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + YELLOW_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + YELLOW_FG; + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/CyanCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/CyanCompositeConverter.java index dbfeecce927ba049562031738a36df69bfb11bfa..43f138b90439234b0b7f0d135fb9b27faea40b98 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/CyanCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/CyanCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class CyanCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.CYAN_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.CYAN_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ForegroundCompositeConverterBase.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ForegroundCompositeConverterBase.java index caa139f29dcd4be6327878f43b0752bb0a47a9cb..cb1dc7facfc60583dee69fdf78a97dcc371f8eb7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ForegroundCompositeConverterBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/ForegroundCompositeConverterBase.java @@ -24,22 +24,22 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.*; */ abstract public class ForegroundCompositeConverterBase extends CompositeConverter { - final private static String SET_DEFAULT_COLOR = ESC_START+"0;"+DEFAULT_FG+ESC_END; + final private static String SET_DEFAULT_COLOR = ESC_START + "0;" + DEFAULT_FG + ESC_END; - @Override - protected String transform(E event, String in) { - StringBuilder sb = new StringBuilder(); - sb.append(ESC_START); - sb.append(getForegroundColorCode(event)); - sb.append(ESC_END); - sb.append(in); - sb.append(SET_DEFAULT_COLOR); - return sb.toString(); - } + @Override + protected String transform(E event, String in) { + StringBuilder sb = new StringBuilder(); + sb.append(ESC_START); + sb.append(getForegroundColorCode(event)); + sb.append(ESC_END); + sb.append(in); + sb.append(SET_DEFAULT_COLOR); + return sb.toString(); + } - /** - * Derived classes return the foreground color specific to the derived class instance. - * @return the foreground color for this instance - */ - abstract protected String getForegroundColorCode(E event); + /** + * Derived classes return the foreground color specific to the derived class instance. + * @return the foreground color for this instance + */ + abstract protected String getForegroundColorCode(E event); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java index 841ed3b2a148f2a3484dc423656f8b9a8bdeb36c..8db9621e3504ab7852537196c70a3d7936b46045 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java @@ -25,8 +25,8 @@ import static ch.qos.logback.core.pattern.color.ANSIConstants.*; */ public class GrayCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return BOLD + BLACK_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return BOLD + BLACK_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GreenCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GreenCompositeConverter.java index b4baea9fc7b46869e9aabbf1e918ac8ff2acf641..3d0b10b6b828a36275a5d6155513531ea0440566 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GreenCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GreenCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class GreenCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.GREEN_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.GREEN_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java index a16d69e878d7d5869d495e685277a4e4579a633c..c98f41f411c8cb148102797ed9aaf97357d97df1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class MagentaCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.MAGENTA_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.MAGENTA_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/RedCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/RedCompositeConverter.java index eb495de406165a65fcc42f0103973adf1d88cd4e..35d0af9ad264e6a28ca05f4ee7795b1a6bf7c469 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/RedCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/RedCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class RedCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.RED_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.RED_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/WhiteCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/WhiteCompositeConverter.java index 5e4e6445a35ae4f09bc85b99dc30ea20471da700..0bee2d7be7f12af2326e3cfa4a1d71cd3b46daa0 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/WhiteCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/WhiteCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class WhiteCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.WHITE_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.WHITE_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/YellowCompositeConverter.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/YellowCompositeConverter.java index 1c71fe60a1f38d8ecc86ccbff672f8703b8925ba..a0b56d50c9b677d26d98981b3aecf3a2f72f00e6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/color/YellowCompositeConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/color/YellowCompositeConverter.java @@ -21,8 +21,8 @@ package ch.qos.logback.core.pattern.color; */ public class YellowCompositeConverter extends ForegroundCompositeConverterBase { - @Override - protected String getForegroundColorCode(E event) { - return ANSIConstants.YELLOW_FG; - } + @Override + protected String getForegroundColorCode(E event) { + return ANSIConstants.YELLOW_FG; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Compiler.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Compiler.java index 1bb36891229860eaeb1bc4b0f696dc89eafd4b76..4a472cf77cfb26adec59beced20ccb934c6630a1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Compiler.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Compiler.java @@ -25,135 +25,125 @@ import ch.qos.logback.core.util.OptionHelper; class Compiler extends ContextAwareBase { - Converter head; - Converter tail; - final Node top; - final Map converterMap; + Converter head; + Converter tail; + final Node top; + final Map converterMap; - Compiler(final Node top, final Map converterMap) { - this.top = top; - this.converterMap = converterMap; - } + Compiler(final Node top, final Map converterMap) { + this.top = top; + this.converterMap = converterMap; + } - Converter compile() { - head = tail = null; - for (Node n = top; n != null; n = n.next) { - switch (n.type) { - case Node.LITERAL: - addToList(new LiteralConverter((String) n.getValue())); - break; - case Node.COMPOSITE_KEYWORD: - CompositeNode cn = (CompositeNode) n; - CompositeConverter compositeConverter = createCompositeConverter(cn); - if(compositeConverter == null) { - addError("Failed to create converter for [%"+cn.getValue()+"] keyword"); - addToList(new LiteralConverter("%PARSER_ERROR["+cn.getValue()+"]")); - break; - } - compositeConverter.setFormattingInfo(cn.getFormatInfo()); - compositeConverter.setOptionList(cn.getOptions()); - Compiler childCompiler = new Compiler(cn.getChildNode(), - converterMap); - childCompiler.setContext(context); - Converter childConverter = childCompiler.compile(); - compositeConverter.setChildConverter(childConverter); - addToList(compositeConverter); - break; - case Node.SIMPLE_KEYWORD: - SimpleKeywordNode kn = (SimpleKeywordNode) n; - DynamicConverter dynaConverter = createConverter(kn); - if (dynaConverter != null) { - dynaConverter.setFormattingInfo(kn.getFormatInfo()); - dynaConverter.setOptionList(kn.getOptions()); - addToList(dynaConverter); - } else { - // if the appropriate dynaconverter cannot be found, then replace - // it with a dummy LiteralConverter indicating an error. - Converter errConveter = new LiteralConverter("%PARSER_ERROR[" - + kn.getValue() + "]"); - addStatus(new ErrorStatus("[" + kn.getValue() - + "] is not a valid conversion word", this)); - addToList(errConveter); - } + Converter compile() { + head = tail = null; + for (Node n = top; n != null; n = n.next) { + switch (n.type) { + case Node.LITERAL: + addToList(new LiteralConverter((String) n.getValue())); + break; + case Node.COMPOSITE_KEYWORD: + CompositeNode cn = (CompositeNode) n; + CompositeConverter compositeConverter = createCompositeConverter(cn); + if (compositeConverter == null) { + addError("Failed to create converter for [%" + cn.getValue() + "] keyword"); + addToList(new LiteralConverter("%PARSER_ERROR[" + cn.getValue() + "]")); + break; + } + compositeConverter.setFormattingInfo(cn.getFormatInfo()); + compositeConverter.setOptionList(cn.getOptions()); + Compiler childCompiler = new Compiler(cn.getChildNode(), converterMap); + childCompiler.setContext(context); + Converter childConverter = childCompiler.compile(); + compositeConverter.setChildConverter(childConverter); + addToList(compositeConverter); + break; + case Node.SIMPLE_KEYWORD: + SimpleKeywordNode kn = (SimpleKeywordNode) n; + DynamicConverter dynaConverter = createConverter(kn); + if (dynaConverter != null) { + dynaConverter.setFormattingInfo(kn.getFormatInfo()); + dynaConverter.setOptionList(kn.getOptions()); + addToList(dynaConverter); + } else { + // if the appropriate dynaconverter cannot be found, then replace + // it with a dummy LiteralConverter indicating an error. + Converter errConveter = new LiteralConverter("%PARSER_ERROR[" + kn.getValue() + "]"); + addStatus(new ErrorStatus("[" + kn.getValue() + "] is not a valid conversion word", this)); + addToList(errConveter); + } - } + } + } + return head; } - return head; - } - private void addToList(Converter c) { - if (head == null) { - head = tail = c; - } else { - tail.setNext(c); - tail = c; + private void addToList(Converter c) { + if (head == null) { + head = tail = c; + } else { + tail.setNext(c); + tail = c; + } } - } - /** - * Attempt to create a converter using the information found in - * 'converterMap'. - * - * @param kn - * @return - */ - @SuppressWarnings("unchecked") - DynamicConverter createConverter(SimpleKeywordNode kn) { - String keyword = (String) kn.getValue(); - String converterClassStr = (String) converterMap.get(keyword); + /** + * Attempt to create a converter using the information found in + * 'converterMap'. + * + * @param kn + * @return + */ + @SuppressWarnings("unchecked") + DynamicConverter createConverter(SimpleKeywordNode kn) { + String keyword = (String) kn.getValue(); + String converterClassStr = (String) converterMap.get(keyword); - if (converterClassStr != null) { - try { - return (DynamicConverter) OptionHelper.instantiateByClassName( - converterClassStr, DynamicConverter.class, context); - } catch (Exception e) { - addError("Failed to instantiate converter class [" + converterClassStr - + "] for keyword ["+keyword+"]", e); - return null; - } - } else { - addError("There is no conversion class registered for conversion word [" - + keyword + "]"); - return null; + if (converterClassStr != null) { + try { + return (DynamicConverter) OptionHelper.instantiateByClassName(converterClassStr, DynamicConverter.class, context); + } catch (Exception e) { + addError("Failed to instantiate converter class [" + converterClassStr + "] for keyword [" + keyword + "]", e); + return null; + } + } else { + addError("There is no conversion class registered for conversion word [" + keyword + "]"); + return null; + } } - } - /** - * Attempt to create a converter using the information found in - * 'compositeConverterMap'. - * - * @param cn - * @return - */ - @SuppressWarnings("unchecked") - CompositeConverter createCompositeConverter(CompositeNode cn) { - String keyword = (String) cn.getValue(); - String converterClassStr = (String) converterMap.get(keyword); + /** + * Attempt to create a converter using the information found in + * 'compositeConverterMap'. + * + * @param cn + * @return + */ + @SuppressWarnings("unchecked") + CompositeConverter createCompositeConverter(CompositeNode cn) { + String keyword = (String) cn.getValue(); + String converterClassStr = (String) converterMap.get(keyword); - if (converterClassStr != null) { - try { - return (CompositeConverter) OptionHelper.instantiateByClassName( - converterClassStr, CompositeConverter.class, context); - } catch (Exception e) { - addError("Failed to instantiate converter class [" + converterClassStr - + "] as a composite converter for keyword ["+keyword+"]", e); - return null; - } - } else { - addError("There is no conversion class registered for composite conversion word [" - + keyword + "]"); - return null; + if (converterClassStr != null) { + try { + return (CompositeConverter) OptionHelper.instantiateByClassName(converterClassStr, CompositeConverter.class, context); + } catch (Exception e) { + addError("Failed to instantiate converter class [" + converterClassStr + "] as a composite converter for keyword [" + keyword + "]", e); + return null; + } + } else { + addError("There is no conversion class registered for composite conversion word [" + keyword + "]"); + return null; + } } - } - - // public void setStatusManager(StatusManager statusManager) { - // this.statusManager = statusManager; - // } - // - // void addStatus(Status status) { - // if(statusManager != null) { - // statusManager.add(status); - // } - // } + // public void setStatusManager(StatusManager statusManager) { + // this.statusManager = statusManager; + // } + // + // void addStatus(Status status) { + // if(statusManager != null) { + // statusManager.add(status); + // } + // } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/CompositeNode.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/CompositeNode.java index f5d743c52ddd0d403b14290d58bb30e1fa562f29..5ae8619401759c85e61c00bb6f0a097ebfa80110 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/CompositeNode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/CompositeNode.java @@ -14,47 +14,46 @@ package ch.qos.logback.core.pattern.parser; public class CompositeNode extends SimpleKeywordNode { - Node childNode; + Node childNode; - CompositeNode(String keyword) { - super(Node.COMPOSITE_KEYWORD, keyword); + CompositeNode(String keyword) { + super(Node.COMPOSITE_KEYWORD, keyword); - } + } + + public Node getChildNode() { + return childNode; + } + + public void setChildNode(Node childNode) { + this.childNode = childNode; + } + + public boolean equals(Object o) { + if (!super.equals(o)) { + return false; + } + if (!(o instanceof CompositeNode)) { + return false; + } + CompositeNode r = (CompositeNode) o; - public Node getChildNode() { - return childNode; - } + return (childNode != null) ? childNode.equals(r.childNode) : (r.childNode == null); + } - public void setChildNode(Node childNode) { - this.childNode = childNode; - } + @Override + public int hashCode() { + return super.hashCode(); + } - public boolean equals(Object o) { - if(!super.equals(o)) { - return false; + public String toString() { + StringBuilder buf = new StringBuilder(); + if (childNode != null) { + buf.append("CompositeNode(" + childNode + ")"); + } else { + buf.append("CompositeNode(no child)"); + } + buf.append(printNext()); + return buf.toString(); } - if (!(o instanceof CompositeNode)) { - return false; - } - CompositeNode r = (CompositeNode) o; - - return (childNode != null) ? childNode.equals(r.childNode) - : (r.childNode == null); - } - - @Override - public int hashCode() { - return super.hashCode(); - } - - public String toString() { - StringBuilder buf = new StringBuilder(); - if(childNode != null) { - buf.append("CompositeNode("+childNode+")"); - } else { - buf.append("CompositeNode(no child)"); - } - buf.append(printNext()); - return buf.toString(); - } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/FormattingNode.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/FormattingNode.java index 297aa569a19cfb7f92d750a9eddfc3b156cd9c67..5cf16f513740c8cb34490cb47530af0333293c99 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/FormattingNode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/FormattingNode.java @@ -17,42 +17,41 @@ import ch.qos.logback.core.pattern.FormatInfo; public class FormattingNode extends Node { - FormatInfo formatInfo; + FormatInfo formatInfo; - FormattingNode(int type) { - super(type); - } + FormattingNode(int type) { + super(type); + } + + FormattingNode(int type, Object value) { + super(type, value); + } - FormattingNode(int type, Object value) { - super(type, value); - } + public FormatInfo getFormatInfo() { + return formatInfo; + } + + public void setFormatInfo(FormatInfo formatInfo) { + this.formatInfo = formatInfo; + } - public FormatInfo getFormatInfo() { - return formatInfo; - } + public boolean equals(Object o) { + if (!super.equals(o)) { + return false; + } - public void setFormatInfo(FormatInfo formatInfo) { - this.formatInfo = formatInfo; - } + if (!(o instanceof FormattingNode)) { + return false; + } + FormattingNode r = (FormattingNode) o; - public boolean equals(Object o) { - if (!super.equals(o)) { - return false; + return (formatInfo != null ? formatInfo.equals(r.formatInfo) : r.formatInfo == null); } - if(!(o instanceof FormattingNode)) { - return false; + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (formatInfo != null ? formatInfo.hashCode() : 0); + return result; } - FormattingNode r = (FormattingNode) o; - - return (formatInfo != null ? formatInfo.equals(r.formatInfo) - : r.formatInfo == null); - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (formatInfo != null ? formatInfo.hashCode() : 0); - return result; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Node.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Node.java index 756e884b3ff6c2172224c0dfcae477ebcd682cb8..7fb543d2ff6c7dbdf514b7acd48e86ffc56d9720 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Node.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Node.java @@ -14,86 +14,84 @@ package ch.qos.logback.core.pattern.parser; public class Node { - static final int LITERAL = 0; - static final int SIMPLE_KEYWORD = 1; - static final int COMPOSITE_KEYWORD = 2; + static final int LITERAL = 0; + static final int SIMPLE_KEYWORD = 1; + static final int COMPOSITE_KEYWORD = 2; - final int type; - final Object value; - Node next; + final int type; + final Object value; + Node next; - Node(int type) { - this(type, null); - } + Node(int type) { + this(type, null); + } - Node(int type, Object value) { - this.type = type; - this.value = value; - } + Node(int type, Object value) { + this.type = type; + this.value = value; + } - /** - * @return Returns the type. - */ - public int getType() { - return type; - } + /** + * @return Returns the type. + */ + public int getType() { + return type; + } - /** - * @return Returns the value. - */ - public Object getValue() { - return value; - } + /** + * @return Returns the value. + */ + public Object getValue() { + return value; + } - public Node getNext() { - return next; - } + public Node getNext() { + return next; + } - public void setNext(Node next) { - this.next = next; - } + public void setNext(Node next) { + this.next = next; + } - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Node)) { - return false; - } - Node r = (Node) o; + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Node)) { + return false; + } + Node r = (Node) o; - return (type == r.type) - && (value != null ? value.equals(r.value) : r.value == null) - && (next != null ? next.equals(r.next) : r.next == null); - } + return (type == r.type) && (value != null ? value.equals(r.value) : r.value == null) && (next != null ? next.equals(r.next) : r.next == null); + } - @Override - public int hashCode() { - int result = type; - result = 31 * result + (value != null ? value.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = type; + result = 31 * result + (value != null ? value.hashCode() : 0); + return result; + } - String printNext() { - if (next != null) { - return " -> " + next; - } else { - return ""; - } - } + String printNext() { + if (next != null) { + return " -> " + next; + } else { + return ""; + } + } - public String toString() { - StringBuilder buf = new StringBuilder(); - switch (type) { - case LITERAL: - buf.append("LITERAL(" + value + ")"); - break; - default: - buf.append(super.toString()); - } + public String toString() { + StringBuilder buf = new StringBuilder(); + switch (type) { + case LITERAL: + buf.append("LITERAL(" + value + ")"); + break; + default: + buf.append(super.toString()); + } - buf.append(printNext()); - - return buf.toString(); - } + buf.append(printNext()); + + return buf.toString(); + } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/OptionTokenizer.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/OptionTokenizer.java index ce32a3548fc3f75e0b84bb4e3b4308849c937f01..2b2791d3740819f40f3aaefdb9a3da75794f13dd 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/OptionTokenizer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/OptionTokenizer.java @@ -21,128 +21,124 @@ import ch.qos.logback.core.pattern.util.IEscapeUtil; import static ch.qos.logback.core.CoreConstants.CURLY_RIGHT; - import static ch.qos.logback.core.CoreConstants.ESCAPE_CHAR; import static ch.qos.logback.core.CoreConstants.COMMA_CHAR; import static ch.qos.logback.core.CoreConstants.SINGLE_QUOTE_CHAR; import static ch.qos.logback.core.CoreConstants.DOUBLE_QUOTE_CHAR; - import ch.qos.logback.core.pattern.parser.TokenStream.TokenizerState; import ch.qos.logback.core.spi.ScanException; public class OptionTokenizer { - private final static int EXPECTING_STATE = 0; - private final static int RAW_COLLECTING_STATE = 1; - private final static int QUOTED_COLLECTING_STATE = 2; - - - final IEscapeUtil escapeUtil; - final TokenStream tokenStream; - final String pattern; - final int patternLength; - - char quoteChar; - int state = EXPECTING_STATE; - - OptionTokenizer(TokenStream tokenStream) { - this(tokenStream, new AsIsEscapeUtil()); - } - - OptionTokenizer(TokenStream tokenStream, IEscapeUtil escapeUtil) { - this.tokenStream = tokenStream; - this.pattern = tokenStream.pattern; - this.patternLength = tokenStream.patternLength; - this.escapeUtil = escapeUtil; - } - - void tokenize(char firstChar, List tokenList) throws ScanException { - StringBuffer buf = new StringBuffer(); - List optionList = new ArrayList(); - char c = firstChar; - - while (tokenStream.pointer < patternLength) { - switch (state) { - case EXPECTING_STATE: - switch (c) { - case ' ': - case '\t': - case '\r': - case '\n': - case COMMA_CHAR: - break; - case SINGLE_QUOTE_CHAR: - case DOUBLE_QUOTE_CHAR: - state = QUOTED_COLLECTING_STATE; - quoteChar = c; - break; - case CURLY_RIGHT: - emitOptionToken(tokenList, optionList); - return; - default: - buf.append(c); - state = RAW_COLLECTING_STATE; - } - break; - case RAW_COLLECTING_STATE: - switch (c) { - case COMMA_CHAR: - optionList.add(buf.toString().trim()); - buf.setLength(0); - state = EXPECTING_STATE; - break; - case CURLY_RIGHT: - optionList.add(buf.toString().trim()); - emitOptionToken(tokenList, optionList); - return; - default: - buf.append(c); - } - break; - case QUOTED_COLLECTING_STATE: - if (c == quoteChar) { - optionList.add(buf.toString()); - buf.setLength(0); - state = EXPECTING_STATE; - } else if (c == ESCAPE_CHAR) { - escape(String.valueOf(quoteChar), buf); - } else { - buf.append(c); - } - - break; - } - - c = pattern.charAt(tokenStream.pointer); - tokenStream.pointer++; + private final static int EXPECTING_STATE = 0; + private final static int RAW_COLLECTING_STATE = 1; + private final static int QUOTED_COLLECTING_STATE = 2; + + final IEscapeUtil escapeUtil; + final TokenStream tokenStream; + final String pattern; + final int patternLength; + + char quoteChar; + int state = EXPECTING_STATE; + + OptionTokenizer(TokenStream tokenStream) { + this(tokenStream, new AsIsEscapeUtil()); } + OptionTokenizer(TokenStream tokenStream, IEscapeUtil escapeUtil) { + this.tokenStream = tokenStream; + this.pattern = tokenStream.pattern; + this.patternLength = tokenStream.patternLength; + this.escapeUtil = escapeUtil; + } - // EOS - if (c == CURLY_RIGHT) { - if(state == EXPECTING_STATE) { - emitOptionToken(tokenList, optionList); - } else if(state == RAW_COLLECTING_STATE){ - optionList.add(buf.toString().trim()); - emitOptionToken(tokenList, optionList); - } else { - throw new ScanException("Unexpected end of pattern string in OptionTokenizer"); - } - } else { - throw new ScanException("Unexpected end of pattern string in OptionTokenizer"); + void tokenize(char firstChar, List tokenList) throws ScanException { + StringBuffer buf = new StringBuffer(); + List optionList = new ArrayList(); + char c = firstChar; + + while (tokenStream.pointer < patternLength) { + switch (state) { + case EXPECTING_STATE: + switch (c) { + case ' ': + case '\t': + case '\r': + case '\n': + case COMMA_CHAR: + break; + case SINGLE_QUOTE_CHAR: + case DOUBLE_QUOTE_CHAR: + state = QUOTED_COLLECTING_STATE; + quoteChar = c; + break; + case CURLY_RIGHT: + emitOptionToken(tokenList, optionList); + return; + default: + buf.append(c); + state = RAW_COLLECTING_STATE; + } + break; + case RAW_COLLECTING_STATE: + switch (c) { + case COMMA_CHAR: + optionList.add(buf.toString().trim()); + buf.setLength(0); + state = EXPECTING_STATE; + break; + case CURLY_RIGHT: + optionList.add(buf.toString().trim()); + emitOptionToken(tokenList, optionList); + return; + default: + buf.append(c); + } + break; + case QUOTED_COLLECTING_STATE: + if (c == quoteChar) { + optionList.add(buf.toString()); + buf.setLength(0); + state = EXPECTING_STATE; + } else if (c == ESCAPE_CHAR) { + escape(String.valueOf(quoteChar), buf); + } else { + buf.append(c); + } + + break; + } + + c = pattern.charAt(tokenStream.pointer); + tokenStream.pointer++; + } + + // EOS + if (c == CURLY_RIGHT) { + if (state == EXPECTING_STATE) { + emitOptionToken(tokenList, optionList); + } else if (state == RAW_COLLECTING_STATE) { + optionList.add(buf.toString().trim()); + emitOptionToken(tokenList, optionList); + } else { + throw new ScanException("Unexpected end of pattern string in OptionTokenizer"); + } + } else { + throw new ScanException("Unexpected end of pattern string in OptionTokenizer"); + } } - } - void emitOptionToken( List tokenList, List optionList) { - tokenList.add(new Token(Token.OPTION, optionList)); - tokenStream.state = TokenizerState.LITERAL_STATE; - } + void emitOptionToken(List tokenList, List optionList) { + tokenList.add(new Token(Token.OPTION, optionList)); + tokenStream.state = TokenizerState.LITERAL_STATE; + } - void escape(String escapeChars, StringBuffer buf) { - if ((tokenStream.pointer < patternLength)) { - char next = pattern.charAt(tokenStream.pointer++); - escapeUtil.escape(escapeChars, buf, next, tokenStream.pointer); + void escape(String escapeChars, StringBuffer buf) { + if ((tokenStream.pointer < patternLength)) { + char next = pattern.charAt(tokenStream.pointer++); + escapeUtil.escape(escapeChars, buf, next, tokenStream.pointer); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Parser.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Parser.java index 9377003c6fdc3d28fed330c81536c8330216af55..0b0a80639738184fcb573e67784f60413d1d995b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Parser.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Parser.java @@ -41,199 +41,194 @@ import ch.qos.logback.core.spi.ScanException; // OPTION = {...} | ~ // COMPOSITE = E ')' OPTION +public class Parser extends ContextAwareBase { + public final static String MISSING_RIGHT_PARENTHESIS = CoreConstants.CODES_URL + "#missingRightParenthesis"; + public final static Map DEFAULT_COMPOSITE_CONVERTER_MAP = new HashMap(); + public final static String REPLACE_CONVERTER_WORD = "replace"; + static { + DEFAULT_COMPOSITE_CONVERTER_MAP.put(Token.BARE_COMPOSITE_KEYWORD_TOKEN.getValue().toString(), IdentityCompositeConverter.class.getName()); + DEFAULT_COMPOSITE_CONVERTER_MAP.put(REPLACE_CONVERTER_WORD, ReplacingCompositeConverter.class.getName()); + } -public class Parser extends ContextAwareBase { + final List tokenList; + int pointer = 0; + + Parser(TokenStream ts) throws ScanException { + this.tokenList = ts.tokenize(); + } + + public Parser(String pattern) throws ScanException { + this(pattern, new RegularEscapeUtil()); + } + + public Parser(String pattern, IEscapeUtil escapeUtil) throws ScanException { + try { + TokenStream ts = new TokenStream(pattern, escapeUtil); + this.tokenList = ts.tokenize(); + } catch (IllegalArgumentException npe) { + throw new ScanException("Failed to initialize Parser", npe); + } + } + + /** + * When the parsing step is done, the Node list can be transformed into a + * converter chain. + * + * @param top + * @param converterMap + * @return + * @throws ScanException + */ + public Converter compile(final Node top, Map converterMap) { + Compiler compiler = new Compiler(top, converterMap); + compiler.setContext(context); + // compiler.setStatusManager(statusManager); + return compiler.compile(); + } + + public Node parse() throws ScanException { + return E(); + } + + // E = TEopt + Node E() throws ScanException { + Node t = T(); + if (t == null) { + return null; + } + Node eOpt = Eopt(); + if (eOpt != null) { + t.setNext(eOpt); + } + return t; + } + + // Eopt = E|~ + Node Eopt() throws ScanException { + // System.out.println("in Eopt()"); + Token next = getCurentToken(); + // System.out.println("Current token is " + next); + if (next == null) { + return null; + } else { + return E(); + } + } + + // T = LITERAL | '%' C | '%' FORMAT_MODIFIER C + Node T() throws ScanException { + Token t = getCurentToken(); + expectNotNull(t, "a LITERAL or '%'"); + + switch (t.getType()) { + case Token.LITERAL: + advanceTokenPointer(); + return new Node(Node.LITERAL, t.getValue()); + case Token.PERCENT: + advanceTokenPointer(); + // System.out.println("% token found"); + FormatInfo fi; + Token u = getCurentToken(); + FormattingNode c; + expectNotNull(u, "a FORMAT_MODIFIER, SIMPLE_KEYWORD or COMPOUND_KEYWORD"); + if (u.getType() == Token.FORMAT_MODIFIER) { + fi = FormatInfo.valueOf((String) u.getValue()); + advanceTokenPointer(); + c = C(); + c.setFormatInfo(fi); + } else { + c = C(); + } + return c; + + default: + return null; + + } + + } + + FormattingNode C() throws ScanException { + Token t = getCurentToken(); + // System.out.println("in C()"); + // System.out.println("Current token is " + t); + expectNotNull(t, "a LEFT_PARENTHESIS or KEYWORD"); + int type = t.getType(); + switch (type) { + case Token.SIMPLE_KEYWORD: + return SINGLE(); + case Token.COMPOSITE_KEYWORD: + advanceTokenPointer(); + return COMPOSITE(t.getValue().toString()); + default: + throw new IllegalStateException("Unexpected token " + t); + } + } + + FormattingNode SINGLE() throws ScanException { + // System.out.println("in SINGLE()"); + Token t = getNextToken(); + // System.out.println("==" + t); + SimpleKeywordNode keywordNode = new SimpleKeywordNode(t.getValue()); + + Token ot = getCurentToken(); + if (ot != null && ot.getType() == Token.OPTION) { + List optionList = (List) ot.getValue(); + keywordNode.setOptions(optionList); + advanceTokenPointer(); + } + return keywordNode; + } + + FormattingNode COMPOSITE(String keyword) throws ScanException { + CompositeNode compositeNode = new CompositeNode(keyword); + + Node childNode = E(); + compositeNode.setChildNode(childNode); + + Token t = getNextToken(); + + if (t == null || t.getType() != Token.RIGHT_PARENTHESIS) { + String msg = "Expecting RIGHT_PARENTHESIS token but got " + t; + addError(msg); + addError("See also " + MISSING_RIGHT_PARENTHESIS); + throw new ScanException(msg); + } + Token ot = getCurentToken(); + if (ot != null && ot.getType() == Token.OPTION) { + List optionList = (List) ot.getValue(); + compositeNode.setOptions(optionList); + advanceTokenPointer(); + } + return compositeNode; + } + + Token getNextToken() { + if (pointer < tokenList.size()) { + return (Token) tokenList.get(pointer++); + } + return null; + } + + Token getCurentToken() { + if (pointer < tokenList.size()) { + return (Token) tokenList.get(pointer); + } + return null; + } + + void advanceTokenPointer() { + pointer++; + } + + void expectNotNull(Token t, String expected) { + if (t == null) { + throw new IllegalStateException("All tokens consumed but was expecting " + expected); + } + } - public final static String MISSING_RIGHT_PARENTHESIS = CoreConstants.CODES_URL+"#missingRightParenthesis"; - public final static Map DEFAULT_COMPOSITE_CONVERTER_MAP = new HashMap(); - public final static String REPLACE_CONVERTER_WORD = "replace"; - static { - DEFAULT_COMPOSITE_CONVERTER_MAP.put(Token.BARE_COMPOSITE_KEYWORD_TOKEN.getValue().toString(), - IdentityCompositeConverter.class.getName()); - DEFAULT_COMPOSITE_CONVERTER_MAP.put(REPLACE_CONVERTER_WORD, - ReplacingCompositeConverter.class.getName()); - } - - final List tokenList; - int pointer = 0; - - Parser(TokenStream ts) throws ScanException { - this.tokenList = ts.tokenize(); - } - - public Parser(String pattern) throws ScanException { - this(pattern, new RegularEscapeUtil()); - } - - public Parser(String pattern, IEscapeUtil escapeUtil) throws ScanException { - try { - TokenStream ts = new TokenStream(pattern, escapeUtil); - this.tokenList = ts.tokenize(); - } catch (IllegalArgumentException npe) { - throw new ScanException("Failed to initialize Parser", npe); - } - } - - /** - * When the parsing step is done, the Node list can be transformed into a - * converter chain. - * - * @param top - * @param converterMap - * @return - * @throws ScanException - */ - public Converter compile(final Node top, Map converterMap) { - Compiler compiler = new Compiler(top, converterMap); - compiler.setContext(context); - //compiler.setStatusManager(statusManager); - return compiler.compile(); - } - - public Node parse() throws ScanException { - return E(); - } - - // E = TEopt - Node E() throws ScanException { - Node t = T(); - if (t == null) { - return null; - } - Node eOpt = Eopt(); - if (eOpt != null) { - t.setNext(eOpt); - } - return t; - } - - // Eopt = E|~ - Node Eopt() throws ScanException { - // System.out.println("in Eopt()"); - Token next = getCurentToken(); - // System.out.println("Current token is " + next); - if (next == null) { - return null; - } else { - return E(); - } - } - - // T = LITERAL | '%' C | '%' FORMAT_MODIFIER C - Node T() throws ScanException { - Token t = getCurentToken(); - expectNotNull(t, "a LITERAL or '%'"); - - switch (t.getType()) { - case Token.LITERAL: - advanceTokenPointer(); - return new Node(Node.LITERAL, t.getValue()); - case Token.PERCENT: - advanceTokenPointer(); - // System.out.println("% token found"); - FormatInfo fi; - Token u = getCurentToken(); - FormattingNode c; - expectNotNull(u, "a FORMAT_MODIFIER, SIMPLE_KEYWORD or COMPOUND_KEYWORD"); - if (u.getType() == Token.FORMAT_MODIFIER) { - fi = FormatInfo.valueOf((String) u.getValue()); - advanceTokenPointer(); - c = C(); - c.setFormatInfo(fi); - } else { - c = C(); - } - return c; - - default: - return null; - - } - - } - - FormattingNode C() throws ScanException { - Token t = getCurentToken(); - // System.out.println("in C()"); - // System.out.println("Current token is " + t); - expectNotNull(t, "a LEFT_PARENTHESIS or KEYWORD"); - int type = t.getType(); - switch (type) { - case Token.SIMPLE_KEYWORD: - return SINGLE(); - case Token.COMPOSITE_KEYWORD: - advanceTokenPointer(); - return COMPOSITE(t.getValue().toString()); - default: - throw new IllegalStateException("Unexpected token " + t); - } - } - - FormattingNode SINGLE() throws ScanException { - // System.out.println("in SINGLE()"); - Token t = getNextToken(); - // System.out.println("==" + t); - SimpleKeywordNode keywordNode = new SimpleKeywordNode(t.getValue()); - - Token ot = getCurentToken(); - if (ot != null && ot.getType() == Token.OPTION) { - List optionList = (List) ot.getValue(); - keywordNode.setOptions(optionList); - advanceTokenPointer(); - } - return keywordNode; - } - - FormattingNode COMPOSITE(String keyword) throws ScanException { - CompositeNode compositeNode = new CompositeNode(keyword); - - Node childNode = E(); - compositeNode.setChildNode(childNode); - - Token t = getNextToken(); - - if (t == null || t.getType() != Token.RIGHT_PARENTHESIS) { - String msg = "Expecting RIGHT_PARENTHESIS token but got " + t; - addError(msg); - addError("See also "+MISSING_RIGHT_PARENTHESIS); - throw new ScanException(msg); - } - Token ot = getCurentToken(); - if (ot != null && ot.getType() == Token.OPTION) { - List optionList = (List) ot.getValue(); - compositeNode.setOptions(optionList); - advanceTokenPointer(); - } - return compositeNode; - } - - Token getNextToken() { - if (pointer < tokenList.size()) { - return (Token) tokenList.get(pointer++); - } - return null; - } - - Token getCurentToken() { - if (pointer < tokenList.size()) { - return (Token) tokenList.get(pointer); - } - return null; - } - - void advanceTokenPointer() { - pointer++; - } - - void expectNotNull(Token t, String expected) { - if (t == null) { - throw new IllegalStateException("All tokens consumed but was expecting " - + expected); - } - } - -// public void setStatusManager(StatusManager statusManager) { -// this.statusManager = statusManager; -// } + // public void setStatusManager(StatusManager statusManager) { + // this.statusManager = statusManager; + // } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/SimpleKeywordNode.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/SimpleKeywordNode.java index bc8a9fea3d4db82fba5ccec7aeb06104894f274e..80ec6e9838598022e131e142e076a8bf5aca25c7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/SimpleKeywordNode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/SimpleKeywordNode.java @@ -17,52 +17,50 @@ import java.util.List; public class SimpleKeywordNode extends FormattingNode { - List optionList; + List optionList; - SimpleKeywordNode(Object value) { - super(Node.SIMPLE_KEYWORD, value); - } - - protected SimpleKeywordNode(int type, Object value) { - super(type, value); - } - - public List getOptions() { - return optionList; - } + SimpleKeywordNode(Object value) { + super(Node.SIMPLE_KEYWORD, value); + } - public void setOptions(List optionList) { - this.optionList = optionList; - } + protected SimpleKeywordNode(int type, Object value) { + super(type, value); + } - public boolean equals(Object o) { - if (!super.equals(o)) { - return false; + public List getOptions() { + return optionList; } - if (!(o instanceof SimpleKeywordNode)) { - return false; + public void setOptions(List optionList) { + this.optionList = optionList; } - SimpleKeywordNode r = (SimpleKeywordNode) o; - return (optionList != null ? optionList.equals(r.optionList) - : r.optionList == null); - } + public boolean equals(Object o) { + if (!super.equals(o)) { + return false; + } - @Override - public int hashCode() { - return super.hashCode(); - } + if (!(o instanceof SimpleKeywordNode)) { + return false; + } + SimpleKeywordNode r = (SimpleKeywordNode) o; + + return (optionList != null ? optionList.equals(r.optionList) : r.optionList == null); + } + + @Override + public int hashCode() { + return super.hashCode(); + } - public String toString() { - StringBuilder buf = new StringBuilder(); - if (optionList == null) { - buf.append("KeyWord(" + value + "," + formatInfo + ")"); - } else { - buf.append("KeyWord(" + value + ", " + formatInfo + "," + optionList - + ")"); + public String toString() { + StringBuilder buf = new StringBuilder(); + if (optionList == null) { + buf.append("KeyWord(" + value + "," + formatInfo + ")"); + } else { + buf.append("KeyWord(" + value + ", " + formatInfo + "," + optionList + ")"); + } + buf.append(printNext()); + return buf.toString(); } - buf.append(printNext()); - return buf.toString(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Token.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Token.java index 52a116dd80fc10ca79203a97da8b854f3fa1efcc..e72e6ddff209c5b2a5afcb03db68431c6f342dc7 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Token.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/Token.java @@ -15,103 +15,103 @@ package ch.qos.logback.core.pattern.parser; class Token { + static final int PERCENT = 37; + // static final int LEFT_PARENTHESIS = 40; + static final int RIGHT_PARENTHESIS = 41; + static final int MINUS = 45; + static final int DOT = 46; + static final int CURLY_LEFT = 123; + static final int CURLY_RIGHT = 125; + + static final int LITERAL = 1000; + static final int FORMAT_MODIFIER = 1002; + static final int SIMPLE_KEYWORD = 1004; + static final int COMPOSITE_KEYWORD = 1005; + static final int OPTION = 1006; + + static final int EOF = Integer.MAX_VALUE; + + static Token EOF_TOKEN = new Token(EOF, "EOF"); + static Token RIGHT_PARENTHESIS_TOKEN = new Token(RIGHT_PARENTHESIS); + static Token BARE_COMPOSITE_KEYWORD_TOKEN = new Token(COMPOSITE_KEYWORD, "BARE"); + static Token PERCENT_TOKEN = new Token(PERCENT); + + private final int type; + private final Object value; + + public Token(int type) { + this(type, null); + } + + public Token(int type, Object value) { + this.type = type; + this.value = value; + } - static final int PERCENT = 37; - //static final int LEFT_PARENTHESIS = 40; - static final int RIGHT_PARENTHESIS = 41; - static final int MINUS = 45; - static final int DOT = 46; - static final int CURLY_LEFT = 123; - static final int CURLY_RIGHT = 125; - - static final int LITERAL = 1000; - static final int FORMAT_MODIFIER = 1002; - static final int SIMPLE_KEYWORD = 1004; - static final int COMPOSITE_KEYWORD = 1005; - static final int OPTION = 1006; - - static final int EOF = Integer.MAX_VALUE; - - static Token EOF_TOKEN = new Token(EOF, "EOF"); - static Token RIGHT_PARENTHESIS_TOKEN = new Token(RIGHT_PARENTHESIS); - static Token BARE_COMPOSITE_KEYWORD_TOKEN = new Token(COMPOSITE_KEYWORD, "BARE"); - static Token PERCENT_TOKEN = new Token(PERCENT); - - private final int type; - private final Object value; - - - public Token(int type) { - this(type, null); - } - - public Token(int type, Object value) { - this.type = type; - this.value = value; - } - - public int getType() { - return type; - } - - public Object getValue() { - return value; - } - - - public String toString() { - String typeStr = null; - switch (type) { - - case PERCENT: - typeStr = "%"; - break; - case FORMAT_MODIFIER: - typeStr = "FormatModifier"; - break; - case LITERAL: - typeStr = "LITERAL"; - break; - case OPTION: - typeStr = "OPTION"; - break; - case SIMPLE_KEYWORD: - typeStr = "SIMPLE_KEYWORD"; - break; - case COMPOSITE_KEYWORD: - typeStr = "COMPOSITE_KEYWORD"; - break; - case RIGHT_PARENTHESIS: - typeStr = "RIGHT_PARENTHESIS"; - break; - default: - typeStr = "UNKNOWN"; + public int getType() { + return type; } - if (value == null) { - return "Token(" + typeStr + ")"; - } else { - return "Token(" + typeStr + ", \"" + value + "\")"; + public Object getValue() { + return value; } - } - public int hashCode() { - int result; - result = type; - result = 29 * result + (value != null ? value.hashCode() : 0); - return result; - } + public String toString() { + String typeStr = null; + switch (type) { + + case PERCENT: + typeStr = "%"; + break; + case FORMAT_MODIFIER: + typeStr = "FormatModifier"; + break; + case LITERAL: + typeStr = "LITERAL"; + break; + case OPTION: + typeStr = "OPTION"; + break; + case SIMPLE_KEYWORD: + typeStr = "SIMPLE_KEYWORD"; + break; + case COMPOSITE_KEYWORD: + typeStr = "COMPOSITE_KEYWORD"; + break; + case RIGHT_PARENTHESIS: + typeStr = "RIGHT_PARENTHESIS"; + break; + default: + typeStr = "UNKNOWN"; + } + if (value == null) { + return "Token(" + typeStr + ")"; + + } else { + return "Token(" + typeStr + ", \"" + value + "\")"; + } + } + public int hashCode() { + int result; + result = type; + result = 29 * result + (value != null ? value.hashCode() : 0); + return result; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Token)) return false; + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Token)) + return false; - final Token token = (Token) o; + final Token token = (Token) o; - if (type != token.type) return false; - if (value != null ? !value.equals(token.value) : token.value != null) return false; + if (type != token.type) + return false; + if (value != null ? !value.equals(token.value) : token.value != null) + return false; - return true; - } + return true; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/TokenStream.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/TokenStream.java index 0b2c8483ab848567de0a0d3b2e328a59e9cfd394..320418bf8d568bb813237665d956f4a1c854b65d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/TokenStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/parser/TokenStream.java @@ -46,192 +46,190 @@ import ch.qos.logback.core.spi.ScanException; */ class TokenStream { - enum TokenizerState { LITERAL_STATE, FORMAT_MODIFIER_STATE, KEYWORD_STATE, OPTION_STATE, RIGHT_PARENTHESIS_STATE} - - final String pattern; - final int patternLength; - final IEscapeUtil escapeUtil; + enum TokenizerState { + LITERAL_STATE, FORMAT_MODIFIER_STATE, KEYWORD_STATE, OPTION_STATE, RIGHT_PARENTHESIS_STATE + } - final IEscapeUtil optionEscapeUtil = new RestrictedEscapeUtil(); + final String pattern; + final int patternLength; + final IEscapeUtil escapeUtil; - TokenizerState state = TokenizerState.LITERAL_STATE; - int pointer = 0; + final IEscapeUtil optionEscapeUtil = new RestrictedEscapeUtil(); - // this variant should be used for testing purposes only - TokenStream(String pattern) { - this(pattern, new RegularEscapeUtil()); - } + TokenizerState state = TokenizerState.LITERAL_STATE; + int pointer = 0; - TokenStream(String pattern, IEscapeUtil escapeUtil) { - if (pattern == null || pattern.length() == 0) { - throw new IllegalArgumentException( - "null or empty pattern string not allowed"); + // this variant should be used for testing purposes only + TokenStream(String pattern) { + this(pattern, new RegularEscapeUtil()); } - this.pattern = pattern; - patternLength = pattern.length(); - this.escapeUtil = escapeUtil; - } - List tokenize() throws ScanException { - List tokenList = new ArrayList(); - StringBuffer buf = new StringBuffer(); + TokenStream(String pattern, IEscapeUtil escapeUtil) { + if (pattern == null || pattern.length() == 0) { + throw new IllegalArgumentException("null or empty pattern string not allowed"); + } + this.pattern = pattern; + patternLength = pattern.length(); + this.escapeUtil = escapeUtil; + } - while (pointer < patternLength) { - char c = pattern.charAt(pointer); - pointer++; + List tokenize() throws ScanException { + List tokenList = new ArrayList(); + StringBuffer buf = new StringBuffer(); + + while (pointer < patternLength) { + char c = pattern.charAt(pointer); + pointer++; + + switch (state) { + case LITERAL_STATE: + handleLiteralState(c, tokenList, buf); + break; + case FORMAT_MODIFIER_STATE: + handleFormatModifierState(c, tokenList, buf); + break; + case OPTION_STATE: + processOption(c, tokenList, buf); + break; + case KEYWORD_STATE: + handleKeywordState(c, tokenList, buf); + break; + case RIGHT_PARENTHESIS_STATE: + handleRightParenthesisState(c, tokenList, buf); + break; + + default: + } + } - switch (state) { + // EOS + switch (state) { case LITERAL_STATE: - handleLiteralState(c, tokenList, buf); - break; - case FORMAT_MODIFIER_STATE: - handleFormatModifierState(c, tokenList, buf); - break; - case OPTION_STATE: - processOption(c, tokenList, buf); - break; + addValuedToken(Token.LITERAL, buf, tokenList); + break; case KEYWORD_STATE: - handleKeywordState(c, tokenList, buf); - break; + tokenList.add(new Token(Token.SIMPLE_KEYWORD, buf.toString())); + break; case RIGHT_PARENTHESIS_STATE: - handleRightParenthesisState(c, tokenList, buf); - break; + tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN); + break; - default: - } + case FORMAT_MODIFIER_STATE: + case OPTION_STATE: + throw new ScanException("Unexpected end of pattern string"); + } + + return tokenList; } - // EOS - switch (state) { - case LITERAL_STATE: - addValuedToken(Token.LITERAL, buf, tokenList); - break; - case KEYWORD_STATE: - tokenList.add(new Token(Token.SIMPLE_KEYWORD, buf.toString())); - break; - case RIGHT_PARENTHESIS_STATE: + private void handleRightParenthesisState(char c, List tokenList, StringBuffer buf) { tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN); - break; - - case FORMAT_MODIFIER_STATE: - case OPTION_STATE: - throw new ScanException("Unexpected end of pattern string"); + switch (c) { + case CoreConstants.RIGHT_PARENTHESIS_CHAR: + break; + case CURLY_LEFT: + state = TokenizerState.OPTION_STATE; + break; + case ESCAPE_CHAR: + escape("%{}", buf); + state = TokenizerState.LITERAL_STATE; + break; + default: + buf.append(c); + state = TokenizerState.LITERAL_STATE; + } } - return tokenList; - } - - private void handleRightParenthesisState(char c, List tokenList, StringBuffer buf) { - tokenList.add(Token.RIGHT_PARENTHESIS_TOKEN); - switch (c) { - case CoreConstants.RIGHT_PARENTHESIS_CHAR: - break; - case CURLY_LEFT: - state = TokenizerState.OPTION_STATE; - break; - case ESCAPE_CHAR: - escape("%{}", buf); - state = TokenizerState.LITERAL_STATE; - break; - default: - buf.append(c); - state = TokenizerState.LITERAL_STATE; - } - } - - private void processOption(char c, List tokenList, StringBuffer buf) throws ScanException { - OptionTokenizer ot = new OptionTokenizer(this); - ot.tokenize(c, tokenList); - } - - private void handleFormatModifierState(char c, List tokenList, StringBuffer buf) { - if (c == CoreConstants.LEFT_PARENTHESIS_CHAR) { - addValuedToken(Token.FORMAT_MODIFIER, buf, tokenList); - tokenList.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - state = TokenizerState.LITERAL_STATE; - } else if (Character.isJavaIdentifierStart(c)) { - addValuedToken(Token.FORMAT_MODIFIER, buf, tokenList); - state = TokenizerState.KEYWORD_STATE; - buf.append(c); - } else { - buf.append(c); - } - } - - private void handleLiteralState(char c, List tokenList, StringBuffer buf) { - switch (c) { - case ESCAPE_CHAR: - escape("%()", buf); - break; - - case CoreConstants.PERCENT_CHAR: - addValuedToken(Token.LITERAL, buf, tokenList); - tokenList.add(Token.PERCENT_TOKEN); - state = TokenizerState.FORMAT_MODIFIER_STATE; - break; - - case CoreConstants.RIGHT_PARENTHESIS_CHAR: - addValuedToken(Token.LITERAL, buf, tokenList); - state = TokenizerState.RIGHT_PARENTHESIS_STATE; - break; - - default: - buf.append(c); + private void processOption(char c, List tokenList, StringBuffer buf) throws ScanException { + OptionTokenizer ot = new OptionTokenizer(this); + ot.tokenize(c, tokenList); } - } - - private void handleKeywordState(char c, List tokenList, StringBuffer buf) { - - if (Character.isJavaIdentifierPart(c)) { - buf.append(c); - } else if (c == CURLY_LEFT) { - addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); - state = TokenizerState.OPTION_STATE; - } else if (c == CoreConstants.LEFT_PARENTHESIS_CHAR) { - addValuedToken(Token.COMPOSITE_KEYWORD, buf, tokenList); - state = TokenizerState.LITERAL_STATE; - } else if (c == CoreConstants.PERCENT_CHAR) { - addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); - tokenList.add(Token.PERCENT_TOKEN); - state = TokenizerState.FORMAT_MODIFIER_STATE; - } else if (c == CoreConstants.RIGHT_PARENTHESIS_CHAR) { - addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); - state = TokenizerState.RIGHT_PARENTHESIS_STATE; - } else { - addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); - if (c == ESCAPE_CHAR) { - if ((pointer < patternLength)) { - char next = pattern.charAt(pointer++); - escapeUtil.escape("%()", buf, next, pointer); + + private void handleFormatModifierState(char c, List tokenList, StringBuffer buf) { + if (c == CoreConstants.LEFT_PARENTHESIS_CHAR) { + addValuedToken(Token.FORMAT_MODIFIER, buf, tokenList); + tokenList.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + state = TokenizerState.LITERAL_STATE; + } else if (Character.isJavaIdentifierStart(c)) { + addValuedToken(Token.FORMAT_MODIFIER, buf, tokenList); + state = TokenizerState.KEYWORD_STATE; + buf.append(c); + } else { + buf.append(c); } - } else { - buf.append(c); - } - state = TokenizerState.LITERAL_STATE; } - } - void escape(String escapeChars, StringBuffer buf) { - if ((pointer < patternLength)) { - char next = pattern.charAt(pointer++); - escapeUtil.escape(escapeChars, buf, next, pointer); - } - } + private void handleLiteralState(char c, List tokenList, StringBuffer buf) { + switch (c) { + case ESCAPE_CHAR: + escape("%()", buf); + break; + + case CoreConstants.PERCENT_CHAR: + addValuedToken(Token.LITERAL, buf, tokenList); + tokenList.add(Token.PERCENT_TOKEN); + state = TokenizerState.FORMAT_MODIFIER_STATE; + break; - void optionEscape(String escapeChars, StringBuffer buf) { - if ((pointer < patternLength)) { - char next = pattern.charAt(pointer++); - optionEscapeUtil.escape(escapeChars, buf, next, pointer); + case CoreConstants.RIGHT_PARENTHESIS_CHAR: + addValuedToken(Token.LITERAL, buf, tokenList); + state = TokenizerState.RIGHT_PARENTHESIS_STATE; + break; + + default: + buf.append(c); + } } - } + private void handleKeywordState(char c, List tokenList, StringBuffer buf) { + + if (Character.isJavaIdentifierPart(c)) { + buf.append(c); + } else if (c == CURLY_LEFT) { + addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); + state = TokenizerState.OPTION_STATE; + } else if (c == CoreConstants.LEFT_PARENTHESIS_CHAR) { + addValuedToken(Token.COMPOSITE_KEYWORD, buf, tokenList); + state = TokenizerState.LITERAL_STATE; + } else if (c == CoreConstants.PERCENT_CHAR) { + addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); + tokenList.add(Token.PERCENT_TOKEN); + state = TokenizerState.FORMAT_MODIFIER_STATE; + } else if (c == CoreConstants.RIGHT_PARENTHESIS_CHAR) { + addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); + state = TokenizerState.RIGHT_PARENTHESIS_STATE; + } else { + addValuedToken(Token.SIMPLE_KEYWORD, buf, tokenList); + if (c == ESCAPE_CHAR) { + if ((pointer < patternLength)) { + char next = pattern.charAt(pointer++); + escapeUtil.escape("%()", buf, next, pointer); + } + } else { + buf.append(c); + } + state = TokenizerState.LITERAL_STATE; + } + } + void escape(String escapeChars, StringBuffer buf) { + if ((pointer < patternLength)) { + char next = pattern.charAt(pointer++); + escapeUtil.escape(escapeChars, buf, next, pointer); + } + } + void optionEscape(String escapeChars, StringBuffer buf) { + if ((pointer < patternLength)) { + char next = pattern.charAt(pointer++); + optionEscapeUtil.escape(escapeChars, buf, next, pointer); + } + } - private void addValuedToken(int type, StringBuffer buf, List tokenList) { - if (buf.length() > 0) { - tokenList.add(new Token(type, buf.toString())); - buf.setLength(0); + private void addValuedToken(int type, StringBuffer buf, List tokenList) { + if (buf.length() > 0) { + tokenList.add(new Token(type, buf.toString())); + buf.setLength(0); + } } - } } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AlmostAsIsEscapeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AlmostAsIsEscapeUtil.java index 7321ac57d39058b04140e9009205eb06130cb72a..8a51d7fb904edef237b1bda7f42e0cff0b28a5e5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AlmostAsIsEscapeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AlmostAsIsEscapeUtil.java @@ -23,23 +23,22 @@ import ch.qos.logback.core.rolling.helper.FileNamePattern; */ public class AlmostAsIsEscapeUtil extends RestrictedEscapeUtil { - /** - * Do not perform any character escaping, except for '%', and ')'. - * - *

- * Here is the rationale. First, filename patterns do not include escape - * combinations such as \r or \n. Moreover, characters which have special - * meaning in logback parsers, such as '{', or '}' cannot be part of file - * names (so me thinks). The left parenthesis character has special meaning - * only if it is preceded by %. Thus, the only characters that needs escaping - * are '%' and ')'. - * - *

- * Note that this method assumes that it is called after the escape character - * has been consumed. - */ - public void escape(String escapeChars, StringBuffer buf, char next, - int pointer) { - super.escape(""+CoreConstants.PERCENT_CHAR+CoreConstants.RIGHT_PARENTHESIS_CHAR, buf, next, pointer); - } + /** + * Do not perform any character escaping, except for '%', and ')'. + * + *

+ * Here is the rationale. First, filename patterns do not include escape + * combinations such as \r or \n. Moreover, characters which have special + * meaning in logback parsers, such as '{', or '}' cannot be part of file + * names (so me thinks). The left parenthesis character has special meaning + * only if it is preceded by %. Thus, the only characters that needs escaping + * are '%' and ')'. + * + *

+ * Note that this method assumes that it is called after the escape character + * has been consumed. + */ + public void escape(String escapeChars, StringBuffer buf, char next, int pointer) { + super.escape("" + CoreConstants.PERCENT_CHAR + CoreConstants.RIGHT_PARENTHESIS_CHAR, buf, next, pointer); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AsIsEscapeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AsIsEscapeUtil.java index 93a26158c1a5205d51347dc461c91cbf798bbb6e..ae6614a451fa8bd298732d1f4aeebda70134a484 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AsIsEscapeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/AsIsEscapeUtil.java @@ -18,18 +18,17 @@ package ch.qos.logback.core.pattern.util; */ public class AsIsEscapeUtil implements IEscapeUtil { - /** - * Do not perform any character escaping. - *

- * Note that this method assumes that it is called after the escape character - * has been consumed. - */ - public void escape(String escapeChars, StringBuffer buf, char next, - int pointer) { - // restitute the escape char (because it was consumed - // before this method was called). - buf.append("\\"); - // restitute the next character - buf.append(next); - } + /** + * Do not perform any character escaping. + *

+ * Note that this method assumes that it is called after the escape character + * has been consumed. + */ + public void escape(String escapeChars, StringBuffer buf, char next, int pointer) { + // restitute the escape char (because it was consumed + // before this method was called). + buf.append("\\"); + // restitute the next character + buf.append(next); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/IEscapeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/IEscapeUtil.java index 77f14e703a0c28751f54853901fd90547fcf2668..8f646ffb79e64458efb2c65c99f91a5af8d5474a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/IEscapeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/IEscapeUtil.java @@ -15,5 +15,5 @@ package ch.qos.logback.core.pattern.util; public interface IEscapeUtil { - void escape(String additionalEscapeChars, StringBuffer buf, char next, int pointer); + void escape(String additionalEscapeChars, StringBuffer buf, char next, int pointer); } \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RegularEscapeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RegularEscapeUtil.java index 3fdb0cb7fb153ae84655f3bbe9fcebf35b05c597..92b2b3324ab4a9236d196c6ddccfe2ffb67896fe 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RegularEscapeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RegularEscapeUtil.java @@ -20,73 +20,71 @@ package ch.qos.logback.core.pattern.util; */ public class RegularEscapeUtil implements IEscapeUtil { - public void escape(String escapeChars, StringBuffer buf, char next, - int pointer) { - if (escapeChars.indexOf(next) >= 0) { - buf.append(next); - } else - switch (next) { - case '_': - // the \_ sequence is swallowed - break; - case '\\': - buf.append(next); - break; - case 't': - buf.append('\t'); - break; - case 'r': - buf.append('\r'); - break; - case 'n': - buf.append('\n'); - break; - default: - String commaSeperatedEscapeChars = formatEscapeCharsForListing(escapeChars); - throw new IllegalArgumentException("Illegal char '" + next + " at column " - + pointer + ". Only \\\\, \\_" + commaSeperatedEscapeChars - + ", \\t, \\n, \\r combinations are allowed as escape characters."); - } - } + public void escape(String escapeChars, StringBuffer buf, char next, int pointer) { + if (escapeChars.indexOf(next) >= 0) { + buf.append(next); + } else + switch (next) { + case '_': + // the \_ sequence is swallowed + break; + case '\\': + buf.append(next); + break; + case 't': + buf.append('\t'); + break; + case 'r': + buf.append('\r'); + break; + case 'n': + buf.append('\n'); + break; + default: + String commaSeperatedEscapeChars = formatEscapeCharsForListing(escapeChars); + throw new IllegalArgumentException("Illegal char '" + next + " at column " + pointer + ". Only \\\\, \\_" + commaSeperatedEscapeChars + + ", \\t, \\n, \\r combinations are allowed as escape characters."); + } + } - String formatEscapeCharsForListing(String escapeChars) { - StringBuilder commaSeperatedEscapeChars = new StringBuilder(); - for (int i = 0; i < escapeChars.length(); i++) { - commaSeperatedEscapeChars.append(", \\").append(escapeChars.charAt(i)); + String formatEscapeCharsForListing(String escapeChars) { + StringBuilder commaSeperatedEscapeChars = new StringBuilder(); + for (int i = 0; i < escapeChars.length(); i++) { + commaSeperatedEscapeChars.append(", \\").append(escapeChars.charAt(i)); + } + return commaSeperatedEscapeChars.toString(); } - return commaSeperatedEscapeChars.toString(); - } - public static String basicEscape(String s) { - char c; - int len = s.length(); - StringBuilder sbuf = new StringBuilder(len); + public static String basicEscape(String s) { + char c; + int len = s.length(); + StringBuilder sbuf = new StringBuilder(len); - int i = 0; - while (i < len) { - c = s.charAt(i++); - if (c == '\\') { - c = s.charAt(i++); - if (c == 'n') { - c = '\n'; - } else if (c == 'r') { - c = '\r'; - } else if (c == 't') { - c = '\t'; - } else if (c == 'f') { - c = '\f'; - } else if (c == '\b') { - c = '\b'; - } else if (c == '\"') { - c = '\"'; - } else if (c == '\'') { - c = '\''; - } else if (c == '\\') { - c = '\\'; + int i = 0; + while (i < len) { + c = s.charAt(i++); + if (c == '\\') { + c = s.charAt(i++); + if (c == 'n') { + c = '\n'; + } else if (c == 'r') { + c = '\r'; + } else if (c == 't') { + c = '\t'; + } else if (c == 'f') { + c = '\f'; + } else if (c == '\b') { + c = '\b'; + } else if (c == '\"') { + c = '\"'; + } else if (c == '\'') { + c = '\''; + } else if (c == '\\') { + c = '\\'; + } + } + sbuf.append(c); } - } - sbuf.append(c); + return sbuf.toString(); } - return sbuf.toString(); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RestrictedEscapeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RestrictedEscapeUtil.java index 9bf933413cdc3c7dc9f612683502d27e997508e6..c440cf4ffef2ec09c1ac20347c02b73b0f0edae4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RestrictedEscapeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/pattern/util/RestrictedEscapeUtil.java @@ -20,18 +20,16 @@ package ch.qos.logback.core.pattern.util; */ public class RestrictedEscapeUtil implements IEscapeUtil { - public void escape(String escapeChars, StringBuffer buf, char next, - int pointer) { - if (escapeChars.indexOf(next) >= 0) { - buf.append(next); - } else { - // restitute the escape char (because it was consumed - // before this method was called). - buf.append("\\"); - // restitute the next character - buf.append(next); + public void escape(String escapeChars, StringBuffer buf, char next, int pointer) { + if (escapeChars.indexOf(next) >= 0) { + buf.append(next); + } else { + // restitute the escape char (because it was consumed + // before this method was called). + buf.append("\\"); + // restitute the next character + buf.append(next); + } } - } - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/property/FileExistsPropertyDefiner.java b/logback-core/src/main/java/ch/qos/logback/core/property/FileExistsPropertyDefiner.java index bdea325cc20cb6ed011f7b36661a2f04076b1cf4..0523f18e6b62a5a7c370af6a346571c71e11bf3e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/property/FileExistsPropertyDefiner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/property/FileExistsPropertyDefiner.java @@ -29,34 +29,34 @@ import java.io.File; */ public class FileExistsPropertyDefiner extends PropertyDefinerBase { - String path; - - public String getPath() { - return path; - } - - /** - * The path for the file to search for. - * - * @param path - */ - public void setPath(String path) { - this.path = path; - } - - /** - * Returns "true" if the file specified by {@link #setPath(String) path} property exists. - * Returns "false" otherwise. - * - * @return "true"|"false" depending on the existence of file - */ - public String getPropertyValue() { - if (OptionHelper.isEmpty(path)) { - addError("The \"path\" property must be set."); - return null; + String path; + + public String getPath() { + return path; + } + + /** + * The path for the file to search for. + * + * @param path + */ + public void setPath(String path) { + this.path = path; } - File file = new File(path); - return booleanAsStr(file.exists()); - } + /** + * Returns "true" if the file specified by {@link #setPath(String) path} property exists. + * Returns "false" otherwise. + * + * @return "true"|"false" depending on the existence of file + */ + public String getPropertyValue() { + if (OptionHelper.isEmpty(path)) { + addError("The \"path\" property must be set."); + return null; + } + + File file = new File(path); + return booleanAsStr(file.exists()); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/property/ResourceExistsPropertyDefiner.java b/logback-core/src/main/java/ch/qos/logback/core/property/ResourceExistsPropertyDefiner.java index b4f6bb6a64138a97df11a409b0c827119735cff5..4ba693c05ecfc31203fed02737b6243e07c630be 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/property/ResourceExistsPropertyDefiner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/property/ResourceExistsPropertyDefiner.java @@ -32,35 +32,35 @@ import java.net.URL; */ public class ResourceExistsPropertyDefiner extends PropertyDefinerBase { - String resourceStr; + String resourceStr; - public String getResource() { - return resourceStr; - } - - /** - * The resource to search for on the class path. - * - * @param resource - */ - public void setResource(String resource) { - this.resourceStr = resource; - } + public String getResource() { + return resourceStr; + } - /** - * Returns the string "true" if the {@link #setResource(String) resource} specified by the - * user is available on the class path, "false" otherwise. - * - * @return "true"|"false" depending on the availability of resource on the classpath - */ - public String getPropertyValue() { - if (OptionHelper.isEmpty(resourceStr)) { - addError("The \"resource\" property must be set."); - return null; + /** + * The resource to search for on the class path. + * + * @param resource + */ + public void setResource(String resource) { + this.resourceStr = resource; } - URL resourceURL = Loader.getResourceBySelfClassLoader(resourceStr); - return booleanAsStr(resourceURL != null); - } + /** + * Returns the string "true" if the {@link #setResource(String) resource} specified by the + * user is available on the class path, "false" otherwise. + * + * @return "true"|"false" depending on the availability of resource on the classpath + */ + public String getPropertyValue() { + if (OptionHelper.isEmpty(resourceStr)) { + addError("The \"resource\" property must be set."); + return null; + } + + URL resourceURL = Loader.getResourceBySelfClassLoader(resourceStr); + return booleanAsStr(resourceURL != null); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/read/CyclicBufferAppender.java b/logback-core/src/main/java/ch/qos/logback/core/read/CyclicBufferAppender.java index abfa4f6d034ec65c38d1970689942df2f3a71d6d..a500c99c5ceb052a13a7e9ae126fff3c3ea704ab 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/read/CyclicBufferAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/read/CyclicBufferAppender.java @@ -25,56 +25,56 @@ import ch.qos.logback.core.helpers.CyclicBuffer; */ public class CyclicBufferAppender extends AppenderBase { - CyclicBuffer cb; - int maxSize = 512; + CyclicBuffer cb; + int maxSize = 512; - public void start() { - cb = new CyclicBuffer(maxSize); - super.start(); - } + public void start() { + cb = new CyclicBuffer(maxSize); + super.start(); + } - public void stop() { - cb = null; - super.stop(); - } + public void stop() { + cb = null; + super.stop(); + } - @Override - protected void append(E eventObject) { - if (!isStarted()) { - return; + @Override + protected void append(E eventObject) { + if (!isStarted()) { + return; + } + cb.add(eventObject); } - cb.add(eventObject); - } - public int getLength() { - if (isStarted()) { - return cb.length(); - } else { - return 0; + public int getLength() { + if (isStarted()) { + return cb.length(); + } else { + return 0; + } } - } - public E get(int i) { - if (isStarted()) { - return cb.get(i); - } else { - return null; + public E get(int i) { + if (isStarted()) { + return cb.get(i); + } else { + return null; + } } - } - public void reset() { - cb.clear(); - } + public void reset() { + cb.clear(); + } - /** - * Set the size of the cyclic buffer. - */ - public int getMaxSize() { - return maxSize; - } + /** + * Set the size of the cyclic buffer. + */ + public int getMaxSize() { + return maxSize; + } - public void setMaxSize(int maxSize) { - this.maxSize = maxSize; - } + public void setMaxSize(int maxSize) { + this.maxSize = maxSize; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/read/ListAppender.java b/logback-core/src/main/java/ch/qos/logback/core/read/ListAppender.java index 2cef0c0776dfcf82707bb6ddc1e1e0169fa37f51..e8eabaa2b84e27454438264a827ee166bc365c9e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/read/ListAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/read/ListAppender.java @@ -20,9 +20,9 @@ import ch.qos.logback.core.AppenderBase; public class ListAppender extends AppenderBase { - public List list = new ArrayList(); - - protected void append(E e) { - list.add(e); - } + public List list = new ArrayList(); + + protected void append(E e) { + list.add(e); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/recovery/RecoveryCoordinator.java b/logback-core/src/main/java/ch/qos/logback/core/recovery/RecoveryCoordinator.java index 588812c3580de00cb31352181b7f114ccc42e02a..2c3c7655853deba8189aa3f6a1f474db4f70243f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/recovery/RecoveryCoordinator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/recovery/RecoveryCoordinator.java @@ -25,16 +25,16 @@ public class RecoveryCoordinator { // tests can set the time directly independently of system clock private long currentTime = UNSET; private long next; - + public RecoveryCoordinator() { next = getCurrentTime() + getBackoffCoefficient(); } - + public RecoveryCoordinator(long currentTime) { this.currentTime = currentTime; next = getCurrentTime() + getBackoffCoefficient(); } - + public boolean isTooSoon() { long now = getCurrentTime(); if (now > next) { diff --git a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientFileOutputStream.java b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientFileOutputStream.java index f5625265890a02d7bf85f01159f3afa958ccd017..f8369254dafaaa16ce5e4a458f267919539869c1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientFileOutputStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientFileOutputStream.java @@ -18,45 +18,42 @@ import java.nio.channels.FileChannel; public class ResilientFileOutputStream extends ResilientOutputStreamBase { - private File file; - private FileOutputStream fos; + private File file; + private FileOutputStream fos; + + public ResilientFileOutputStream(File file, boolean append) throws FileNotFoundException { + this.file = file; + fos = new FileOutputStream(file, append); + this.os = new BufferedOutputStream(fos); + this.presumedClean = true; + } + + public FileChannel getChannel() { + if (os == null) { + return null; + } + return fos.getChannel(); + } + public File getFile() { + return file; + } - public ResilientFileOutputStream(File file, boolean append) - throws FileNotFoundException { - this.file = file; - fos = new FileOutputStream(file, append); - this.os = new BufferedOutputStream(fos); - this.presumedClean = true; - } + @Override + String getDescription() { + return "file [" + file + "]"; + } + + @Override + OutputStream openNewOutputStream() throws IOException { + // see LOGBACK-765 + fos = new FileOutputStream(file, true); + return new BufferedOutputStream(fos); + } - public FileChannel getChannel() { - if (os == null) { - return null; + @Override + public String toString() { + return "c.q.l.c.recovery.ResilientFileOutputStream@" + System.identityHashCode(this); } - return fos.getChannel(); - } - - public File getFile() { - return file; - } - - @Override - String getDescription() { - return "file ["+file+"]"; - } - - @Override - OutputStream openNewOutputStream() throws IOException { - // see LOGBACK-765 - fos = new FileOutputStream(file, true); - return new BufferedOutputStream(fos); - } - - @Override - public String toString() { - return "c.q.l.c.recovery.ResilientFileOutputStream@" - + System.identityHashCode(this); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientOutputStreamBase.java b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientOutputStreamBase.java index f0d0df7854e1e0cd050fb007f2d0eb62153fade9..dd33046c627c8463359c245ee41110eab1c6676d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientOutputStreamBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientOutputStreamBase.java @@ -24,145 +24,140 @@ import ch.qos.logback.core.status.StatusManager; abstract public class ResilientOutputStreamBase extends OutputStream { - final static int STATUS_COUNT_LIMIT = 2 * 4; + final static int STATUS_COUNT_LIMIT = 2 * 4; - private int noContextWarning = 0; - private int statusCount = 0; + private int noContextWarning = 0; + private int statusCount = 0; - private Context context; - private RecoveryCoordinator recoveryCoordinator; + private Context context; + private RecoveryCoordinator recoveryCoordinator; - protected OutputStream os; - protected boolean presumedClean = true; + protected OutputStream os; + protected boolean presumedClean = true; - private boolean isPresumedInError() { - // existence of recoveryCoordinator indicates failed state - return (recoveryCoordinator != null && !presumedClean); - } - - public void write(byte b[], int off, int len) { - if (isPresumedInError()) { - if (!recoveryCoordinator.isTooSoon()) { - attemptRecovery(); - } - return; // return regardless of the success of the recovery attempt + private boolean isPresumedInError() { + // existence of recoveryCoordinator indicates failed state + return (recoveryCoordinator != null && !presumedClean); } - try { - os.write(b, off, len); - postSuccessfulWrite(); - } catch (IOException e) { - postIOFailure(e); - } - } - - @Override - public void write(int b) { - if (isPresumedInError()) { - if (!recoveryCoordinator.isTooSoon()) { - attemptRecovery(); - } - return; // return regardless of the success of the recovery attempt + public void write(byte b[], int off, int len) { + if (isPresumedInError()) { + if (!recoveryCoordinator.isTooSoon()) { + attemptRecovery(); + } + return; // return regardless of the success of the recovery attempt + } + + try { + os.write(b, off, len); + postSuccessfulWrite(); + } catch (IOException e) { + postIOFailure(e); + } } - try { - os.write(b); - postSuccessfulWrite(); - } catch (IOException e) { - postIOFailure(e); + + @Override + public void write(int b) { + if (isPresumedInError()) { + if (!recoveryCoordinator.isTooSoon()) { + attemptRecovery(); + } + return; // return regardless of the success of the recovery attempt + } + try { + os.write(b); + postSuccessfulWrite(); + } catch (IOException e) { + postIOFailure(e); + } } - } - - @Override - public void flush() { - if (os != null) { - try { - os.flush(); - postSuccessfulWrite(); - } catch (IOException e) { - postIOFailure(e); - } + + @Override + public void flush() { + if (os != null) { + try { + os.flush(); + postSuccessfulWrite(); + } catch (IOException e) { + postIOFailure(e); + } + } } - } - abstract String getDescription(); + abstract String getDescription(); - abstract OutputStream openNewOutputStream() throws IOException; + abstract OutputStream openNewOutputStream() throws IOException; - private void postSuccessfulWrite() { - if (recoveryCoordinator != null) { - recoveryCoordinator = null; - statusCount = 0; - addStatus(new InfoStatus("Recovered from IO failure on " - + getDescription(), this)); + private void postSuccessfulWrite() { + if (recoveryCoordinator != null) { + recoveryCoordinator = null; + statusCount = 0; + addStatus(new InfoStatus("Recovered from IO failure on " + getDescription(), this)); + } } - } - - public void postIOFailure(IOException e) { - addStatusIfCountNotOverLimit(new ErrorStatus("IO failure while writing to " - + getDescription(), this, e)); - presumedClean = false; - if (recoveryCoordinator == null) { - recoveryCoordinator = new RecoveryCoordinator(); + + public void postIOFailure(IOException e) { + addStatusIfCountNotOverLimit(new ErrorStatus("IO failure while writing to " + getDescription(), this, e)); + presumedClean = false; + if (recoveryCoordinator == null) { + recoveryCoordinator = new RecoveryCoordinator(); + } } - } - @Override - public void close() throws IOException { - if (os != null) { - os.close(); + @Override + public void close() throws IOException { + if (os != null) { + os.close(); + } } - } - void attemptRecovery() { - try { - close(); - } catch (IOException e) { + void attemptRecovery() { + try { + close(); + } catch (IOException e) { + } + + addStatusIfCountNotOverLimit(new InfoStatus("Attempting to recover from IO failure on " + getDescription(), this)); + + // subsequent writes must always be in append mode + try { + os = openNewOutputStream(); + presumedClean = true; + } catch (IOException e) { + addStatusIfCountNotOverLimit(new ErrorStatus("Failed to open " + getDescription(), this, e)); + } } - addStatusIfCountNotOverLimit(new InfoStatus( - "Attempting to recover from IO failure on " + getDescription(), this)); + void addStatusIfCountNotOverLimit(Status s) { + ++statusCount; + if (statusCount < STATUS_COUNT_LIMIT) { + addStatus(s); + } - // subsequent writes must always be in append mode - try { - os = openNewOutputStream(); - presumedClean = true; - } catch (IOException e) { - addStatusIfCountNotOverLimit(new ErrorStatus("Failed to open " - + getDescription(), this, e)); + if (statusCount == STATUS_COUNT_LIMIT) { + addStatus(s); + addStatus(new InfoStatus("Will supress future messages regarding " + getDescription(), this)); + } } - } - void addStatusIfCountNotOverLimit(Status s) { - ++statusCount; - if (statusCount < STATUS_COUNT_LIMIT) { - addStatus(s); + public void addStatus(Status status) { + if (context == null) { + if (noContextWarning++ == 0) { + System.out.println("LOGBACK: No context given for " + this); + } + return; + } + StatusManager sm = context.getStatusManager(); + if (sm != null) { + sm.add(status); + } } - if (statusCount == STATUS_COUNT_LIMIT) { - addStatus(s); - addStatus(new InfoStatus("Will supress future messages regarding " - + getDescription(), this)); + public Context getContext() { + return context; } - } - - public void addStatus(Status status) { - if (context == null) { - if (noContextWarning++ == 0) { - System.out.println("LOGBACK: No context given for " + this); - } - return; - } - StatusManager sm = context.getStatusManager(); - if (sm != null) { - sm.add(status); - } - } - public Context getContext() { - return context; - } - - public void setContext(Context context) { - this.context = context; - } + public void setContext(Context context) { + this.context = context; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientSyslogOutputStream.java b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientSyslogOutputStream.java index 73ac8448d00743376ada8d1a39b993c29ffd54c0..064a484f90297cde29f03c7f7178b40d3489454a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientSyslogOutputStream.java +++ b/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientSyslogOutputStream.java @@ -22,32 +22,29 @@ import ch.qos.logback.core.net.SyslogOutputStream; public class ResilientSyslogOutputStream extends ResilientOutputStreamBase { - - String syslogHost; - int port; - - public ResilientSyslogOutputStream(String syslogHost, int port) - throws UnknownHostException, SocketException { - this.syslogHost = syslogHost; - this.port = port; - super.os = new SyslogOutputStream(syslogHost, port); - this.presumedClean = true; - } - - @Override - String getDescription() { - return "syslog ["+syslogHost+":"+port+"]"; - } - - @Override - OutputStream openNewOutputStream() throws IOException { - return new SyslogOutputStream(syslogHost, port); - } - - @Override - public String toString() { - return "c.q.l.c.recovery.ResilientSyslogOutputStream@" - + System.identityHashCode(this); - } + String syslogHost; + int port; + + public ResilientSyslogOutputStream(String syslogHost, int port) throws UnknownHostException, SocketException { + this.syslogHost = syslogHost; + this.port = port; + super.os = new SyslogOutputStream(syslogHost, port); + this.presumedClean = true; + } + + @Override + String getDescription() { + return "syslog [" + syslogHost + ":" + port + "]"; + } + + @Override + OutputStream openNewOutputStream() throws IOException { + return new SyslogOutputStream(syslogHost, port); + } + + @Override + public String toString() { + return "c.q.l.c.recovery.ResilientSyslogOutputStream@" + System.identityHashCode(this); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/DefaultTimeBasedFileNamingAndTriggeringPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/DefaultTimeBasedFileNamingAndTriggeringPolicy.java index 560b6877eceb8becc38571cc49e24217f28084e8..131d3bf41b695598e7ce807af20ab92f0bb11e6e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/DefaultTimeBasedFileNamingAndTriggeringPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/DefaultTimeBasedFileNamingAndTriggeringPolicy.java @@ -26,33 +26,32 @@ import ch.qos.logback.core.rolling.helper.TimeBasedArchiveRemover; */ public class DefaultTimeBasedFileNamingAndTriggeringPolicy extends TimeBasedFileNamingAndTriggeringPolicyBase { - @Override - public void start() { - super.start(); - if(!super.isErrorFree()) - return; - archiveRemover = new TimeBasedArchiveRemover(tbrp.fileNamePattern, rc); - archiveRemover.setContext(context); - started = true; - } + @Override + public void start() { + super.start(); + if (!super.isErrorFree()) + return; + archiveRemover = new TimeBasedArchiveRemover(tbrp.fileNamePattern, rc); + archiveRemover.setContext(context); + started = true; + } - public boolean isTriggeringEvent(File activeFile, final E event) { - long time = getCurrentTime(); - if (time >= nextCheck) { - Date dateOfElapsedPeriod = dateInCurrentPeriod; - addInfo("Elapsed period: "+dateOfElapsedPeriod); - elapsedPeriodsFileName = tbrp.fileNamePatternWCS - .convert(dateOfElapsedPeriod); - setDateInCurrentPeriod(time); - computeNextCheck(); - return true; - } else { - return false; + public boolean isTriggeringEvent(File activeFile, final E event) { + long time = getCurrentTime(); + if (time >= nextCheck) { + Date dateOfElapsedPeriod = dateInCurrentPeriod; + addInfo("Elapsed period: " + dateOfElapsedPeriod); + elapsedPeriodsFileName = tbrp.fileNamePatternWCS.convert(dateOfElapsedPeriod); + setDateInCurrentPeriod(time); + computeNextCheck(); + return true; + } else { + return false; + } } - } - @Override - public String toString() { - return "c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy"; - } + @Override + public String toString() { + return "c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.java index efdb83e77b42c83972bc2344d8b7813f1f92552b..da3340426cde7feffee2ab00ad2344cf74e1aead 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/FixedWindowRollingPolicy.java @@ -29,157 +29,153 @@ import ch.qos.logback.core.rolling.helper.*; * @author Ceki Gülcü */ public class FixedWindowRollingPolicy extends RollingPolicyBase { - static final String FNP_NOT_SET = "The \"FileNamePattern\" property must be set before using FixedWindowRollingPolicy. "; - static final String PRUDENT_MODE_UNSUPPORTED = "See also http://logback.qos.ch/codes.html#tbr_fnp_prudent_unsupported"; - static final String SEE_PARENT_FN_NOT_SET = "Please refer to http://logback.qos.ch/codes.html#fwrp_parentFileName_not_set"; - int maxIndex; - int minIndex; - RenameUtil util = new RenameUtil(); - Compressor compressor; - - public static final String ZIP_ENTRY_DATE_PATTERN = "yyyy-MM-dd_HHmm"; - - /** - * It's almost always a bad idea to have a large window size, say over 20. - */ - private static int MAX_WINDOW_SIZE = 20; - - public FixedWindowRollingPolicy() { - minIndex = 1; - maxIndex = 7; - } - - public void start() { - util.setContext(this.context); - - if (fileNamePatternStr != null) { - fileNamePattern = new FileNamePattern(fileNamePatternStr, this.context); - determineCompressionMode(); - } else { - addError(FNP_NOT_SET); - addError(CoreConstants.SEE_FNP_NOT_SET); - throw new IllegalStateException(FNP_NOT_SET + CoreConstants.SEE_FNP_NOT_SET); + static final String FNP_NOT_SET = "The \"FileNamePattern\" property must be set before using FixedWindowRollingPolicy. "; + static final String PRUDENT_MODE_UNSUPPORTED = "See also http://logback.qos.ch/codes.html#tbr_fnp_prudent_unsupported"; + static final String SEE_PARENT_FN_NOT_SET = "Please refer to http://logback.qos.ch/codes.html#fwrp_parentFileName_not_set"; + int maxIndex; + int minIndex; + RenameUtil util = new RenameUtil(); + Compressor compressor; + + public static final String ZIP_ENTRY_DATE_PATTERN = "yyyy-MM-dd_HHmm"; + + /** + * It's almost always a bad idea to have a large window size, say over 20. + */ + private static int MAX_WINDOW_SIZE = 20; + + public FixedWindowRollingPolicy() { + minIndex = 1; + maxIndex = 7; } - if(isParentPrudent()) { - addError("Prudent mode is not supported with FixedWindowRollingPolicy."); - addError(PRUDENT_MODE_UNSUPPORTED); - throw new IllegalStateException("Prudent mode is not supported."); + public void start() { + util.setContext(this.context); + + if (fileNamePatternStr != null) { + fileNamePattern = new FileNamePattern(fileNamePatternStr, this.context); + determineCompressionMode(); + } else { + addError(FNP_NOT_SET); + addError(CoreConstants.SEE_FNP_NOT_SET); + throw new IllegalStateException(FNP_NOT_SET + CoreConstants.SEE_FNP_NOT_SET); + } + + if (isParentPrudent()) { + addError("Prudent mode is not supported with FixedWindowRollingPolicy."); + addError(PRUDENT_MODE_UNSUPPORTED); + throw new IllegalStateException("Prudent mode is not supported."); + } + + if (getParentsRawFileProperty() == null) { + addError("The File name property must be set before using this rolling policy."); + addError(SEE_PARENT_FN_NOT_SET); + throw new IllegalStateException("The \"File\" option must be set."); + } + + if (maxIndex < minIndex) { + addWarn("MaxIndex (" + maxIndex + ") cannot be smaller than MinIndex (" + minIndex + ")."); + addWarn("Setting maxIndex to equal minIndex."); + maxIndex = minIndex; + } + + final int maxWindowSize = getMaxWindowSize(); + if ((maxIndex - minIndex) > maxWindowSize) { + addWarn("Large window sizes are not allowed."); + maxIndex = minIndex + maxWindowSize; + addWarn("MaxIndex reduced to " + maxIndex); + } + + IntegerTokenConverter itc = fileNamePattern.getIntegerTokenConverter(); + + if (itc == null) { + throw new IllegalStateException("FileNamePattern [" + fileNamePattern.getPattern() + "] does not contain a valid IntegerToken"); + } + + if (compressionMode == CompressionMode.ZIP) { + String zipEntryFileNamePatternStr = transformFileNamePatternFromInt2Date(fileNamePatternStr); + zipEntryFileNamePattern = new FileNamePattern(zipEntryFileNamePatternStr, context); + } + compressor = new Compressor(compressionMode); + compressor.setContext(this.context); + super.start(); + } + + /** + * Subclasses can override this method to increase the max window size, if required. This is to + * address LOGBACK-266. + * @return + */ + protected int getMaxWindowSize() { + return MAX_WINDOW_SIZE; } - - if (getParentsRawFileProperty() == null) { - addError("The File name property must be set before using this rolling policy."); - addError(SEE_PARENT_FN_NOT_SET); - throw new IllegalStateException("The \"File\" option must be set."); + + private String transformFileNamePatternFromInt2Date(String fileNamePatternStr) { + String slashified = FileFilterUtil.slashify(fileNamePatternStr); + String stemOfFileNamePattern = FileFilterUtil.afterLastSlash(slashified); + return stemOfFileNamePattern.replace("%i", "%d{" + ZIP_ENTRY_DATE_PATTERN + "}"); } - if (maxIndex < minIndex) { - addWarn("MaxIndex (" + maxIndex + ") cannot be smaller than MinIndex (" - + minIndex + ")."); - addWarn("Setting maxIndex to equal minIndex."); - maxIndex = minIndex; + public void rollover() throws RolloverFailure { + + // Inside this method it is guaranteed that the hereto active log file is + // closed. + // If maxIndex <= 0, then there is no file renaming to be done. + if (maxIndex >= 0) { + // Delete the oldest file, to keep Windows happy. + File file = new File(fileNamePattern.convertInt(maxIndex)); + + if (file.exists()) { + file.delete(); + } + + // Map {(maxIndex - 1), ..., minIndex} to {maxIndex, ..., minIndex+1} + for (int i = maxIndex - 1; i >= minIndex; i--) { + String toRenameStr = fileNamePattern.convertInt(i); + File toRename = new File(toRenameStr); + // no point in trying to rename an inexistent file + if (toRename.exists()) { + util.rename(toRenameStr, fileNamePattern.convertInt(i + 1)); + } else { + addInfo("Skipping roll-over for inexistent file " + toRenameStr); + } + } + + // move active file name to min + switch (compressionMode) { + case NONE: + util.rename(getActiveFileName(), fileNamePattern.convertInt(minIndex)); + break; + case GZ: + compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex), null); + break; + case ZIP: + compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex), zipEntryFileNamePattern.convert(new Date())); + break; + } + } } - final int maxWindowSize = getMaxWindowSize(); - if ((maxIndex - minIndex) > maxWindowSize) { - addWarn("Large window sizes are not allowed."); - maxIndex = minIndex + maxWindowSize; - addWarn("MaxIndex reduced to " + maxIndex); + /** + * Return the value of the parent's RawFile property. + */ + public String getActiveFileName() { + return getParentsRawFileProperty(); } - IntegerTokenConverter itc = fileNamePattern.getIntegerTokenConverter(); + public int getMaxIndex() { + return maxIndex; + } - if (itc == null) { - throw new IllegalStateException("FileNamePattern [" - + fileNamePattern.getPattern() - + "] does not contain a valid IntegerToken"); + public int getMinIndex() { + return minIndex; } - if(compressionMode == CompressionMode.ZIP) { - String zipEntryFileNamePatternStr = transformFileNamePatternFromInt2Date(fileNamePatternStr); - zipEntryFileNamePattern = new FileNamePattern(zipEntryFileNamePatternStr, context); + public void setMaxIndex(int maxIndex) { + this.maxIndex = maxIndex; } - compressor = new Compressor(compressionMode); - compressor.setContext(this.context); - super.start(); - } - - /** - * Subclasses can override this method to increase the max window size, if required. This is to - * address LOGBACK-266. - * @return - */ - protected int getMaxWindowSize() { - return MAX_WINDOW_SIZE; - } - - private String transformFileNamePatternFromInt2Date(String fileNamePatternStr) { - String slashified = FileFilterUtil.slashify(fileNamePatternStr); - String stemOfFileNamePattern = FileFilterUtil.afterLastSlash(slashified); - return stemOfFileNamePattern.replace("%i", "%d{"+ZIP_ENTRY_DATE_PATTERN+"}"); - } - - public void rollover() throws RolloverFailure { - - // Inside this method it is guaranteed that the hereto active log file is - // closed. - // If maxIndex <= 0, then there is no file renaming to be done. - if (maxIndex >= 0) { - // Delete the oldest file, to keep Windows happy. - File file = new File(fileNamePattern.convertInt(maxIndex)); - - if (file.exists()) { - file.delete(); - } - - // Map {(maxIndex - 1), ..., minIndex} to {maxIndex, ..., minIndex+1} - for (int i = maxIndex - 1; i >= minIndex; i--) { - String toRenameStr = fileNamePattern.convertInt(i); - File toRename = new File(toRenameStr); - // no point in trying to rename an inexistent file - if (toRename.exists()) { - util.rename(toRenameStr, fileNamePattern.convertInt(i + 1)); - } else { - addInfo("Skipping roll-over for inexistent file " + toRenameStr); - } - } - - // move active file name to min - switch (compressionMode) { - case NONE: - util.rename(getActiveFileName(), fileNamePattern - .convertInt(minIndex)); - break; - case GZ: - compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex), null); - break; - case ZIP: - compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex), zipEntryFileNamePattern.convert(new Date())); - break; - } + + public void setMinIndex(int minIndex) { + this.minIndex = minIndex; } - } - - /** - * Return the value of the parent's RawFile property. - */ - public String getActiveFileName() { - return getParentsRawFileProperty(); - } - - public int getMaxIndex() { - return maxIndex; - } - - public int getMinIndex() { - return minIndex; - } - - public void setMaxIndex(int maxIndex) { - this.maxIndex = maxIndex; - } - - public void setMinIndex(int minIndex) { - this.minIndex = minIndex; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicy.java index 4ade489bdb1c8e1a123687a65e27d23c21cf0877..e2daf388d01513410e2b4f69b0208bfa5d2eb87b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicy.java @@ -27,41 +27,41 @@ import ch.qos.logback.core.spi.LifeCycle; */ public interface RollingPolicy extends LifeCycle { - /** - * Rolls over log files according to implementation policy. - * - *

This method is invoked by {@link RollingFileAppender}, usually at the - * behest of its {@link TriggeringPolicy}. - * - * @throws RolloverFailure - * Thrown if the rollover operation fails for any reason. - */ - void rollover() throws RolloverFailure; + /** + * Rolls over log files according to implementation policy. + * + *

This method is invoked by {@link RollingFileAppender}, usually at the + * behest of its {@link TriggeringPolicy}. + * + * @throws RolloverFailure + * Thrown if the rollover operation fails for any reason. + */ + void rollover() throws RolloverFailure; - /** - * Get the name of the active log file. - * - *

With implementations such as {@link TimeBasedRollingPolicy}, this - * method returns a new file name, where the actual output will be sent. - * - *

On other implementations, this method might return the FileAppender's - * file property. - */ - String getActiveFileName(); + /** + * Get the name of the active log file. + * + *

With implementations such as {@link TimeBasedRollingPolicy}, this + * method returns a new file name, where the actual output will be sent. + * + *

On other implementations, this method might return the FileAppender's + * file property. + */ + String getActiveFileName(); - /** - * The compression mode for this policy. - * - * @return - */ - CompressionMode getCompressionMode(); - - /** - * This method allows RollingPolicy implementations to be aware of their - * containing appender. - * - * @param appender - */ + /** + * The compression mode for this policy. + * + * @return + */ + CompressionMode getCompressionMode(); - void setParent(FileAppender appender); + /** + * This method allows RollingPolicy implementations to be aware of their + * containing appender. + * + * @param appender + */ + + void setParent(FileAppender appender); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicyBase.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicyBase.java index 39d83b6982cea5e5d482db37ff8809ae889a39c0..5cedb0feffe059227eb55648f92f94b0c12652d7 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicyBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/RollingPolicyBase.java @@ -25,71 +25,71 @@ import ch.qos.logback.core.spi.ContextAwareBase; * @author Ceki Gülcü */ public abstract class RollingPolicyBase extends ContextAwareBase implements RollingPolicy { - protected CompressionMode compressionMode = CompressionMode.NONE; + protected CompressionMode compressionMode = CompressionMode.NONE; - FileNamePattern fileNamePattern; - // fileNamePatternStr is always slashified, see setter - protected String fileNamePatternStr; + FileNamePattern fileNamePattern; + // fileNamePatternStr is always slashified, see setter + protected String fileNamePatternStr; - private FileAppender parent; + private FileAppender parent; - // use to name files within zip file, i.e. the zipEntry - FileNamePattern zipEntryFileNamePattern; - private boolean started; + // use to name files within zip file, i.e. the zipEntry + FileNamePattern zipEntryFileNamePattern; + private boolean started; - /** - * Given the FileNamePattern string, this method determines the compression - * mode depending on last letters of the fileNamePatternStr. Patterns ending - * with .gz imply GZIP compression, endings with '.zip' imply ZIP compression. - * Otherwise and by default, there is no compression. - * - */ - protected void determineCompressionMode() { - if (fileNamePatternStr.endsWith(".gz")) { - addInfo("Will use gz compression"); - compressionMode = CompressionMode.GZ; - } else if (fileNamePatternStr.endsWith(".zip")) { - addInfo("Will use zip compression"); - compressionMode = CompressionMode.ZIP; - } else { - addInfo("No compression will be used"); - compressionMode = CompressionMode.NONE; + /** + * Given the FileNamePattern string, this method determines the compression + * mode depending on last letters of the fileNamePatternStr. Patterns ending + * with .gz imply GZIP compression, endings with '.zip' imply ZIP compression. + * Otherwise and by default, there is no compression. + * + */ + protected void determineCompressionMode() { + if (fileNamePatternStr.endsWith(".gz")) { + addInfo("Will use gz compression"); + compressionMode = CompressionMode.GZ; + } else if (fileNamePatternStr.endsWith(".zip")) { + addInfo("Will use zip compression"); + compressionMode = CompressionMode.ZIP; + } else { + addInfo("No compression will be used"); + compressionMode = CompressionMode.NONE; + } } - } - public void setFileNamePattern(String fnp) { - fileNamePatternStr = fnp; - } + public void setFileNamePattern(String fnp) { + fileNamePatternStr = fnp; + } - public String getFileNamePattern() { - return fileNamePatternStr; - } + public String getFileNamePattern() { + return fileNamePatternStr; + } - public CompressionMode getCompressionMode() { - return compressionMode; - } + public CompressionMode getCompressionMode() { + return compressionMode; + } - public boolean isStarted() { - return started; - } + public boolean isStarted() { + return started; + } - public void start() { - started = true; - } + public void start() { + started = true; + } - public void stop() { - started = false; - } + public void stop() { + started = false; + } - public void setParent(FileAppender appender) { - this.parent = appender; - } + public void setParent(FileAppender appender) { + this.parent = appender; + } - public boolean isParentPrudent() { - return parent.isPrudent(); - } + public boolean isParentPrudent() { + return parent.isPrudent(); + } - public String getParentsRawFileProperty() { - return parent.rawFileProperty(); - } + public String getParentsRawFileProperty() { + return parent.rawFileProperty(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/RolloverFailure.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/RolloverFailure.java index 86c3767ffdeb65600fa5fb7b6f56dded009f01e2..4086b3f4c763be7168a8c4930eae8dbdeb8adf42 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/RolloverFailure.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/RolloverFailure.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.rolling; - import ch.qos.logback.core.LogbackException; /** @@ -23,13 +22,13 @@ import ch.qos.logback.core.LogbackException; */ public class RolloverFailure extends LogbackException { - private static final long serialVersionUID = -4407533730831239458L; + private static final long serialVersionUID = -4407533730831239458L; - public RolloverFailure(String msg) { - super(msg); - } + public RolloverFailure(String msg) { + super(msg); + } - public RolloverFailure(String message, Throwable cause) { - super(message, cause); - } + public RolloverFailure(String message, Throwable cause) { + super(message, cause); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP.java index bad1b5eebfc1c40a7c49342545897911de198177..e15935e72b56b3db20963b6c30c63c59e706b95f 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP.java @@ -33,20 +33,20 @@ public class SizeAndTimeBasedFNATP extends TimeBasedFileNamingAndTriggeringPo static String MISSING_INT_TOKEN = "Missing integer token, that is %i, in FileNamePattern ["; static String MISSING_DATE_TOKEN = "Missing date token, that is %d, in FileNamePattern ["; - + @Override public void start() { // we depend on certain fields having been initialized in super class super.start(); - if(!super.isErrorFree()) + if (!super.isErrorFree()) return; - + if (!validDateAndIntegerTokens()) { started = false; return; } - + archiveRemover = createArchiveRemover(); archiveRemover.setContext(context); @@ -63,16 +63,16 @@ public class SizeAndTimeBasedFNATP extends TimeBasedFileNamingAndTriggeringPo private boolean validDateAndIntegerTokens() { boolean inError = false; - if(tbrp.fileNamePattern.getIntegerTokenConverter() == null) { + if (tbrp.fileNamePattern.getIntegerTokenConverter() == null) { inError = true; - addError(MISSING_INT_TOKEN+tbrp.fileNamePatternStr+"]"); + addError(MISSING_INT_TOKEN + tbrp.fileNamePatternStr + "]"); addError(CoreConstants.SEE_MISSING_INTEGER_TOKEN); } - if(tbrp.fileNamePattern.getPrimaryDateTokenConverter() == null) { + if (tbrp.fileNamePattern.getPrimaryDateTokenConverter() == null) { inError = true; - addError(MISSING_DATE_TOKEN+tbrp.fileNamePatternStr+"]"); + addError(MISSING_DATE_TOKEN + tbrp.fileNamePatternStr + "]"); } - + return !inError; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.java index 6c869de85eb71b5f8066056d40788474f87230a4..d1bca99a4743efe77d8617cb0b46e2e377f64a10 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicy.java @@ -31,70 +31,69 @@ import ch.qos.logback.core.util.InvocationGate; */ public class SizeBasedTriggeringPolicy extends TriggeringPolicyBase { - public static final String SEE_SIZE_FORMAT = "http://logback.qos.ch/codes.html#sbtp_size_format"; - /** - * The default maximum file size. - */ - public static final long DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB - - String maxFileSizeAsString = Long.toString(DEFAULT_MAX_FILE_SIZE); - FileSize maxFileSize; - - public SizeBasedTriggeringPolicy() { - } - - public SizeBasedTriggeringPolicy(final String maxFileSize) { - setMaxFileSize(maxFileSize); - } - - private InvocationGate invocationGate = new InvocationGate(); - - public boolean isTriggeringEvent(final File activeFile, final E event) { - if(invocationGate.skipFurtherWork()) - return false; - - long now = System.currentTimeMillis(); - invocationGate.updateMaskIfNecessary(now); - - return (activeFile.length() >= maxFileSize.getSize()); - } - - public String getMaxFileSize() { - return maxFileSizeAsString; - } - - public void setMaxFileSize(String maxFileSize) { - this.maxFileSizeAsString = maxFileSize; - this.maxFileSize = FileSize.valueOf(maxFileSize); - } - - long toFileSize(String value) { - if (value == null) - return DEFAULT_MAX_FILE_SIZE; - - String s = value.trim().toUpperCase(); - long multiplier = 1; - int index; - - if ((index = s.indexOf("KB")) != -1) { - multiplier = 1024; - s = s.substring(0, index); - } else if ((index = s.indexOf("MB")) != -1) { - multiplier = 1024 * 1024; - s = s.substring(0, index); - } else if ((index = s.indexOf("GB")) != -1) { - multiplier = 1024 * 1024 * 1024; - s = s.substring(0, index); + public static final String SEE_SIZE_FORMAT = "http://logback.qos.ch/codes.html#sbtp_size_format"; + /** + * The default maximum file size. + */ + public static final long DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB + + String maxFileSizeAsString = Long.toString(DEFAULT_MAX_FILE_SIZE); + FileSize maxFileSize; + + public SizeBasedTriggeringPolicy() { + } + + public SizeBasedTriggeringPolicy(final String maxFileSize) { + setMaxFileSize(maxFileSize); + } + + private InvocationGate invocationGate = new InvocationGate(); + + public boolean isTriggeringEvent(final File activeFile, final E event) { + if (invocationGate.skipFurtherWork()) + return false; + + long now = System.currentTimeMillis(); + invocationGate.updateMaskIfNecessary(now); + + return (activeFile.length() >= maxFileSize.getSize()); + } + + public String getMaxFileSize() { + return maxFileSizeAsString; } - if (s != null) { - try { - return Long.valueOf(s).longValue() * multiplier; - } catch (NumberFormatException e) { - addError("[" + s + "] is not in proper int format. Please refer to " - + SEE_SIZE_FORMAT); - addError("[" + value + "] not in expected format.", e); - } + + public void setMaxFileSize(String maxFileSize) { + this.maxFileSizeAsString = maxFileSize; + this.maxFileSize = FileSize.valueOf(maxFileSize); + } + + long toFileSize(String value) { + if (value == null) + return DEFAULT_MAX_FILE_SIZE; + + String s = value.trim().toUpperCase(); + long multiplier = 1; + int index; + + if ((index = s.indexOf("KB")) != -1) { + multiplier = 1024; + s = s.substring(0, index); + } else if ((index = s.indexOf("MB")) != -1) { + multiplier = 1024 * 1024; + s = s.substring(0, index); + } else if ((index = s.indexOf("GB")) != -1) { + multiplier = 1024 * 1024 * 1024; + s = s.substring(0, index); + } + if (s != null) { + try { + return Long.valueOf(s).longValue() * multiplier; + } catch (NumberFormatException e) { + addError("[" + s + "] is not in proper int format. Please refer to " + SEE_SIZE_FORMAT); + addError("[" + value + "] not in expected format.", e); + } + } + return DEFAULT_MAX_FILE_SIZE; } - return DEFAULT_MAX_FILE_SIZE; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicy.java index 945dcef0794acee77cabc76f43f96faf5bffc730..ae2724524e7f3801162c787295cfeb5c48201419 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicy.java @@ -26,58 +26,58 @@ import ch.qos.logback.core.spi.ContextAware; */ public interface TimeBasedFileNamingAndTriggeringPolicy extends TriggeringPolicy, ContextAware { - /** - * Set the host/parent {@link TimeBasedRollingPolicy}. - * - * @param tbrp - * parent TimeBasedRollingPolicy - */ - void setTimeBasedRollingPolicy(TimeBasedRollingPolicy tbrp); + /** + * Set the host/parent {@link TimeBasedRollingPolicy}. + * + * @param tbrp + * parent TimeBasedRollingPolicy + */ + void setTimeBasedRollingPolicy(TimeBasedRollingPolicy tbrp); - /** - * Return the file name for the elapsed periods file name. - * - * @return - */ - String getElapsedPeriodsFileName(); + /** + * Return the file name for the elapsed periods file name. + * + * @return + */ + String getElapsedPeriodsFileName(); - /** - * Return the current periods file name without the compression suffix. This - * value is equivalent to the active file name. - * - * @return current period's file name (without compression suffix) - */ - String getCurrentPeriodsFileNameWithoutCompressionSuffix(); + /** + * Return the current periods file name without the compression suffix. This + * value is equivalent to the active file name. + * + * @return current period's file name (without compression suffix) + */ + String getCurrentPeriodsFileNameWithoutCompressionSuffix(); - /** - * Return the archive remover appropriate for this instance. - */ - ArchiveRemover getArchiveRemover(); - - /** - * Return the current time which is usually the value returned by - * System.currentMillis(). However, for testing purposed this value - * may be different than the real time. - * - * @return current time value - */ - long getCurrentTime(); + /** + * Return the archive remover appropriate for this instance. + */ + ArchiveRemover getArchiveRemover(); - /** - * Set the current time. Only unit tests should invoke this method. - * - * @param now - */ - void setCurrentTime(long now); + /** + * Return the current time which is usually the value returned by + * System.currentMillis(). However, for testing purposed this value + * may be different than the real time. + * + * @return current time value + */ + long getCurrentTime(); - /** - * Set some date in the current period. Only unit tests should invoke this - * method. - * - * WARNING: method removed. A unit test should not set the - * date in current period. It is the job of the FNATP to compute that. - * - * @param date - */ - //void setDateInCurrentPeriod(Date date); + /** + * Set the current time. Only unit tests should invoke this method. + * + * @param now + */ + void setCurrentTime(long now); + + /** + * Set some date in the current period. Only unit tests should invoke this + * method. + * + * WARNING: method removed. A unit test should not set the + * date in current period. It is the job of the FNATP to compute that. + * + * @param date + */ + // void setDateInCurrentPeriod(Date date); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBase.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBase.java index 31a9d44cf1794e8e63dec07f73684a9608bdaf34..65f01c179cc0a0e25ef5695e8bc882374d208c7e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBase.java @@ -28,7 +28,7 @@ import ch.qos.logback.core.spi.ContextAwareBase; abstract public class TimeBasedFileNamingAndTriggeringPolicyBase extends ContextAwareBase implements TimeBasedFileNamingAndTriggeringPolicy { static private String COLLIDING_DATE_FORMAT_URL = CODES_URL + "#rfa_collision_in_dateFormat"; - + protected TimeBasedRollingPolicy tbrp; protected ArchiveRemover archiveRemover = null; @@ -41,7 +41,7 @@ abstract public class TimeBasedFileNamingAndTriggeringPolicyBase extends Cont protected long nextCheck; protected boolean started = false; protected boolean errorFree = true; - + public boolean isStarted() { return started; } @@ -59,14 +59,14 @@ abstract public class TimeBasedFileNamingAndTriggeringPolicyBase extends Cont } addInfo("The date pattern is '" + dtc.getDatePattern() + "' from file name pattern '" + tbrp.fileNamePattern.getPattern() + "'."); rc.printPeriodicity(this); - - if(!rc.isCollisionFree()) { + + if (!rc.isCollisionFree()) { addError("The date format in FileNamePattern will result in collisions in the names of archived log files."); - addError(CoreConstants.MORE_INFO_PREFIX+COLLIDING_DATE_FORMAT_URL); + addError(CoreConstants.MORE_INFO_PREFIX + COLLIDING_DATE_FORMAT_URL); errorFree = false; return; } - + setDateInCurrentPeriod(new Date(getCurrentTime())); if (tbrp.getParentsRawFileProperty() != null) { File currentFile = new File(tbrp.getParentsRawFileProperty()); diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.java index 6073e790d750f1d41532009d8143fae82de99feb..cc6ba51ab0d98ddb299491d76368ce9e65226910 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/TimeBasedRollingPolicy.java @@ -90,7 +90,7 @@ public class TimeBasedRollingPolicy extends RollingPolicyBase implements Trig timeBasedFileNamingAndTriggeringPolicy.setTimeBasedRollingPolicy(this); timeBasedFileNamingAndTriggeringPolicy.start(); - if(!timeBasedFileNamingAndTriggeringPolicy.isStarted()) { + if (!timeBasedFileNamingAndTriggeringPolicy.isStarted()) { addWarn("Subcomponent did not start. TimeBasedRollingPolicy will not start."); return; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicy.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicy.java index a8595cffaddc5f3241196dce801a6f506ec680e3..ba24604f802fa54ee22eae9a9b6cfe9e844ddbac 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicy.java @@ -17,7 +17,6 @@ import java.io.File; import ch.qos.logback.core.spi.LifeCycle; - /** * A TriggeringPolicy controls the conditions under which roll-over * occurs. Such conditions include time of day, file size, an @@ -27,13 +26,13 @@ import ch.qos.logback.core.spi.LifeCycle; * */ public interface TriggeringPolicy extends LifeCycle { - - /** - * Should roll-over be triggered at this time? - * - * @param activeFile A reference to the currently active log file. - * @param event A reference to the currently event. - * @return true if a roll-over should occur. - */ - boolean isTriggeringEvent(final File activeFile, final E event); + + /** + * Should roll-over be triggered at this time? + * + * @param activeFile A reference to the currently active log file. + * @param event A reference to the currently event. + * @return true if a roll-over should occur. + */ + boolean isTriggeringEvent(final File activeFile, final E event); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicyBase.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicyBase.java index c4c8fb9ede1e9dfef2974e7603eb4e96c8b9497f..852a6061c3259649fa18ac1607877b5d36282f00 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicyBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/TriggeringPolicyBase.java @@ -15,7 +15,6 @@ package ch.qos.logback.core.rolling; import ch.qos.logback.core.spi.ContextAwareBase; - /** * SizeBasedTriggeringPolicy looks at size of the file being * currently written to. @@ -24,21 +23,19 @@ import ch.qos.logback.core.spi.ContextAwareBase; * */ abstract public class TriggeringPolicyBase extends ContextAwareBase implements TriggeringPolicy { - - private boolean start; - - public void start() { - start = true; - } - public void stop() { - start = false; - } + private boolean start; - public boolean isStarted() { - return start; - } + public void start() { + start = true; + } + public void stop() { + start = false; + } + public boolean isStarted() { + return start; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/ArchiveRemover.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/ArchiveRemover.java index d0f6397467c5fe48a38180fbf142ac164dd47078..b42be3a7c6f1ae791cf2df4754cf9e8d84b67008 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/ArchiveRemover.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/ArchiveRemover.java @@ -23,6 +23,7 @@ import ch.qos.logback.core.spi.ContextAware; * @author Ceki Gülcü */ public interface ArchiveRemover extends ContextAware { - void clean(Date now); - void setMaxHistory(int maxHistory); -} \ No newline at end of file + void clean(Date now); + + void setMaxHistory(int maxHistory); +} \ No newline at end of file diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/AsynchronousCompressor.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/AsynchronousCompressor.java index e04f7d590eff12229e74aff985189251908b00ca..ee0e14e94868e402b77d0338878186419b032dc8 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/AsynchronousCompressor.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/AsynchronousCompressor.java @@ -18,19 +18,17 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; public class AsynchronousCompressor { - Compressor compressor; + Compressor compressor; - public AsynchronousCompressor(Compressor compressor) { - this.compressor = compressor; - } + public AsynchronousCompressor(Compressor compressor) { + this.compressor = compressor; + } - public Future compressAsynchronously(String nameOfFile2Compress, - String nameOfCompressedFile, String innerEntryName) { - ExecutorService executor = Executors.newScheduledThreadPool(1); - Future future = executor.submit(new CompressionRunnable(compressor, - nameOfFile2Compress, nameOfCompressedFile, innerEntryName)); - executor.shutdown(); - return future; - } + public Future compressAsynchronously(String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) { + ExecutorService executor = Executors.newScheduledThreadPool(1); + Future future = executor.submit(new CompressionRunnable(compressor, nameOfFile2Compress, nameOfCompressedFile, innerEntryName)); + executor.shutdown(); + return future; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionMode.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionMode.java index d864cb0e851ea322b0973cdba4aae5df32bdf618..e2fd3cd91a161e27fe230d23a64aff403b1aaae3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionMode.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionMode.java @@ -14,5 +14,5 @@ package ch.qos.logback.core.rolling.helper; public enum CompressionMode { - NONE, GZ, ZIP; + NONE, GZ, ZIP; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionRunnable.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionRunnable.java index a2ea2bbcaa483a293fbcc87b8e354d2862ae2c5b..40719b8f35115da396d1f1daeea4c5d1baf4a811 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionRunnable.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/CompressionRunnable.java @@ -13,23 +13,21 @@ */ package ch.qos.logback.core.rolling.helper; - public class CompressionRunnable implements Runnable { - final Compressor compressor; - final String nameOfFile2Compress; - final String nameOfCompressedFile; - final String innerEntryName; + final Compressor compressor; + final String nameOfFile2Compress; + final String nameOfCompressedFile; + final String innerEntryName; - public CompressionRunnable(Compressor compressor, String nameOfFile2Compress, - String nameOfCompressedFile, String innerEntryName) { - this.compressor = compressor; - this.nameOfFile2Compress = nameOfFile2Compress; - this.nameOfCompressedFile = nameOfCompressedFile; - this.innerEntryName = innerEntryName; - } + public CompressionRunnable(Compressor compressor, String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) { + this.compressor = compressor; + this.nameOfFile2Compress = nameOfFile2Compress; + this.nameOfCompressedFile = nameOfCompressedFile; + this.innerEntryName = innerEntryName; + } - public void run() { - compressor.compress(nameOfFile2Compress, nameOfCompressedFile, innerEntryName); - } + public void run() { + compressor.compress(nameOfFile2Compress, nameOfCompressedFile, innerEntryName); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/Compressor.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/Compressor.java index 3ce8d78de219be3edc17c982b2c57c57b415bb11..517ec1422e90dfe62dc4a3e1b20226e5d4e2df7d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/Compressor.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/Compressor.java @@ -36,237 +36,222 @@ import ch.qos.logback.core.util.FileUtil; */ public class Compressor extends ContextAwareBase { - final CompressionMode compressionMode; - - static final int BUFFER_SIZE = 8192; - - public Compressor(CompressionMode compressionMode) { - this.compressionMode = compressionMode; - } - - /** - * @param nameOfFile2Compress - * @param nameOfCompressedFile - * @param innerEntryName The name of the file within the zip file. Use for ZIP compression. - */ - public void compress(String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) { - switch (compressionMode) { - case GZ: - gzCompress(nameOfFile2Compress, nameOfCompressedFile); - break; - case ZIP: - zipCompress(nameOfFile2Compress, nameOfCompressedFile, innerEntryName); - break; - case NONE: - throw new UnsupportedOperationException( - "compress method called in NONE compression mode"); - } - } - - private void zipCompress(String nameOfFile2zip, String nameOfZippedFile, String innerEntryName) { - File file2zip = new File(nameOfFile2zip); + final CompressionMode compressionMode; - if (!file2zip.exists()) { - addStatus(new WarnStatus("The file to compress named [" + nameOfFile2zip - + "] does not exist.", this)); + static final int BUFFER_SIZE = 8192; - return; + public Compressor(CompressionMode compressionMode) { + this.compressionMode = compressionMode; } - if (innerEntryName == null) { - addStatus(new WarnStatus("The innerEntryName parameter cannot be null", this)); - return; + /** + * @param nameOfFile2Compress + * @param nameOfCompressedFile + * @param innerEntryName The name of the file within the zip file. Use for ZIP compression. + */ + public void compress(String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) { + switch (compressionMode) { + case GZ: + gzCompress(nameOfFile2Compress, nameOfCompressedFile); + break; + case ZIP: + zipCompress(nameOfFile2Compress, nameOfCompressedFile, innerEntryName); + break; + case NONE: + throw new UnsupportedOperationException("compress method called in NONE compression mode"); + } } - if (!nameOfZippedFile.endsWith(".zip")) { - nameOfZippedFile = nameOfZippedFile + ".zip"; - } + private void zipCompress(String nameOfFile2zip, String nameOfZippedFile, String innerEntryName) { + File file2zip = new File(nameOfFile2zip); - File zippedFile = new File(nameOfZippedFile); + if (!file2zip.exists()) { + addStatus(new WarnStatus("The file to compress named [" + nameOfFile2zip + "] does not exist.", this)); - if (zippedFile.exists()) { - addStatus(new WarnStatus("The target compressed file named [" - + nameOfZippedFile + "] exist already.", this)); + return; + } - return; - } + if (innerEntryName == null) { + addStatus(new WarnStatus("The innerEntryName parameter cannot be null", this)); + return; + } - addInfo("ZIP compressing [" + file2zip + "] as ["+zippedFile+"]"); - createMissingTargetDirsIfNecessary(zippedFile); - - BufferedInputStream bis = null; - ZipOutputStream zos = null; - try { - bis = new BufferedInputStream(new FileInputStream(nameOfFile2zip)); - zos = new ZipOutputStream(new FileOutputStream(nameOfZippedFile)); - - ZipEntry zipEntry = computeZipEntry(innerEntryName); - zos.putNextEntry(zipEntry); - - byte[] inbuf = new byte[BUFFER_SIZE]; - int n; - - while ((n = bis.read(inbuf)) != -1) { - zos.write(inbuf, 0, n); - } - - bis.close(); - bis = null; - zos.close(); - zos = null; - - if (!file2zip.delete()) { - addStatus(new WarnStatus("Could not delete [" + nameOfFile2zip + "].", - this)); - } - } catch (Exception e) { - addStatus(new ErrorStatus("Error occurred while compressing [" - + nameOfFile2zip + "] into [" + nameOfZippedFile + "].", this, e)); - } finally { - if (bis != null) { - try { - bis.close(); - } catch (IOException e) { - // ignore + if (!nameOfZippedFile.endsWith(".zip")) { + nameOfZippedFile = nameOfZippedFile + ".zip"; } - } - if (zos != null) { + + File zippedFile = new File(nameOfZippedFile); + + if (zippedFile.exists()) { + addStatus(new WarnStatus("The target compressed file named [" + nameOfZippedFile + "] exist already.", this)); + + return; + } + + addInfo("ZIP compressing [" + file2zip + "] as [" + zippedFile + "]"); + createMissingTargetDirsIfNecessary(zippedFile); + + BufferedInputStream bis = null; + ZipOutputStream zos = null; try { - zos.close(); - } catch (IOException e) { - // ignore + bis = new BufferedInputStream(new FileInputStream(nameOfFile2zip)); + zos = new ZipOutputStream(new FileOutputStream(nameOfZippedFile)); + + ZipEntry zipEntry = computeZipEntry(innerEntryName); + zos.putNextEntry(zipEntry); + + byte[] inbuf = new byte[BUFFER_SIZE]; + int n; + + while ((n = bis.read(inbuf)) != -1) { + zos.write(inbuf, 0, n); + } + + bis.close(); + bis = null; + zos.close(); + zos = null; + + if (!file2zip.delete()) { + addStatus(new WarnStatus("Could not delete [" + nameOfFile2zip + "].", this)); + } + } catch (Exception e) { + addStatus(new ErrorStatus("Error occurred while compressing [" + nameOfFile2zip + "] into [" + nameOfZippedFile + "].", this, e)); + } finally { + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + // ignore + } + } + if (zos != null) { + try { + zos.close(); + } catch (IOException e) { + // ignore + } + } } - } + } + // http://jira.qos.ch/browse/LBCORE-98 + // The name of the compressed file as nested within the zip archive + // + // Case 1: RawFile = null, Patern = foo-%d.zip + // nestedFilename = foo-${current-date} + // + // Case 2: RawFile = hello.txt, Pattern = = foo-%d.zip + // nestedFilename = foo-${current-date} + // + // in both cases, the strategy consisting of removing the compression + // suffix of zip file works reasonably well. The alternative strategy + // whereby the nested file name was based on the value of the raw file name + // (applicable to case 2 only) has the disadvantage of the nested files + // all having the same name, which could make it harder for the user + // to unzip the file without collisions + ZipEntry computeZipEntry(File zippedFile) { + return computeZipEntry(zippedFile.getName()); + } - } - - // http://jira.qos.ch/browse/LBCORE-98 - // The name of the compressed file as nested within the zip archive - // - // Case 1: RawFile = null, Patern = foo-%d.zip - // nestedFilename = foo-${current-date} - // - // Case 2: RawFile = hello.txt, Pattern = = foo-%d.zip - // nestedFilename = foo-${current-date} - // - // in both cases, the strategy consisting of removing the compression - // suffix of zip file works reasonably well. The alternative strategy - // whereby the nested file name was based on the value of the raw file name - // (applicable to case 2 only) has the disadvantage of the nested files - // all having the same name, which could make it harder for the user - // to unzip the file without collisions - ZipEntry computeZipEntry(File zippedFile) { - return computeZipEntry(zippedFile.getName()); - } - - ZipEntry computeZipEntry(String filename) { - String nameOfFileNestedWithinArchive = computeFileNameStr_WCS(filename, compressionMode); - return new ZipEntry(nameOfFileNestedWithinArchive); - } - - - private void gzCompress(String nameOfFile2gz, String nameOfgzedFile) { - File file2gz = new File(nameOfFile2gz); - - if (!file2gz.exists()) { - addStatus(new WarnStatus("The file to compress named [" + nameOfFile2gz - + "] does not exist.", this)); - - return; + ZipEntry computeZipEntry(String filename) { + String nameOfFileNestedWithinArchive = computeFileNameStr_WCS(filename, compressionMode); + return new ZipEntry(nameOfFileNestedWithinArchive); } + private void gzCompress(String nameOfFile2gz, String nameOfgzedFile) { + File file2gz = new File(nameOfFile2gz); - if (!nameOfgzedFile.endsWith(".gz")) { - nameOfgzedFile = nameOfgzedFile + ".gz"; - } + if (!file2gz.exists()) { + addStatus(new WarnStatus("The file to compress named [" + nameOfFile2gz + "] does not exist.", this)); - File gzedFile = new File(nameOfgzedFile); + return; + } - if (gzedFile.exists()) { - addWarn("The target compressed file named [" - + nameOfgzedFile + "] exist already. Aborting file compression."); - return; - } + if (!nameOfgzedFile.endsWith(".gz")) { + nameOfgzedFile = nameOfgzedFile + ".gz"; + } - addInfo("GZ compressing [" + file2gz + "] as ["+gzedFile+"]"); - createMissingTargetDirsIfNecessary(gzedFile); - - BufferedInputStream bis = null; - GZIPOutputStream gzos = null; - try { - bis = new BufferedInputStream(new FileInputStream(nameOfFile2gz)); - gzos = new GZIPOutputStream(new FileOutputStream(nameOfgzedFile)); - byte[] inbuf = new byte[BUFFER_SIZE]; - int n; - - while ((n = bis.read(inbuf)) != -1) { - gzos.write(inbuf, 0, n); - } - - bis.close(); - bis = null; - gzos.close(); - gzos = null; - - if (!file2gz.delete()) { - addStatus(new WarnStatus("Could not delete [" + nameOfFile2gz + "].", - this)); - } - } catch (Exception e) { - addStatus(new ErrorStatus("Error occurred while compressing [" - + nameOfFile2gz + "] into [" + nameOfgzedFile + "].", this, e)); - } finally { - if (bis != null) { - try { - bis.close(); - } catch (IOException e) { - // ignore + File gzedFile = new File(nameOfgzedFile); + + if (gzedFile.exists()) { + addWarn("The target compressed file named [" + nameOfgzedFile + "] exist already. Aborting file compression."); + return; } - } - if (gzos != null) { + + addInfo("GZ compressing [" + file2gz + "] as [" + gzedFile + "]"); + createMissingTargetDirsIfNecessary(gzedFile); + + BufferedInputStream bis = null; + GZIPOutputStream gzos = null; try { - gzos.close(); - } catch (IOException e) { - // ignore + bis = new BufferedInputStream(new FileInputStream(nameOfFile2gz)); + gzos = new GZIPOutputStream(new FileOutputStream(nameOfgzedFile)); + byte[] inbuf = new byte[BUFFER_SIZE]; + int n; + + while ((n = bis.read(inbuf)) != -1) { + gzos.write(inbuf, 0, n); + } + + bis.close(); + bis = null; + gzos.close(); + gzos = null; + + if (!file2gz.delete()) { + addStatus(new WarnStatus("Could not delete [" + nameOfFile2gz + "].", this)); + } + } catch (Exception e) { + addStatus(new ErrorStatus("Error occurred while compressing [" + nameOfFile2gz + "] into [" + nameOfgzedFile + "].", this, e)); + } finally { + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + // ignore + } + } + if (gzos != null) { + try { + gzos.close(); + } catch (IOException e) { + // ignore + } + } } - } } - } - - static public String computeFileNameStr_WCS(String fileNamePatternStr, - CompressionMode compressionMode) { - int len = fileNamePatternStr.length(); - switch (compressionMode) { - case GZ: - if (fileNamePatternStr.endsWith(".gz")) - return fileNamePatternStr.substring(0, len - 3); - else - return fileNamePatternStr; - case ZIP: - if (fileNamePatternStr.endsWith(".zip")) - return fileNamePatternStr.substring(0, len - 4); - else - return fileNamePatternStr; - case NONE: - return fileNamePatternStr; - } - throw new IllegalStateException("Execution should not reach this point"); - } + static public String computeFileNameStr_WCS(String fileNamePatternStr, CompressionMode compressionMode) { + int len = fileNamePatternStr.length(); + switch (compressionMode) { + case GZ: + if (fileNamePatternStr.endsWith(".gz")) + return fileNamePatternStr.substring(0, len - 3); + else + return fileNamePatternStr; + case ZIP: + if (fileNamePatternStr.endsWith(".zip")) + return fileNamePatternStr.substring(0, len - 4); + else + return fileNamePatternStr; + case NONE: + return fileNamePatternStr; + } + throw new IllegalStateException("Execution should not reach this point"); + } - void createMissingTargetDirsIfNecessary(File file) { - boolean result = FileUtil.createMissingParentDirectories(file); - if (!result) { - addError("Failed to create parent directories for [" - + file.getAbsolutePath() + "]"); + void createMissingTargetDirsIfNecessary(File file) { + boolean result = FileUtil.createMissingParentDirectories(file); + if (!result) { + addError("Failed to create parent directories for [" + file.getAbsolutePath() + "]"); + } } - } - @Override - public String toString() { - return this.getClass().getName(); - } + @Override + public String toString() { + return this.getClass().getName(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DateTokenConverter.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DateTokenConverter.java index cca4853342af0cc8ba212231a3dbe63f97a5ab20..870fed4a5c507119f089e08602289912f9ee4e1c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DateTokenConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DateTokenConverter.java @@ -29,78 +29,79 @@ import ch.qos.logback.core.util.DatePatternToRegexUtil; */ public class DateTokenConverter extends DynamicConverter implements MonoTypedConverter { - /** - * The conversion word/character with which this converter is registered. - */ - public final static String CONVERTER_KEY = "d"; - public final static String AUXILIARY_TOKEN = "AUX"; - public static final String DEFAULT_DATE_PATTERN = CoreConstants.DAILY_DATE_PATTERN; + /** + * The conversion word/character with which this converter is registered. + */ + public final static String CONVERTER_KEY = "d"; + public final static String AUXILIARY_TOKEN = "AUX"; + public static final String DEFAULT_DATE_PATTERN = CoreConstants.DAILY_DATE_PATTERN; - private String datePattern; - private TimeZone timeZone; - private CachingDateFormatter cdf; - // is this token converter primary or auxiliary? Only the primary converter - // determines the rolling period - private boolean primary = true; - public void start() { - this.datePattern = getFirstOption(); - if (this.datePattern == null) { - this.datePattern = DEFAULT_DATE_PATTERN; - } + private String datePattern; + private TimeZone timeZone; + private CachingDateFormatter cdf; + // is this token converter primary or auxiliary? Only the primary converter + // determines the rolling period + private boolean primary = true; - final List optionList = getOptionList(); - if (optionList != null) { - for (int optionIndex = 1; optionIndex < optionList.size(); optionIndex++) { - String option = optionList.get(optionIndex); - if (AUXILIARY_TOKEN.equalsIgnoreCase(option)) { - primary = false; - } else { - timeZone = TimeZone.getTimeZone(option); + public void start() { + this.datePattern = getFirstOption(); + if (this.datePattern == null) { + this.datePattern = DEFAULT_DATE_PATTERN; + } + + final List optionList = getOptionList(); + if (optionList != null) { + for (int optionIndex = 1; optionIndex < optionList.size(); optionIndex++) { + String option = optionList.get(optionIndex); + if (AUXILIARY_TOKEN.equalsIgnoreCase(option)) { + primary = false; + } else { + timeZone = TimeZone.getTimeZone(option); + } + } } - } - } - cdf = new CachingDateFormatter(datePattern); - if (timeZone != null) { - cdf.setTimeZone(timeZone); + cdf = new CachingDateFormatter(datePattern); + if (timeZone != null) { + cdf.setTimeZone(timeZone); + } } - } - public String convert(Date date) { - return cdf.format(date.getTime()); - } + public String convert(Date date) { + return cdf.format(date.getTime()); + } - public String convert(Object o) { - if (o == null) { - throw new IllegalArgumentException("Null argument forbidden"); + public String convert(Object o) { + if (o == null) { + throw new IllegalArgumentException("Null argument forbidden"); + } + if (o instanceof Date) { + return convert((Date) o); + } + throw new IllegalArgumentException("Cannot convert " + o + " of type" + o.getClass().getName()); } - if (o instanceof Date) { - return convert((Date) o); - } - throw new IllegalArgumentException("Cannot convert "+o+" of type"+o.getClass().getName()); - } - /** - * Return the date pattern. - */ - public String getDatePattern() { - return datePattern; - } + /** + * Return the date pattern. + */ + public String getDatePattern() { + return datePattern; + } - public TimeZone getTimeZone() { - return timeZone; - } + public TimeZone getTimeZone() { + return timeZone; + } - public boolean isApplicable(Object o) { - return (o instanceof Date); - } + public boolean isApplicable(Object o) { + return (o instanceof Date); + } - public String toRegex() { - DatePatternToRegexUtil datePatternToRegexUtil = new DatePatternToRegexUtil(datePattern); - return datePatternToRegexUtil.toRegex(); - } + public String toRegex() { + DatePatternToRegexUtil datePatternToRegexUtil = new DatePatternToRegexUtil(datePattern); + return datePatternToRegexUtil.toRegex(); + } - public boolean isPrimary() { - return primary; - } + public boolean isPrimary() { + return primary; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DefaultArchiveRemover.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DefaultArchiveRemover.java index ba82c76ce7bb02abfcba023c0b02f0b69a34e24b..dbe6d635d68ce119e603a963cb103efb265d2648 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DefaultArchiveRemover.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/DefaultArchiveRemover.java @@ -21,118 +21,115 @@ import ch.qos.logback.core.pattern.Converter; import ch.qos.logback.core.pattern.LiteralConverter; import ch.qos.logback.core.spi.ContextAwareBase; -abstract public class DefaultArchiveRemover extends ContextAwareBase implements - ArchiveRemover { - - static protected final long UNINITIALIZED = -1; - // aim for 64 days, except in case of hourly rollover - static protected final long INACTIVITY_TOLERANCE_IN_MILLIS = 64L * (long) CoreConstants.MILLIS_IN_ONE_DAY; - static final int MAX_VALUE_FOR_INACTIVITY_PERIODS = 14 * 24; // 14 days in case of hourly rollover - - final FileNamePattern fileNamePattern; - final RollingCalendar rc; - int periodOffsetForDeletionTarget; - final boolean parentClean; - long lastHeartBeat = UNINITIALIZED; - - public DefaultArchiveRemover(FileNamePattern fileNamePattern, - RollingCalendar rc) { - this.fileNamePattern = fileNamePattern; - this.rc = rc; - this.parentClean = computeParentCleaningFlag(fileNamePattern); - } - - - int computeElapsedPeriodsSinceLastClean(long nowInMillis) { - long periodsElapsed = 0; - if (lastHeartBeat == UNINITIALIZED) { - addInfo("first clean up after appender initialization"); - periodsElapsed = rc.periodsElapsed(nowInMillis, nowInMillis + INACTIVITY_TOLERANCE_IN_MILLIS); - if (periodsElapsed > MAX_VALUE_FOR_INACTIVITY_PERIODS) - periodsElapsed = MAX_VALUE_FOR_INACTIVITY_PERIODS; - } else { - periodsElapsed = rc.periodsElapsed(lastHeartBeat, nowInMillis); - if (periodsElapsed < 1) { - addWarn("Unexpected periodsElapsed value " + periodsElapsed); - periodsElapsed = 1; - } +abstract public class DefaultArchiveRemover extends ContextAwareBase implements ArchiveRemover { + + static protected final long UNINITIALIZED = -1; + // aim for 64 days, except in case of hourly rollover + static protected final long INACTIVITY_TOLERANCE_IN_MILLIS = 64L * (long) CoreConstants.MILLIS_IN_ONE_DAY; + static final int MAX_VALUE_FOR_INACTIVITY_PERIODS = 14 * 24; // 14 days in case of hourly rollover + + final FileNamePattern fileNamePattern; + final RollingCalendar rc; + int periodOffsetForDeletionTarget; + final boolean parentClean; + long lastHeartBeat = UNINITIALIZED; + + public DefaultArchiveRemover(FileNamePattern fileNamePattern, RollingCalendar rc) { + this.fileNamePattern = fileNamePattern; + this.rc = rc; + this.parentClean = computeParentCleaningFlag(fileNamePattern); } - return (int) periodsElapsed; - } - - public void clean(Date now) { - long nowInMillis = now.getTime(); - int periodsElapsed = computeElapsedPeriodsSinceLastClean(nowInMillis); - lastHeartBeat = nowInMillis; - if (periodsElapsed > 1) { - addInfo("periodsElapsed = " + periodsElapsed); + + int computeElapsedPeriodsSinceLastClean(long nowInMillis) { + long periodsElapsed = 0; + if (lastHeartBeat == UNINITIALIZED) { + addInfo("first clean up after appender initialization"); + periodsElapsed = rc.periodsElapsed(nowInMillis, nowInMillis + INACTIVITY_TOLERANCE_IN_MILLIS); + if (periodsElapsed > MAX_VALUE_FOR_INACTIVITY_PERIODS) + periodsElapsed = MAX_VALUE_FOR_INACTIVITY_PERIODS; + } else { + periodsElapsed = rc.periodsElapsed(lastHeartBeat, nowInMillis); + if (periodsElapsed < 1) { + addWarn("Unexpected periodsElapsed value " + periodsElapsed); + periodsElapsed = 1; + } + } + return (int) periodsElapsed; } - for (int i = 0; i < periodsElapsed; i++) { - cleanByPeriodOffset(now, periodOffsetForDeletionTarget - i); + + public void clean(Date now) { + long nowInMillis = now.getTime(); + int periodsElapsed = computeElapsedPeriodsSinceLastClean(nowInMillis); + lastHeartBeat = nowInMillis; + if (periodsElapsed > 1) { + addInfo("periodsElapsed = " + periodsElapsed); + } + for (int i = 0; i < periodsElapsed; i++) { + cleanByPeriodOffset(now, periodOffsetForDeletionTarget - i); + } } - } - abstract void cleanByPeriodOffset(Date now, int periodOffset); + abstract void cleanByPeriodOffset(Date now, int periodOffset); - boolean computeParentCleaningFlag(FileNamePattern fileNamePattern) { - DateTokenConverter dtc = fileNamePattern.getPrimaryDateTokenConverter(); - // if the date pattern has a /, then we need parent cleaning - if (dtc.getDatePattern().indexOf('/') != -1) { - return true; - } - // if the literal string subsequent to the dtc contains a /, we also - // need parent cleaning + boolean computeParentCleaningFlag(FileNamePattern fileNamePattern) { + DateTokenConverter dtc = fileNamePattern.getPrimaryDateTokenConverter(); + // if the date pattern has a /, then we need parent cleaning + if (dtc.getDatePattern().indexOf('/') != -1) { + return true; + } + // if the literal string subsequent to the dtc contains a /, we also + // need parent cleaning - Converter p = fileNamePattern.headTokenConverter; + Converter p = fileNamePattern.headTokenConverter; - // find the date converter - while (p != null) { - if (p instanceof DateTokenConverter) { - break; - } - p = p.getNext(); - } + // find the date converter + while (p != null) { + if (p instanceof DateTokenConverter) { + break; + } + p = p.getNext(); + } - while (p != null) { - if (p instanceof LiteralConverter) { - String s = p.convert(null); - if (s.indexOf('/') != -1) { - return true; + while (p != null) { + if (p instanceof LiteralConverter) { + String s = p.convert(null); + if (s.indexOf('/') != -1) { + return true; + } + } + p = p.getNext(); } - } - p = p.getNext(); + + // no /, so we don't need parent cleaning + return false; } - // no /, so we don't need parent cleaning - return false; - } - - void removeFolderIfEmpty(File dir) { - removeFolderIfEmpty(dir, 0); - } - - /** - * Will remove the directory passed as parameter if empty. After that, if the - * parent is also becomes empty, remove the parent dir as well but at most 3 - * times. - * - * @param dir - * @param depth - */ - private void removeFolderIfEmpty(File dir, int depth) { - // we should never go more than 3 levels higher - if (depth >= 3) { - return; + void removeFolderIfEmpty(File dir) { + removeFolderIfEmpty(dir, 0); } - if (dir.isDirectory() && FileFilterUtil.isEmptyDirectory(dir)) { - addInfo("deleting folder [" + dir + "]"); - dir.delete(); - removeFolderIfEmpty(dir.getParentFile(), depth + 1); + + /** + * Will remove the directory passed as parameter if empty. After that, if the + * parent is also becomes empty, remove the parent dir as well but at most 3 + * times. + * + * @param dir + * @param depth + */ + private void removeFolderIfEmpty(File dir, int depth) { + // we should never go more than 3 levels higher + if (depth >= 3) { + return; + } + if (dir.isDirectory() && FileFilterUtil.isEmptyDirectory(dir)) { + addInfo("deleting folder [" + dir + "]"); + dir.delete(); + removeFolderIfEmpty(dir.getParentFile(), depth + 1); + } } - } - public void setMaxHistory(int maxHistory) { - this.periodOffsetForDeletionTarget = -maxHistory - 1; - } + public void setMaxHistory(int maxHistory) { + this.periodOffsetForDeletionTarget = -maxHistory - 1; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileFilterUtil.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileFilterUtil.java index 9659bec837ab7003345c6b72801294f5d4703005..484e3ab530c5bc8d6dbe488ca2283feb3cffb9b4 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileFilterUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileFilterUtil.java @@ -22,108 +22,105 @@ import java.util.regex.Pattern; public class FileFilterUtil { - public static void sortFileArrayByName(File[] fileArray) { - Arrays.sort(fileArray, new Comparator() { - public int compare(File o1, File o2) { - String o1Name = o1.getName(); - String o2Name = o2.getName(); - return (o1Name.compareTo(o2Name)); - } - }); - } - - public static void reverseSortFileArrayByName(File[] fileArray) { - Arrays.sort(fileArray, new Comparator() { - public int compare(File o1, File o2) { - String o1Name = o1.getName(); - String o2Name = o2.getName(); - return (o2Name.compareTo(o1Name)); - } - }); - } + public static void sortFileArrayByName(File[] fileArray) { + Arrays.sort(fileArray, new Comparator() { + public int compare(File o1, File o2) { + String o1Name = o1.getName(); + String o2Name = o2.getName(); + return (o1Name.compareTo(o2Name)); + } + }); + } - public static String afterLastSlash(String sregex) { - int i = sregex.lastIndexOf('/'); - if (i == -1) { - return sregex; - } else { - return sregex.substring(i + 1); + public static void reverseSortFileArrayByName(File[] fileArray) { + Arrays.sort(fileArray, new Comparator() { + public int compare(File o1, File o2) { + String o1Name = o1.getName(); + String o2Name = o2.getName(); + return (o2Name.compareTo(o1Name)); + } + }); } - } - static public boolean isEmptyDirectory(File dir) { - if (!dir.isDirectory()) { - throw new IllegalArgumentException("[" + dir + "] must be a directory"); + public static String afterLastSlash(String sregex) { + int i = sregex.lastIndexOf('/'); + if (i == -1) { + return sregex; + } else { + return sregex.substring(i + 1); + } } - String[] filesInDir = dir.list(); - if (filesInDir == null || filesInDir.length == 0) { - return true; - } else { - return false; + + static public boolean isEmptyDirectory(File dir) { + if (!dir.isDirectory()) { + throw new IllegalArgumentException("[" + dir + "] must be a directory"); + } + String[] filesInDir = dir.list(); + if (filesInDir == null || filesInDir.length == 0) { + return true; + } else { + return false; + } } - } - /** - * Return the set of files matching the stemRegex as found in 'directory'. A - * stemRegex does not contain any slash characters or any folder separators. - * - * @param file - * @param stemRegex - * @return - */ - public static File[] filesInFolderMatchingStemRegex(File file, - final String stemRegex) { + /** + * Return the set of files matching the stemRegex as found in 'directory'. A + * stemRegex does not contain any slash characters or any folder separators. + * + * @param file + * @param stemRegex + * @return + */ + public static File[] filesInFolderMatchingStemRegex(File file, final String stemRegex) { - if (file == null) { - return new File[0]; + if (file == null) { + return new File[0]; + } + if (!file.exists() || !file.isDirectory()) { + return new File[0]; + } + return file.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.matches(stemRegex); + } + }); } - if (!file.exists() || !file.isDirectory()) { - return new File[0]; - } - return file.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.matches(stemRegex); - } - }); - } - static public int findHighestCounter(File[] matchingFileArray, final String stemRegex) { - int max = Integer.MIN_VALUE; - for (File aFile : matchingFileArray) { - int aCounter = FileFilterUtil.extractCounter(aFile, stemRegex); - if (max < aCounter) - max = aCounter; + static public int findHighestCounter(File[] matchingFileArray, final String stemRegex) { + int max = Integer.MIN_VALUE; + for (File aFile : matchingFileArray) { + int aCounter = FileFilterUtil.extractCounter(aFile, stemRegex); + if (max < aCounter) + max = aCounter; + } + return max; } - return max; - } - static public int extractCounter(File file, final String stemRegex) { - Pattern p = Pattern.compile(stemRegex); - String lastFileName = file.getName(); + static public int extractCounter(File file, final String stemRegex) { + Pattern p = Pattern.compile(stemRegex); + String lastFileName = file.getName(); - Matcher m = p.matcher(lastFileName); - if (!m.matches()) { - throw new IllegalStateException("The regex [" + stemRegex - + "] should match [" + lastFileName + "]"); + Matcher m = p.matcher(lastFileName); + if (!m.matches()) { + throw new IllegalStateException("The regex [" + stemRegex + "] should match [" + lastFileName + "]"); + } + String counterAsStr = m.group(1); + return new Integer(counterAsStr).intValue(); } - String counterAsStr = m.group(1); - return new Integer(counterAsStr).intValue(); - } - - public static String slashify(String in) { - return in.replace('\\', '/'); - } - public static void removeEmptyParentDirectories(File file, - int recursivityCount) { - // we should never go more than 3 levels higher - if (recursivityCount >= 3) { - return; + public static String slashify(String in) { + return in.replace('\\', '/'); } - File parent = file.getParentFile(); - if (parent.isDirectory() && FileFilterUtil.isEmptyDirectory(parent)) { - parent.delete(); - removeEmptyParentDirectories(parent, recursivityCount + 1); + + public static void removeEmptyParentDirectories(File file, int recursivityCount) { + // we should never go more than 3 levels higher + if (recursivityCount >= 3) { + return; + } + File parent = file.getParentFile(); + if (parent.isDirectory() && FileFilterUtil.isEmptyDirectory(parent)) { + parent.delete(); + removeEmptyParentDirectories(parent, recursivityCount + 1); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileNamePattern.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileNamePattern.java index 4ff7b23c5beba45e8739dfe7327c99d8a2911206..072d81a1083190bab401ac5b678a7f9b8e701fd9 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileNamePattern.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileNamePattern.java @@ -108,7 +108,7 @@ public class FileNamePattern extends ContextAwareBase { } return null; } - + public String convertMultipleArguments(Object... objectList) { StringBuilder buf = new StringBuilder(); Converter c = headTokenConverter; diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileStoreUtil.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileStoreUtil.java index c5827829bd81b3b35e04ad62851b1bc756f4a3e9..e5a610243825eb62658b4f00e9ee9c585a86377d 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileStoreUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/FileStoreUtil.java @@ -26,50 +26,49 @@ import java.lang.reflect.Method; */ public class FileStoreUtil { - static final String PATH_CLASS_STR = "java.nio.file.Path"; - static final String FILES_CLASS_STR = "java.nio.file.Files"; + static final String PATH_CLASS_STR = "java.nio.file.Path"; + static final String FILES_CLASS_STR = "java.nio.file.Files"; - /** - * This method assumes that both files a and b exists. - * - * @param a - * @param b - * @return - * @throws Exception - */ - static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure { - if (!a.exists()) { - throw new IllegalArgumentException("File [" + a + "] does not exist."); - } - if (!b.exists()) { - throw new IllegalArgumentException("File [" + b + "] does not exist."); - } - -// Implements the following by reflection -// Path pathA = a.toPath(); -// Path pathB = b.toPath(); -// -// FileStore fileStoreA = Files.getFileStore(pathA); -// FileStore fileStoreB = Files.getFileStore(pathB); -// -// return fileStoreA.equals(fileStoreB); + /** + * This method assumes that both files a and b exists. + * + * @param a + * @param b + * @return + * @throws Exception + */ + static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure { + if (!a.exists()) { + throw new IllegalArgumentException("File [" + a + "] does not exist."); + } + if (!b.exists()) { + throw new IllegalArgumentException("File [" + b + "] does not exist."); + } - try { - Class pathClass = Class.forName(PATH_CLASS_STR); - Class filesClass = Class.forName(FILES_CLASS_STR); + // Implements the following by reflection + // Path pathA = a.toPath(); + // Path pathB = b.toPath(); + // + // FileStore fileStoreA = Files.getFileStore(pathA); + // FileStore fileStoreB = Files.getFileStore(pathB); + // + // return fileStoreA.equals(fileStoreB); - Method toPath = File.class.getMethod("toPath"); - Method getFileStoreMethod = filesClass.getMethod("getFileStore", pathClass); + try { + Class pathClass = Class.forName(PATH_CLASS_STR); + Class filesClass = Class.forName(FILES_CLASS_STR); + Method toPath = File.class.getMethod("toPath"); + Method getFileStoreMethod = filesClass.getMethod("getFileStore", pathClass); - Object pathA = toPath.invoke(a); - Object pathB = toPath.invoke(b); + Object pathA = toPath.invoke(a); + Object pathB = toPath.invoke(b); - Object fileStoreA = getFileStoreMethod.invoke(null, pathA); - Object fileStoreB = getFileStoreMethod.invoke(null, pathB); - return fileStoreA.equals(fileStoreB); - } catch (Exception e) { - throw new RolloverFailure("Failed to check file store equality for [" + a + "] and [" + b + "]", e); + Object fileStoreA = getFileStoreMethod.invoke(null, pathA); + Object fileStoreB = getFileStoreMethod.invoke(null, pathB); + return fileStoreA.equals(fileStoreB); + } catch (Exception e) { + throw new RolloverFailure("Failed to check file store equality for [" + a + "] and [" + b + "]", e); + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/IntegerTokenConverter.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/IntegerTokenConverter.java index 3f08ab60d0bd2fc85c5bd6e122828ecd30690d6b..e0d531d8360dced84fefb427171f1956ef4562bc 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/IntegerTokenConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/IntegerTokenConverter.java @@ -23,24 +23,24 @@ import ch.qos.logback.core.pattern.DynamicConverter; */ public class IntegerTokenConverter extends DynamicConverter implements MonoTypedConverter { - public final static String CONVERTER_KEY = "i"; - - public String convert(int i) { - return Integer.toString(i); - } + public final static String CONVERTER_KEY = "i"; - public String convert(Object o) { - if(o == null) { - throw new IllegalArgumentException("Null argument forbidden"); + public String convert(int i) { + return Integer.toString(i); } - if(o instanceof Integer) { - Integer i = (Integer) o; - return convert(i.intValue()); - } - throw new IllegalArgumentException("Cannot convert "+o+" of type"+o.getClass().getName()); - } - public boolean isApplicable(Object o) { - return (o instanceof Integer); - } + public String convert(Object o) { + if (o == null) { + throw new IllegalArgumentException("Null argument forbidden"); + } + if (o instanceof Integer) { + Integer i = (Integer) o; + return convert(i.intValue()); + } + throw new IllegalArgumentException("Cannot convert " + o + " of type" + o.getClass().getName()); + } + + public boolean isApplicable(Object o) { + return (o instanceof Integer); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/MonoTypedConverter.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/MonoTypedConverter.java index c1eccbb2d1ddd0739e5c7027df29b03493c7800e..c43369294d0b0416c9790976fa9d7ed3b2e1ac3b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/MonoTypedConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/MonoTypedConverter.java @@ -20,5 +20,5 @@ package ch.qos.logback.core.rolling.helper; * */ public interface MonoTypedConverter { - boolean isApplicable(Object o); + boolean isApplicable(Object o); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/PeriodicityType.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/PeriodicityType.java index c9446b40ea11a24604cbd40eea512cd93ac6ddcf..786e9fb6e82affb0fd6886c69033c8e093da7cc2 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/PeriodicityType.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/PeriodicityType.java @@ -15,14 +15,11 @@ package ch.qos.logback.core.rolling.helper; public enum PeriodicityType { - ERRONEOUS, TOP_OF_MILLISECOND, TOP_OF_SECOND, TOP_OF_MINUTE, TOP_OF_HOUR, HALF_DAY, TOP_OF_DAY, TOP_OF_WEEK, TOP_OF_MONTH; + ERRONEOUS, TOP_OF_MILLISECOND, TOP_OF_SECOND, TOP_OF_MINUTE, TOP_OF_HOUR, HALF_DAY, TOP_OF_DAY, TOP_OF_WEEK, TOP_OF_MONTH; - // The followed list consists of valid periodicy types in increasing period - // lengths - static PeriodicityType[] VALID_ORDERED_LIST = new PeriodicityType[] { - TOP_OF_MILLISECOND, PeriodicityType.TOP_OF_SECOND, - PeriodicityType.TOP_OF_MINUTE, PeriodicityType.TOP_OF_HOUR, - PeriodicityType.TOP_OF_DAY, PeriodicityType.TOP_OF_WEEK, - PeriodicityType.TOP_OF_MONTH }; + // The followed list consists of valid periodicy types in increasing period + // lengths + static PeriodicityType[] VALID_ORDERED_LIST = new PeriodicityType[] { TOP_OF_MILLISECOND, PeriodicityType.TOP_OF_SECOND, PeriodicityType.TOP_OF_MINUTE, + PeriodicityType.TOP_OF_HOUR, PeriodicityType.TOP_OF_DAY, PeriodicityType.TOP_OF_WEEK, PeriodicityType.TOP_OF_MONTH }; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RenameUtil.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RenameUtil.java index 781f8cdff47c95471e75ee0d29899d5a232a65dc..79c817dd8df577f2743b8d7aed4482eac09f85bd 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RenameUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RenameUtil.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.rolling.helper; - import java.io.File; import ch.qos.logback.core.CoreConstants; @@ -23,7 +22,6 @@ import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.EnvUtil; import ch.qos.logback.core.util.FileUtil; - /** * Utility class to help solving problems encountered while renaming files. * @@ -31,98 +29,92 @@ import ch.qos.logback.core.util.FileUtil; */ public class RenameUtil extends ContextAwareBase { - static String RENAMING_ERROR_URL = CoreConstants.CODES_URL + "#renamingError"; - - /** - * A relatively robust file renaming method which in case of failure due to - * src and target being on different volumes, falls back onto - * renaming by copying. - * - * @param src - * @param target - * @throws RolloverFailure - */ - public void rename(String src, String target) throws RolloverFailure { - if (src.equals(target)) { - addWarn("Source and target files are the same [" + src + "]. Skipping."); - return; - } - File srcFile = new File(src); - - if (srcFile.exists()) { - File targetFile = new File(target); - createMissingTargetDirsIfNecessary(targetFile); - - addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]"); - - boolean result = srcFile.renameTo(targetFile); - - if (!result) { - addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "]."); - if (areOnDifferentVolumes(srcFile, targetFile)) { - addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying."); - renameByCopying(src, target); - return; + static String RENAMING_ERROR_URL = CoreConstants.CODES_URL + "#renamingError"; + + /** + * A relatively robust file renaming method which in case of failure due to + * src and target being on different volumes, falls back onto + * renaming by copying. + * + * @param src + * @param target + * @throws RolloverFailure + */ + public void rename(String src, String target) throws RolloverFailure { + if (src.equals(target)) { + addWarn("Source and target files are the same [" + src + "]. Skipping."); + return; + } + File srcFile = new File(src); + + if (srcFile.exists()) { + File targetFile = new File(target); + createMissingTargetDirsIfNecessary(targetFile); + + addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]"); + + boolean result = srcFile.renameTo(targetFile); + + if (!result) { + addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "]."); + if (areOnDifferentVolumes(srcFile, targetFile)) { + addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying."); + renameByCopying(src, target); + return; + } else { + addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty."); + addWarn("See also " + RENAMING_ERROR_URL); + } + } } else { - addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty."); - addWarn("See also " + RENAMING_ERROR_URL); + throw new RolloverFailure("File [" + src + "] does not exist."); } - } - } else { - throw new RolloverFailure("File [" + src + "] does not exist."); } - } - - - /** - * Attempts tp determine whether both files are on different volumes. Returns true if we could determine that - * the files are on different volumes. Returns false otherwise or if an error occurred while doing the check. - * - * @param srcFile - * @param targetFile - * @return true if on different volumes, false otherwise or if an error occurred - */ - boolean areOnDifferentVolumes(File srcFile, File targetFile) throws RolloverFailure { - if (!EnvUtil.isJDK7OrHigher()) - return false; - - File parentOfTarget = targetFile.getParentFile(); - - try { - boolean onSameFileStore = FileStoreUtil.areOnSameFileStore(srcFile, parentOfTarget); - return !onSameFileStore; - } catch (RolloverFailure rf) { - addWarn("Error while checking file store equality", rf); - return false; - } - } - + /** + * Attempts tp determine whether both files are on different volumes. Returns true if we could determine that + * the files are on different volumes. Returns false otherwise or if an error occurred while doing the check. + * + * @param srcFile + * @param targetFile + * @return true if on different volumes, false otherwise or if an error occurred + */ + boolean areOnDifferentVolumes(File srcFile, File targetFile) throws RolloverFailure { + if (!EnvUtil.isJDK7OrHigher()) + return false; + + File parentOfTarget = targetFile.getParentFile(); + + try { + boolean onSameFileStore = FileStoreUtil.areOnSameFileStore(srcFile, parentOfTarget); + return !onSameFileStore; + } catch (RolloverFailure rf) { + addWarn("Error while checking file store equality", rf); + return false; + } + } + public void renameByCopying(String src, String target) throws RolloverFailure { - public void renameByCopying(String src, String target) - throws RolloverFailure { + FileUtil fileUtil = new FileUtil(getContext()); + fileUtil.copy(src, target); - FileUtil fileUtil = new FileUtil(getContext()); - fileUtil.copy(src, target); + File srcFile = new File(src); + if (!srcFile.delete()) { + addWarn("Could not delete " + src); + } - File srcFile = new File(src); - if (!srcFile.delete()) { - addWarn("Could not delete " + src); } - } - - void createMissingTargetDirsIfNecessary(File toFile) throws RolloverFailure { - boolean result = FileUtil.createMissingParentDirectories(toFile); - if (!result) { - throw new RolloverFailure("Failed to create parent directories for [" - + toFile.getAbsolutePath() + "]"); + void createMissingTargetDirsIfNecessary(File toFile) throws RolloverFailure { + boolean result = FileUtil.createMissingParentDirectories(toFile); + if (!result) { + throw new RolloverFailure("Failed to create parent directories for [" + toFile.getAbsolutePath() + "]"); + } } - } - @Override - public String toString() { - return "c.q.l.co.rolling.helper.RenameUtil"; - } + @Override + public String toString() { + return "c.q.l.co.rolling.helper.RenameUtil"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java index 5f9d3eb070a88ec6839d4f0a926b48eea7256543..b78bde70ad1319b9725bf7065c475fff6c9fd841 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/RollingCalendar.java @@ -103,21 +103,21 @@ public class RollingCalendar extends GregorianCalendar { case TOP_OF_DAY: // EE or uu - if(collision(7 * MILLIS_IN_ONE_DAY)) + if (collision(7 * MILLIS_IN_ONE_DAY)) return false; // isolated dd - if(collision(31 * MILLIS_IN_ONE_DAY)) + if (collision(31 * MILLIS_IN_ONE_DAY)) return false; // DD - if(collision(365 * MILLIS_IN_ONE_DAY)) + if (collision(365 * MILLIS_IN_ONE_DAY)) return false; return true; case TOP_OF_WEEK: // WW - if(collision(31 * MILLIS_IN_ONE_DAY)) + if (collision(31 * MILLIS_IN_ONE_DAY)) return false; // isolated ww - if(collision(365 * MILLIS_IN_ONE_DAY)) + if (collision(365 * MILLIS_IN_ONE_DAY)) return false; return true; default: @@ -216,7 +216,7 @@ public class RollingCalendar extends GregorianCalendar { static private Date innerGetEndOfThisPeriod(Calendar cal, PeriodicityType periodicityType, Date now) { return innerGetEndOfNextNthPeriod(cal, periodicityType, now, 1); } - + static private Date innerGetEndOfNextNthPeriod(Calendar cal, PeriodicityType periodicityType, Date now, int numPeriods) { cal.setTime(now); switch (periodicityType) { diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/SizeAndTimeBasedArchiveRemover.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/SizeAndTimeBasedArchiveRemover.java index 605795647e451e9f83c55ad9771feb34f2951d39..611423bbd9f49e0fddadbf6df8ca1729bc08d1fb 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/SizeAndTimeBasedArchiveRemover.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/SizeAndTimeBasedArchiveRemover.java @@ -18,39 +18,35 @@ import java.util.Date; public class SizeAndTimeBasedArchiveRemover extends DefaultArchiveRemover { - public SizeAndTimeBasedArchiveRemover(FileNamePattern fileNamePattern, - RollingCalendar rc) { - super(fileNamePattern, rc); - } - - public void cleanByPeriodOffset(Date now, int periodOffset) { - Date dateOfPeriodToClean = rc.getEndOfNextNthPeriod(now, periodOffset); - - String regex = fileNamePattern.toRegexForFixedDate(dateOfPeriodToClean); - String stemRegex = FileFilterUtil.afterLastSlash(regex); - File archive0 = new File(fileNamePattern.convertMultipleArguments( - dateOfPeriodToClean, 0)); - // in case the file has no directory part, i.e. if it's written into the - // user's current directory. - archive0 = archive0.getAbsoluteFile(); - - File parentDir = archive0.getAbsoluteFile().getParentFile(); - File[] matchingFileArray = FileFilterUtil.filesInFolderMatchingStemRegex( - parentDir, stemRegex); - - for (File f : matchingFileArray) { - Date fileLastModified = rc.getEndOfNextNthPeriod(new Date(f.lastModified()), -1); - - if (fileLastModified.compareTo(dateOfPeriodToClean) <= 0) { - addInfo("deleting " + f); - f.delete(); - } + public SizeAndTimeBasedArchiveRemover(FileNamePattern fileNamePattern, RollingCalendar rc) { + super(fileNamePattern, rc); } - if (parentClean) { - removeFolderIfEmpty(parentDir); - } - } + public void cleanByPeriodOffset(Date now, int periodOffset) { + Date dateOfPeriodToClean = rc.getEndOfNextNthPeriod(now, periodOffset); + + String regex = fileNamePattern.toRegexForFixedDate(dateOfPeriodToClean); + String stemRegex = FileFilterUtil.afterLastSlash(regex); + File archive0 = new File(fileNamePattern.convertMultipleArguments(dateOfPeriodToClean, 0)); + // in case the file has no directory part, i.e. if it's written into the + // user's current directory. + archive0 = archive0.getAbsoluteFile(); + + File parentDir = archive0.getAbsoluteFile().getParentFile(); + File[] matchingFileArray = FileFilterUtil.filesInFolderMatchingStemRegex(parentDir, stemRegex); + for (File f : matchingFileArray) { + Date fileLastModified = rc.getEndOfNextNthPeriod(new Date(f.lastModified()), -1); + + if (fileLastModified.compareTo(dateOfPeriodToClean) <= 0) { + addInfo("deleting " + f); + f.delete(); + } + } + + if (parentClean) { + removeFolderIfEmpty(parentDir); + } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TimeBasedArchiveRemover.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TimeBasedArchiveRemover.java index 7c8a8a9159c8912dd5c63e465e53e6b87c11764c..1911b63cf6dc8997716b0120e73ff6489e32fdce 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TimeBasedArchiveRemover.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TimeBasedArchiveRemover.java @@ -18,31 +18,30 @@ import java.util.Date; public class TimeBasedArchiveRemover extends DefaultArchiveRemover { - public TimeBasedArchiveRemover(FileNamePattern fileNamePattern, - RollingCalendar rc) { - super(fileNamePattern, rc); - } - - protected void cleanByPeriodOffset(Date now, int periodOffset) { - Date date2delete = rc.getEndOfNextNthPeriod(now, periodOffset); - String filename = fileNamePattern.convert(date2delete); - File file2Delete = new File(filename); - if (file2Delete.exists() && file2Delete.isFile()) { - Date fileLastModified = rc.getEndOfNextNthPeriod(new Date(file2Delete.lastModified()), -1); - - if (fileLastModified.compareTo(date2delete) <= 0) { - addInfo("deleting " + file2Delete); - file2Delete.delete(); - - if (parentClean) { - removeFolderIfEmpty(file2Delete.getParentFile()); - } - } + public TimeBasedArchiveRemover(FileNamePattern fileNamePattern, RollingCalendar rc) { + super(fileNamePattern, rc); + } + + protected void cleanByPeriodOffset(Date now, int periodOffset) { + Date date2delete = rc.getEndOfNextNthPeriod(now, periodOffset); + String filename = fileNamePattern.convert(date2delete); + File file2Delete = new File(filename); + if (file2Delete.exists() && file2Delete.isFile()) { + Date fileLastModified = rc.getEndOfNextNthPeriod(new Date(file2Delete.lastModified()), -1); + + if (fileLastModified.compareTo(date2delete) <= 0) { + addInfo("deleting " + file2Delete); + file2Delete.delete(); + if (parentClean) { + removeFolderIfEmpty(file2Delete.getParentFile()); + } + } + + } } - } - public String toString() { - return "c.q.l.core.rolling.helper.TimeBasedArchiveRemover"; - } + public String toString() { + return "c.q.l.core.rolling.helper.TimeBasedArchiveRemover"; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TokenConverter.java b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TokenConverter.java index 19af46d46d5ac215b0c5c1c2821a7340f83c45f3..aa4daa508cd9a2482f51d895ed0bfe3fb736e47b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TokenConverter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/rolling/helper/TokenConverter.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.rolling.helper; - /** * TokenConverter offers some basic functionality used by more * specific token converters. @@ -25,32 +24,31 @@ package ch.qos.logback.core.rolling.helper; * @since 1.3 */ public class TokenConverter { - - - static final int IDENTITY = 0; - static final int INTEGER = 1; - static final int DATE = 1; - int type; - TokenConverter next; - - protected TokenConverter(int t) { - type = t; - } - - public TokenConverter getNext() { - return next; - } - - public void setNext(TokenConverter next) { - this.next = next; - } - - public int getType() { - return type; - } - - public void setType(int i) { - type = i; - } + + static final int IDENTITY = 0; + static final int INTEGER = 1; + static final int DATE = 1; + int type; + TokenConverter next; + + protected TokenConverter(int t) { + type = t; + } + + public TokenConverter getNext() { + return next; + } + + public void setNext(TokenConverter next) { + this.next = next; + } + + public int getType() { + return type; + } + + public void setType(int i) { + type = i; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractAppenderFactoryUsingJoran.java b/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractAppenderFactoryUsingJoran.java index 981b674879e08c71b5b48aa976d25413b49fff24..60e18a6cac18adb88edee6d946a83fda38e22473 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractAppenderFactoryUsingJoran.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractAppenderFactoryUsingJoran.java @@ -28,32 +28,32 @@ import ch.qos.logback.core.joran.spi.JoranException; */ public abstract class AbstractAppenderFactoryUsingJoran implements AppenderFactory { - final List eventList; - protected String key; - protected Map parentPropertyMap; - - protected AbstractAppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { - this.eventList = removeSiftElement(eventList); - this.key = key; - this.parentPropertyMap = parentPropertyMap; - - } - - List removeSiftElement(List eventList) { - return eventList.subList(1, eventList.size() - 1); - } - - public abstract SiftingJoranConfiguratorBase getSiftingJoranConfigurator(String k); - - public Appender buildAppender(Context context, String discriminatingValue) throws JoranException { - SiftingJoranConfiguratorBase sjc = getSiftingJoranConfigurator(discriminatingValue); - sjc.setContext(context); - sjc.doConfigure(eventList); - return sjc.getAppender(); - } - - public List getEventList() { - return eventList; - } + final List eventList; + protected String key; + protected Map parentPropertyMap; + + protected AbstractAppenderFactoryUsingJoran(List eventList, String key, Map parentPropertyMap) { + this.eventList = removeSiftElement(eventList); + this.key = key; + this.parentPropertyMap = parentPropertyMap; + + } + + List removeSiftElement(List eventList) { + return eventList.subList(1, eventList.size() - 1); + } + + public abstract SiftingJoranConfiguratorBase getSiftingJoranConfigurator(String k); + + public Appender buildAppender(Context context, String discriminatingValue) throws JoranException { + SiftingJoranConfiguratorBase sjc = getSiftingJoranConfigurator(discriminatingValue); + sjc.setContext(context); + sjc.doConfigure(eventList); + return sjc.getAppender(); + } + + public List getEventList() { + return eventList; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractDiscriminator.java b/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractDiscriminator.java index 860f7a5e55db6ba280534dfcca0e6c77443c7c9d..a8c634a38e1337eadae2cc9756f961e84013435e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractDiscriminator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/AbstractDiscriminator.java @@ -23,17 +23,17 @@ import ch.qos.logback.core.spi.ContextAwareBase; */ public abstract class AbstractDiscriminator extends ContextAwareBase implements Discriminator { - protected boolean started; + protected boolean started; - public void start() { - started = true; - } + public void start() { + started = true; + } - public void stop() { - started = false; - } + public void stop() { + started = false; + } - public boolean isStarted() { - return started; - } + public boolean isStarted() { + return started; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderFactory.java b/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderFactory.java index 06acdbcfb761bf64d91dd4c37580d724d1aca5f3..fcc916caa53ec936d21aae89ae11461fb9041d7c 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderFactory.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderFactory.java @@ -25,5 +25,5 @@ import ch.qos.logback.core.joran.spi.JoranException; * To change this template use File | Settings | File Templates. */ public interface AppenderFactory { - Appender buildAppender(Context context, String discriminatingValue) throws JoranException; + Appender buildAppender(Context context, String discriminatingValue) throws JoranException; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderTracker.java b/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderTracker.java index e88a658405826e03c7f55fd591509641e364ac53..acb9752bec4bda13986b8b7d712c7adad5a651d9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderTracker.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/AppenderTracker.java @@ -31,54 +31,53 @@ import ch.qos.logback.core.spi.ContextAwareImpl; */ public class AppenderTracker extends AbstractComponentTracker> { - int nopaWarningCount = 0; + int nopaWarningCount = 0; - final Context context; - final AppenderFactory appenderFactory; - final ContextAwareImpl contextAware; + final Context context; + final AppenderFactory appenderFactory; + final ContextAwareImpl contextAware; - public AppenderTracker(Context context, AppenderFactory appenderFactory) { - super(); - this.context = context; - this.appenderFactory = appenderFactory; - this.contextAware = new ContextAwareImpl(context, this); - } + public AppenderTracker(Context context, AppenderFactory appenderFactory) { + super(); + this.context = context; + this.appenderFactory = appenderFactory; + this.contextAware = new ContextAwareImpl(context, this); + } + @Override + protected void processPriorToRemoval(Appender component) { + component.stop(); + } - @Override - protected void processPriorToRemoval(Appender component) { - component.stop(); - } + @Override + protected Appender buildComponent(String key) { + Appender appender = null; + try { + appender = appenderFactory.buildAppender(context, key); + } catch (JoranException je) { + contextAware.addError("Error while building appender with discriminating value [" + key + "]"); + } + if (appender == null) { + appender = buildNOPAppender(key); + } - @Override - protected Appender buildComponent(String key) { - Appender appender = null; - try { - appender = appenderFactory.buildAppender(context, key); - } catch (JoranException je) { - contextAware.addError("Error while building appender with discriminating value [" + key + "]"); - } - if (appender == null) { - appender = buildNOPAppender(key); + return appender; } - return appender; - } - - private NOPAppender buildNOPAppender(String key) { - if (nopaWarningCount < CoreConstants.MAX_ERROR_COUNT) { - nopaWarningCount++; - contextAware.addError("Building NOPAppender for discriminating value [" + key + "]"); + private NOPAppender buildNOPAppender(String key) { + if (nopaWarningCount < CoreConstants.MAX_ERROR_COUNT) { + nopaWarningCount++; + contextAware.addError("Building NOPAppender for discriminating value [" + key + "]"); + } + NOPAppender nopa = new NOPAppender(); + nopa.setContext(context); + nopa.start(); + return nopa; } - NOPAppender nopa = new NOPAppender(); - nopa.setContext(context); - nopa.start(); - return nopa; - } - @Override - protected boolean isComponentStale(Appender appender) { - return !appender.isStarted(); - } + @Override + protected boolean isComponentStale(Appender appender) { + return !appender.isStarted(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/DefaultDiscriminator.java b/logback-core/src/main/java/ch/qos/logback/core/sift/DefaultDiscriminator.java index 8dc86a9e733a8cfb8f5e11ff2ab19aeb1b27f9e6..7c94ac053d7c767aa1058ae9a077ce91f7b01f98 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/DefaultDiscriminator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/DefaultDiscriminator.java @@ -13,20 +13,19 @@ */ package ch.qos.logback.core.sift; - /** * @author Ceki Gücü */ public class DefaultDiscriminator extends AbstractDiscriminator { - static public final String DEFAULT = "default"; + static public final String DEFAULT = "default"; - public String getDiscriminatingValue(E e) { - return DEFAULT; - } + public String getDiscriminatingValue(E e) { + return DEFAULT; + } - public String getKey() { - return DEFAULT; - } + public String getKey() { + return DEFAULT; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/Discriminator.java b/logback-core/src/main/java/ch/qos/logback/core/sift/Discriminator.java index 13ce962e857b2557a0d4b93f26beab658b2dc28d..18be83447c0d6f7bf1657a17f18b32ff2807b83f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/Discriminator.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/Discriminator.java @@ -27,20 +27,20 @@ import ch.qos.logback.core.spi.LifeCycle; * @param */ public interface Discriminator extends LifeCycle { - - /** - * Given event 'e' return a discriminating value. - * - * @param e - * @return - */ - String getDiscriminatingValue(E e); - /** - * The key or variable name under which the discriminating value should be - * exported into the host environment. - * - * @return - */ - String getKey(); + /** + * Given event 'e' return a discriminating value. + * + * @param e + * @return + */ + String getDiscriminatingValue(E e); + + /** + * The key or variable name under which the discriminating value should be + * exported into the host environment. + * + * @return + */ + String getKey(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingAppenderBase.java b/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingAppenderBase.java index 61052c2e46c18cfdebedcf8f42690993c0c202dd..9880e74467d8a0be8caa6cb0b8e774833a7775ed 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingAppenderBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingAppenderBase.java @@ -27,119 +27,117 @@ import ch.qos.logback.core.util.Duration; * * @author Ceki Gulcu */ -public abstract class SiftingAppenderBase extends - AppenderBase { - - protected AppenderTracker appenderTracker; - AppenderFactory appenderFactory; - Duration timeout = new Duration(AppenderTracker.DEFAULT_TIMEOUT); - int maxAppenderCount = AppenderTracker.DEFAULT_MAX_COMPONENTS; - - Discriminator discriminator; - - public Duration getTimeout() { - return timeout; - } - - public void setTimeout(Duration timeout) { - this.timeout = timeout; - } - - public int getMaxAppenderCount() { - return maxAppenderCount; - } - - public void setMaxAppenderCount(int maxAppenderCount) { - this.maxAppenderCount = maxAppenderCount; - } - - /** - * This setter is intended to be invoked by SiftAction. Customers have no reason to invoke - * this method directly. - */ - public void setAppenderFactory(AppenderFactory appenderFactory) { - this.appenderFactory = appenderFactory; - } - - @Override - public void start() { - int errors = 0; - if (discriminator == null) { - addError("Missing discriminator. Aborting"); - errors++; +public abstract class SiftingAppenderBase extends AppenderBase { + + protected AppenderTracker appenderTracker; + AppenderFactory appenderFactory; + Duration timeout = new Duration(AppenderTracker.DEFAULT_TIMEOUT); + int maxAppenderCount = AppenderTracker.DEFAULT_MAX_COMPONENTS; + + Discriminator discriminator; + + public Duration getTimeout() { + return timeout; } - if (!discriminator.isStarted()) { - addError("Discriminator has not started successfully. Aborting"); - errors++; + + public void setTimeout(Duration timeout) { + this.timeout = timeout; } - if (appenderFactory == null) { - addError("AppenderFactory has not been set. Aborting"); - errors++; - } else { - appenderTracker = new AppenderTracker(context, appenderFactory); - appenderTracker.setMaxComponents(maxAppenderCount); - appenderTracker.setTimeout(timeout.getMilliseconds()); + + public int getMaxAppenderCount() { + return maxAppenderCount; } - if (errors == 0) { - super.start(); + + public void setMaxAppenderCount(int maxAppenderCount) { + this.maxAppenderCount = maxAppenderCount; } - } - @Override - public void stop() { - for (Appender appender : appenderTracker.allComponents()) { - appender.stop(); + /** + * This setter is intended to be invoked by SiftAction. Customers have no reason to invoke + * this method directly. + */ + public void setAppenderFactory(AppenderFactory appenderFactory) { + this.appenderFactory = appenderFactory; } - } - abstract protected long getTimestamp(E event); + @Override + public void start() { + int errors = 0; + if (discriminator == null) { + addError("Missing discriminator. Aborting"); + errors++; + } + if (!discriminator.isStarted()) { + addError("Discriminator has not started successfully. Aborting"); + errors++; + } + if (appenderFactory == null) { + addError("AppenderFactory has not been set. Aborting"); + errors++; + } else { + appenderTracker = new AppenderTracker(context, appenderFactory); + appenderTracker.setMaxComponents(maxAppenderCount); + appenderTracker.setTimeout(timeout.getMilliseconds()); + } + if (errors == 0) { + super.start(); + } + } - @Override - protected void append(E event) { - if (!isStarted()) { - return; + @Override + public void stop() { + for (Appender appender : appenderTracker.allComponents()) { + appender.stop(); + } } - String discriminatingValue = discriminator.getDiscriminatingValue(event); - long timestamp = getTimestamp(event); - Appender appender = appenderTracker.getOrCreate(discriminatingValue, timestamp); - // marks the appender for removal as specified by the user - if (eventMarksEndOfLife(event)) { - appenderTracker.endOfLife(discriminatingValue); + abstract protected long getTimestamp(E event); + + @Override + protected void append(E event) { + if (!isStarted()) { + return; + } + String discriminatingValue = discriminator.getDiscriminatingValue(event); + long timestamp = getTimestamp(event); + + Appender appender = appenderTracker.getOrCreate(discriminatingValue, timestamp); + // marks the appender for removal as specified by the user + if (eventMarksEndOfLife(event)) { + appenderTracker.endOfLife(discriminatingValue); + } + appenderTracker.removeStaleComponents(timestamp); + appender.doAppend(event); } - appenderTracker.removeStaleComponents(timestamp); - appender.doAppend(event); - } - - protected abstract boolean eventMarksEndOfLife(E event); - - public Discriminator getDiscriminator() { - return discriminator; - } - - public void setDiscriminator(Discriminator discriminator) { - this.discriminator = discriminator; - } - - - // sometimes one needs to close a nested appender immediately - // for example when executing a command which has its own nested appender - // and the command also cleans up after itself. However, an open file appender - // will prevent the folder from being deleted - // see http://www.qos.ch/pipermail/logback-user/2010-March/001487.html - - /** - * @since 0.9.19 - */ - public AppenderTracker getAppenderTracker() { - return appenderTracker; - } - - public String getDiscriminatorKey() { - if (discriminator != null) { - return discriminator.getKey(); - } else { - return null; + + protected abstract boolean eventMarksEndOfLife(E event); + + public Discriminator getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(Discriminator discriminator) { + this.discriminator = discriminator; + } + + // sometimes one needs to close a nested appender immediately + // for example when executing a command which has its own nested appender + // and the command also cleans up after itself. However, an open file appender + // will prevent the folder from being deleted + // see http://www.qos.ch/pipermail/logback-user/2010-March/001487.html + + /** + * @since 0.9.19 + */ + public AppenderTracker getAppenderTracker() { + return appenderTracker; + } + + public String getDiscriminatorKey() { + if (discriminator != null) { + return discriminator.getKey(); + } else { + return null; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingJoranConfiguratorBase.java b/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingJoranConfiguratorBase.java index 3f2b8e748d7aaaa41267a74ee525510cc889eef9..6bb81e4d765529370e6e5fa448b57ae68007620b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingJoranConfiguratorBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/sift/SiftingJoranConfiguratorBase.java @@ -26,67 +26,64 @@ import ch.qos.logback.core.joran.spi.Interpreter; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.joran.spi.RuleStore; -public abstract class SiftingJoranConfiguratorBase extends - GenericConfigurator { +public abstract class SiftingJoranConfiguratorBase extends GenericConfigurator { - protected final String key; - protected final String value; - // properties inherited from the main joran run - protected final Map parentPropertyMap; + protected final String key; + protected final String value; + // properties inherited from the main joran run + protected final Map parentPropertyMap; - protected SiftingJoranConfiguratorBase(String key, String value, Map parentPropertyMap) { - this.key = key; - this.value = value; - this.parentPropertyMap = parentPropertyMap; - } + protected SiftingJoranConfiguratorBase(String key, String value, Map parentPropertyMap) { + this.key = key; + this.value = value; + this.parentPropertyMap = parentPropertyMap; + } + + final static String ONE_AND_ONLY_ONE_URL = CoreConstants.CODES_URL + "#1andOnly1"; - final static String ONE_AND_ONLY_ONE_URL = CoreConstants.CODES_URL - + "#1andOnly1"; + @Override + protected void addImplicitRules(Interpreter interpreter) { + NestedComplexPropertyIA nestedComplexIA = new NestedComplexPropertyIA(); + nestedComplexIA.setContext(context); + interpreter.addImplicitAction(nestedComplexIA); - @Override - protected void addImplicitRules(Interpreter interpreter) { - NestedComplexPropertyIA nestedComplexIA = new NestedComplexPropertyIA(); - nestedComplexIA.setContext(context); - interpreter.addImplicitAction(nestedComplexIA); + NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); + nestedSimpleIA.setContext(context); + interpreter.addImplicitAction(nestedSimpleIA); + } - NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); - nestedSimpleIA.setContext(context); - interpreter.addImplicitAction(nestedSimpleIA); - } + @Override + protected void addInstanceRules(RuleStore rs) { + rs.addRule(new ElementSelector("configuration/property"), new PropertyAction()); + rs.addRule(new ElementSelector("configuration/timestamp"), new TimestampAction()); + rs.addRule(new ElementSelector("configuration/define"), new DefinePropertyAction()); + } - @Override - protected void addInstanceRules(RuleStore rs) { - rs.addRule(new ElementSelector("configuration/property"), new PropertyAction()); - rs.addRule(new ElementSelector("configuration/timestamp"), new TimestampAction()); - rs.addRule(new ElementSelector("configuration/define"), new DefinePropertyAction()); - } + abstract public Appender getAppender(); - abstract public Appender getAppender(); + int errorEmmissionCount = 0; - int errorEmmissionCount = 0; + protected void oneAndOnlyOneCheck(Map appenderMap) { + String errMsg = null; + if (appenderMap.size() == 0) { + errorEmmissionCount++; + errMsg = "No nested appenders found within the element in SiftingAppender."; + } else if (appenderMap.size() > 1) { + errorEmmissionCount++; + errMsg = "Only and only one appender can be nested the element in SiftingAppender. See also " + ONE_AND_ONLY_ONE_URL; + } - protected void oneAndOnlyOneCheck(Map appenderMap) { - String errMsg = null; - if (appenderMap.size() == 0) { - errorEmmissionCount++; - errMsg = "No nested appenders found within the element in SiftingAppender."; - } else if (appenderMap.size() > 1) { - errorEmmissionCount++; - errMsg = "Only and only one appender can be nested the element in SiftingAppender. See also " - + ONE_AND_ONLY_ONE_URL; + if (errMsg != null && errorEmmissionCount < CoreConstants.MAX_ERROR_COUNT) { + addError(errMsg); + } } - if (errMsg != null && errorEmmissionCount < CoreConstants.MAX_ERROR_COUNT) { - addError(errMsg); + public void doConfigure(final List eventList) throws JoranException { + super.doConfigure(eventList); } - } - - public void doConfigure(final List eventList) throws JoranException { - super.doConfigure(eventList); - } - @Override - public String toString() { - return this.getClass().getName() + "{" + key + "=" + value + '}'; - } + @Override + public String toString() { + return this.getClass().getName() + "{" + key + "=" + value + '}'; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/AbstractComponentTracker.java b/logback-core/src/main/java/ch/qos/logback/core/spi/AbstractComponentTracker.java index 80707667178151ff6f7552ccaf3d90ddf3e201ad..ae934627f5df57f6c1f82f997c4e9ba322537d44 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/AbstractComponentTracker.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/AbstractComponentTracker.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.spi; - import ch.qos.logback.core.CoreConstants; import java.util.*; @@ -30,281 +29,283 @@ import java.util.*; * @author David Roussel */ abstract public class AbstractComponentTracker implements ComponentTracker { - private static final boolean ACCESS_ORDERED = true; - - // Components in lingering state last 10 seconds - final public static long LINGERING_TIMEOUT = 10 * CoreConstants.MILLIS_IN_ONE_SECOND; - - /** - * The minimum amount of time that has to elapse between successive removal iterations. - */ - final public static long WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS = CoreConstants.MILLIS_IN_ONE_SECOND; - - protected int maxComponents = DEFAULT_MAX_COMPONENTS; - protected long timeout = DEFAULT_TIMEOUT; - - // an access ordered map. Least recently accessed element will be removed after a 'timeout' - LinkedHashMap> liveMap = new LinkedHashMap>(32, .75f, ACCESS_ORDERED); - - // an access ordered map. Least recently accessed element will be removed after LINGERING_TIMEOUT - LinkedHashMap> lingerersMap = new LinkedHashMap>(16, .75f, ACCESS_ORDERED); - long lastCheck = 0; - - /** - * Stop or clean the component. - * - * @param component - */ - abstract protected void processPriorToRemoval(C component); - - /** - * Build a component based on the key. - * - * @param key - * @return - */ - abstract protected C buildComponent(String key); - - /** - * Components can declare themselves stale. Such components may be - * removed before they time out. - * - * @param c - * @return - */ - protected abstract boolean isComponentStale(C c); - - - public int getComponentCount() { - return liveMap.size() + lingerersMap.size(); - } - - /** - * Get an entry from the liveMap, if not found search the lingerersMap. - * - * @param key - * @return - */ - private Entry getFromEitherMap(String key) { - Entry entry = liveMap.get(key); - if (entry != null) - return entry; - else { - return lingerersMap.get(key); + private static final boolean ACCESS_ORDERED = true; + + // Components in lingering state last 10 seconds + final public static long LINGERING_TIMEOUT = 10 * CoreConstants.MILLIS_IN_ONE_SECOND; + + /** + * The minimum amount of time that has to elapse between successive removal iterations. + */ + final public static long WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS = CoreConstants.MILLIS_IN_ONE_SECOND; + + protected int maxComponents = DEFAULT_MAX_COMPONENTS; + protected long timeout = DEFAULT_TIMEOUT; + + // an access ordered map. Least recently accessed element will be removed after a 'timeout' + LinkedHashMap> liveMap = new LinkedHashMap>(32, .75f, ACCESS_ORDERED); + + // an access ordered map. Least recently accessed element will be removed after LINGERING_TIMEOUT + LinkedHashMap> lingerersMap = new LinkedHashMap>(16, .75f, ACCESS_ORDERED); + long lastCheck = 0; + + /** + * Stop or clean the component. + * + * @param component + */ + abstract protected void processPriorToRemoval(C component); + + /** + * Build a component based on the key. + * + * @param key + * @return + */ + abstract protected C buildComponent(String key); + + /** + * Components can declare themselves stale. Such components may be + * removed before they time out. + * + * @param c + * @return + */ + protected abstract boolean isComponentStale(C c); + + public int getComponentCount() { + return liveMap.size() + lingerersMap.size(); } - } - - /** - * {@inheritDoc} - * - *

Note that this method is synchronized.

- * - * @param key {@inheritDoc} - * @return {@inheritDoc} - * - */ - public synchronized C find(String key) { - Entry entry = getFromEitherMap(key); - if (entry == null) return null; - else return entry.component; - } - - /** - * {@inheritDoc} - * - *

Note that this method is atomic, i.e. synchronized.

- * - * @param key {@inheritDoc} - * @param timestamp {@inheritDoc} - * @return {@inheritDoc} - */ - public synchronized C getOrCreate(String key, long timestamp) { - Entry entry = getFromEitherMap(key); - if (entry == null) { - C c = buildComponent(key); - entry = new Entry(key, c, timestamp); - // new entries go into the main map - liveMap.put(key, entry); - } else { - entry.setTimestamp(timestamp); + + /** + * Get an entry from the liveMap, if not found search the lingerersMap. + * + * @param key + * @return + */ + private Entry getFromEitherMap(String key) { + Entry entry = liveMap.get(key); + if (entry != null) + return entry; + else { + return lingerersMap.get(key); + } } - return entry.component; - } - - /** - * Mark component identified by 'key' as having reached its end-of-life. - * - * @param key - */ - public void endOfLife(String key) { - Entry entry = liveMap.remove(key); - if (entry == null) - return; - lingerersMap.put(key, entry); - } - - /** - * Clear (and detach) components which are stale. Components which have not - * been accessed for more than a user-specified duration are deemed stale. - * - * @param now - */ - public synchronized void removeStaleComponents(long now) { - if (isTooSoonForRemovalIteration(now)) return; - removeExcedentComponents(); - removeStaleComponentsFromMainMap(now); - removeStaleComponentsFromLingerersMap(now); - } - - private void removeExcedentComponents() { - genericStaleComponentRemover(liveMap, 0, byExcedent); - } - - private void removeStaleComponentsFromMainMap(long now) { - genericStaleComponentRemover(liveMap, now, byTimeout); - } - - private void removeStaleComponentsFromLingerersMap(long now) { - genericStaleComponentRemover(lingerersMap, now, byLingering); - } - - private void genericStaleComponentRemover(LinkedHashMap> map, long now, - RemovalPredicator removalPredicator) { - Iterator>> iter = map.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry> mapEntry = iter.next(); - Entry entry = mapEntry.getValue(); - if (removalPredicator.isSlatedForRemoval(entry, now)) { - iter.remove(); - C c = entry.component; - processPriorToRemoval(c); - } else { - break; - } + + /** + * {@inheritDoc} + * + *

Note that this method is synchronized.

+ * + * @param key {@inheritDoc} + * @return {@inheritDoc} + * + */ + public synchronized C find(String key) { + Entry entry = getFromEitherMap(key); + if (entry == null) + return null; + else + return entry.component; } - } - private RemovalPredicator byExcedent = new RemovalPredicator() { - public boolean isSlatedForRemoval(Entry entry, long timestamp) { - return (liveMap.size() > maxComponents); + /** + * {@inheritDoc} + * + *

Note that this method is atomic, i.e. synchronized.

+ * + * @param key {@inheritDoc} + * @param timestamp {@inheritDoc} + * @return {@inheritDoc} + */ + public synchronized C getOrCreate(String key, long timestamp) { + Entry entry = getFromEitherMap(key); + if (entry == null) { + C c = buildComponent(key); + entry = new Entry(key, c, timestamp); + // new entries go into the main map + liveMap.put(key, entry); + } else { + entry.setTimestamp(timestamp); + } + return entry.component; } - }; - private RemovalPredicator byTimeout = new RemovalPredicator() { - public boolean isSlatedForRemoval(Entry entry, long timestamp) { - return isEntryStale(entry, timestamp); + /** + * Mark component identified by 'key' as having reached its end-of-life. + * + * @param key + */ + public void endOfLife(String key) { + Entry entry = liveMap.remove(key); + if (entry == null) + return; + lingerersMap.put(key, entry); } - }; - private RemovalPredicator byLingering = new RemovalPredicator() { - public boolean isSlatedForRemoval(Entry entry, long timestamp) { - return isEntryDoneLingering(entry, timestamp); + + /** + * Clear (and detach) components which are stale. Components which have not + * been accessed for more than a user-specified duration are deemed stale. + * + * @param now + */ + public synchronized void removeStaleComponents(long now) { + if (isTooSoonForRemovalIteration(now)) + return; + removeExcedentComponents(); + removeStaleComponentsFromMainMap(now); + removeStaleComponentsFromLingerersMap(now); } - }; - private boolean isTooSoonForRemovalIteration(long now) { - if (lastCheck + WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS > now) { - return true; + private void removeExcedentComponents() { + genericStaleComponentRemover(liveMap, 0, byExcedent); } - lastCheck = now; - return false; - } - - private boolean isEntryStale(Entry entry, long now) { - // stopped or improperly started appenders are considered stale - // see also http://jira.qos.ch/browse/LBCLASSIC-316 - C c = entry.component; - if (isComponentStale(c)) - return true; - - return ((entry.timestamp + timeout) < now); - } - - private boolean isEntryDoneLingering(Entry entry, long now) { - return ((entry.timestamp + LINGERING_TIMEOUT) < now); - } - - public Set allKeys() { - HashSet allKeys = new HashSet(liveMap.keySet()); - allKeys.addAll(lingerersMap.keySet()); - return allKeys; - } - - public Collection allComponents() { - List allComponents = new ArrayList(); - for (Entry e : liveMap.values()) - allComponents.add(e.component); - for (Entry e : lingerersMap.values()) - allComponents.add(e.component); - - return allComponents; - } - - public long getTimeout() { - return timeout; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } - - public int getMaxComponents() { - return maxComponents; - } - - public void setMaxComponents(int maxComponents) { - this.maxComponents = maxComponents; - } - - // ================================================================ - private interface RemovalPredicator { - boolean isSlatedForRemoval(Entry entry, long timestamp); - } - // ================================================================ - private static class Entry { - String key; - C component; - long timestamp; - - Entry(String k, C c, long timestamp) { - this.key = k; - this.component = c; - this.timestamp = timestamp; + + private void removeStaleComponentsFromMainMap(long now) { + genericStaleComponentRemover(liveMap, now, byTimeout); } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; + private void removeStaleComponentsFromLingerersMap(long now) { + genericStaleComponentRemover(lingerersMap, now, byLingering); } - @Override - public int hashCode() { - return key.hashCode(); + private void genericStaleComponentRemover(LinkedHashMap> map, long now, RemovalPredicator removalPredicator) { + Iterator>> iter = map.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry> mapEntry = iter.next(); + Entry entry = mapEntry.getValue(); + if (removalPredicator.isSlatedForRemoval(entry, now)) { + iter.remove(); + C c = entry.component; + processPriorToRemoval(c); + } else { + break; + } + } } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Entry other = (Entry) obj; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) + private RemovalPredicator byExcedent = new RemovalPredicator() { + public boolean isSlatedForRemoval(Entry entry, long timestamp) { + return (liveMap.size() > maxComponents); + } + }; + + private RemovalPredicator byTimeout = new RemovalPredicator() { + public boolean isSlatedForRemoval(Entry entry, long timestamp) { + return isEntryStale(entry, timestamp); + } + }; + private RemovalPredicator byLingering = new RemovalPredicator() { + public boolean isSlatedForRemoval(Entry entry, long timestamp) { + return isEntryDoneLingering(entry, timestamp); + } + }; + + private boolean isTooSoonForRemovalIteration(long now) { + if (lastCheck + WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS > now) { + return true; + } + lastCheck = now; return false; - if (component == null) { - if (other.component != null) - return false; - } else if (!component.equals(other.component)) - return false; - return true; } - @Override - public String toString() { - return "(" + key + ", " + component + ")"; + private boolean isEntryStale(Entry entry, long now) { + // stopped or improperly started appenders are considered stale + // see also http://jira.qos.ch/browse/LBCLASSIC-316 + C c = entry.component; + if (isComponentStale(c)) + return true; + + return ((entry.timestamp + timeout) < now); + } + + private boolean isEntryDoneLingering(Entry entry, long now) { + return ((entry.timestamp + LINGERING_TIMEOUT) < now); + } + + public Set allKeys() { + HashSet allKeys = new HashSet(liveMap.keySet()); + allKeys.addAll(lingerersMap.keySet()); + return allKeys; + } + + public Collection allComponents() { + List allComponents = new ArrayList(); + for (Entry e : liveMap.values()) + allComponents.add(e.component); + for (Entry e : lingerersMap.values()) + allComponents.add(e.component); + + return allComponents; + } + + public long getTimeout() { + return timeout; + } + + public void setTimeout(long timeout) { + this.timeout = timeout; + } + + public int getMaxComponents() { + return maxComponents; + } + + public void setMaxComponents(int maxComponents) { + this.maxComponents = maxComponents; + } + + // ================================================================ + private interface RemovalPredicator { + boolean isSlatedForRemoval(Entry entry, long timestamp); + } + + // ================================================================ + private static class Entry { + String key; + C component; + long timestamp; + + Entry(String k, C c, long timestamp) { + this.key = k; + this.component = c; + this.timestamp = timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Entry other = (Entry) obj; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (component == null) { + if (other.component != null) + return false; + } else if (!component.equals(other.component)) + return false; + return true; + } + + @Override + public String toString() { + return "(" + key + ", " + component + ")"; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachable.java b/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachable.java index 125b0690b622884e010755c689c8280db5e6cef6..f805d36384e0dce774be315b9ab744b5026c362e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachable.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachable.java @@ -23,40 +23,40 @@ import ch.qos.logback.core.Appender; * @author Ceki Gülcü */ public interface AppenderAttachable { - /** - * Add an appender. - */ - void addAppender(Appender newAppender); - - /** - * Get an iterator for appenders contained in the parent object. - */ - Iterator> iteratorForAppenders(); - - /** - * Get an appender by name. - */ - Appender getAppender(String name); - - /** - * Returns true if the specified appender is in list of - * attached attached, false otherwise. - */ - boolean isAttached(Appender appender); - - /** - * Detach and processPriorToRemoval all previously added appenders. - */ - void detachAndStopAllAppenders(); - - /** - * Detach the appender passed as parameter from the list of appenders. - */ - boolean detachAppender(Appender appender); - - /** - * Detach the appender with the name passed as parameter from the list of - * appenders. - */ - boolean detachAppender(String name); + /** + * Add an appender. + */ + void addAppender(Appender newAppender); + + /** + * Get an iterator for appenders contained in the parent object. + */ + Iterator> iteratorForAppenders(); + + /** + * Get an appender by name. + */ + Appender getAppender(String name); + + /** + * Returns true if the specified appender is in list of + * attached attached, false otherwise. + */ + boolean isAttached(Appender appender); + + /** + * Detach and processPriorToRemoval all previously added appenders. + */ + void detachAndStopAllAppenders(); + + /** + * Detach the appender passed as parameter from the list of appenders. + */ + boolean detachAppender(Appender appender); + + /** + * Detach the appender with the name passed as parameter from the list of + * appenders. + */ + boolean detachAppender(String name); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachableImpl.java b/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachableImpl.java index 0ac3cdc43ac5f1347f7d22b69a7db24a42ce3102..4c09ccc277c5d32d4881b23ca2286e7acb80c576 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachableImpl.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/AppenderAttachableImpl.java @@ -26,115 +26,116 @@ import ch.qos.logback.core.Appender; */ public class AppenderAttachableImpl implements AppenderAttachable { - final private CopyOnWriteArrayList> appenderList = new CopyOnWriteArrayList>(); + final private CopyOnWriteArrayList> appenderList = new CopyOnWriteArrayList>(); - /** - * Attach an appender. If the appender is already in the list in won't be - * added again. - */ - public void addAppender(Appender newAppender) { - if (newAppender == null) { - throw new IllegalArgumentException("Null argument disallowed"); + /** + * Attach an appender. If the appender is already in the list in won't be + * added again. + */ + public void addAppender(Appender newAppender) { + if (newAppender == null) { + throw new IllegalArgumentException("Null argument disallowed"); + } + appenderList.addIfAbsent(newAppender); } - appenderList.addIfAbsent(newAppender); - } - - /** - * Call the doAppend method on all attached appenders. - */ - public int appendLoopOnAppenders(E e) { - int size = 0; - for (Appender appender : appenderList) { - appender.doAppend(e); - size++; - } - return size; - } - /** - * Get all attached appenders as an Enumeration. If there are no attached - * appenders null is returned. - * - * @return Iterator An iterator of attached appenders. - */ - public Iterator> iteratorForAppenders() { - return appenderList.iterator(); - } - - /** - * Look for an attached appender named as name. - *

- *

Return the appender with that name if in the list. Return null - * otherwise. - */ - public Appender getAppender(String name) { - if (name == null) { - return null; + /** + * Call the doAppend method on all attached appenders. + */ + public int appendLoopOnAppenders(E e) { + int size = 0; + for (Appender appender : appenderList) { + appender.doAppend(e); + size++; + } + return size; } - for (Appender appender : appenderList) { - if (name.equals(appender.getName())) { - return appender; - } + + /** + * Get all attached appenders as an Enumeration. If there are no attached + * appenders null is returned. + * + * @return Iterator An iterator of attached appenders. + */ + public Iterator> iteratorForAppenders() { + return appenderList.iterator(); } - return null; - } - /** - * Returns true if the specified appender is in the list of - * attached appenders, false otherwise. - * - * @since 1.2 - */ - public boolean isAttached(Appender appender) { - if (appender == null) { - return false; + /** + * Look for an attached appender named as name. + *

+ *

Return the appender with that name if in the list. Return null + * otherwise. + */ + public Appender getAppender(String name) { + if (name == null) { + return null; + } + for (Appender appender : appenderList) { + if (name.equals(appender.getName())) { + return appender; + } + } + return null; } - for (Appender a : appenderList) { - if (a == appender) return true; + + /** + * Returns true if the specified appender is in the list of + * attached appenders, false otherwise. + * + * @since 1.2 + */ + public boolean isAttached(Appender appender) { + if (appender == null) { + return false; + } + for (Appender a : appenderList) { + if (a == appender) + return true; + } + return false; } - return false; - } - /** - * Remove and processPriorToRemoval all previously attached appenders. - */ - public void detachAndStopAllAppenders() { - for (Appender a : appenderList) { - a.stop(); + /** + * Remove and processPriorToRemoval all previously attached appenders. + */ + public void detachAndStopAllAppenders() { + for (Appender a : appenderList) { + a.stop(); + } + appenderList.clear(); } - appenderList.clear(); - } - static final long START = System.currentTimeMillis(); + static final long START = System.currentTimeMillis(); - /** - * Remove the appender passed as parameter form the list of attached - * appenders. - */ - public boolean detachAppender(Appender appender) { - if (appender == null) { - return false; + /** + * Remove the appender passed as parameter form the list of attached + * appenders. + */ + public boolean detachAppender(Appender appender) { + if (appender == null) { + return false; + } + boolean result; + result = appenderList.remove(appender); + return result; } - boolean result; - result = appenderList.remove(appender); - return result; - } - /** - * Remove the appender with the name passed as parameter form the list of - * appenders. - */ - public boolean detachAppender(String name) { - if (name == null) { - return false; - } - boolean removed = false; - for (Appender a : appenderList) { - if (name.equals((a).getName())) { - removed = appenderList.remove(a); - break; + /** + * Remove the appender with the name passed as parameter form the list of + * appenders. + */ + public boolean detachAppender(String name) { + if (name == null) { + return false; + } + boolean removed = false; + for (Appender a : appenderList) { + if (name.equals((a).getName())) { + removed = appenderList.remove(a); + break; + } } - } - return removed; - } + return removed; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/ComponentTracker.java b/logback-core/src/main/java/ch/qos/logback/core/spi/ComponentTracker.java index dd7507221a719572970940dfc6a14a6644a2b85c..70321d02b2d8ecf21c7f1f4c3df3ef86359e25e5 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/ComponentTracker.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/ComponentTracker.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.spi; - import ch.qos.logback.core.CoreConstants; import java.util.Collection; @@ -34,77 +33,73 @@ import java.util.Set; */ public interface ComponentTracker { - /** - * The default timeout duration is 30 minutes - */ - public final int DEFAULT_TIMEOUT = (int) (30 * 60 * CoreConstants.MILLIS_IN_ONE_SECOND); // 30 minutes - - /** - * By default an unlimited number of elements can be tracked. - */ - int DEFAULT_MAX_COMPONENTS = Integer.MAX_VALUE; - - /** - * Returns the number of components tracked. - * @return number of components - */ - int getComponentCount(); - - - /** - * Find the component identified by 'key', without updating the timestamp. Returns null if no - * corresponding component could be found. - * - * @param key - * @return corresponding component, may be null - */ - C find(String key); - - /** - * Get the component identified by 'key', updating its timestamp in the - * process. If the corresponding component could not be found, it is created. - * - * @param key - * @param timestamp - * @return - */ - C getOrCreate(String key, long timestamp); - - - /** - * Remove components which are deemed stale. Components which have not - * been accessed for more than a user-specified duration are deemed stale. - * - *

If the number of components exceeds, {@link #getComponentCount()}, - * components in excess will be removed.

- * - *

Depending on the component type, components will be cleared or stopped - * (as appropriate) right before removal.

- * - * @param now current time in milliseconds - */ - void removeStaleComponents(long now); - - - /** - * Mark component identified by 'key' as having reached its end-of-life. End-of-lifed - * components will linger for a few more seconds before being removed. - * - * @param key - */ - void endOfLife(String key); - - /** - * Returns the collection of all components tracked by this instance. - * @return collection of components - */ - Collection allComponents(); - - - /** - * Set of all keys in this tracker in no particular order. - * - * @return - */ - Set allKeys(); + /** + * The default timeout duration is 30 minutes + */ + public final int DEFAULT_TIMEOUT = (int) (30 * 60 * CoreConstants.MILLIS_IN_ONE_SECOND); // 30 minutes + + /** + * By default an unlimited number of elements can be tracked. + */ + int DEFAULT_MAX_COMPONENTS = Integer.MAX_VALUE; + + /** + * Returns the number of components tracked. + * @return number of components + */ + int getComponentCount(); + + /** + * Find the component identified by 'key', without updating the timestamp. Returns null if no + * corresponding component could be found. + * + * @param key + * @return corresponding component, may be null + */ + C find(String key); + + /** + * Get the component identified by 'key', updating its timestamp in the + * process. If the corresponding component could not be found, it is created. + * + * @param key + * @param timestamp + * @return + */ + C getOrCreate(String key, long timestamp); + + /** + * Remove components which are deemed stale. Components which have not + * been accessed for more than a user-specified duration are deemed stale. + * + *

If the number of components exceeds, {@link #getComponentCount()}, + * components in excess will be removed.

+ * + *

Depending on the component type, components will be cleared or stopped + * (as appropriate) right before removal.

+ * + * @param now current time in milliseconds + */ + void removeStaleComponents(long now); + + /** + * Mark component identified by 'key' as having reached its end-of-life. End-of-lifed + * components will linger for a few more seconds before being removed. + * + * @param key + */ + void endOfLife(String key); + + /** + * Returns the collection of all components tracked by this instance. + * @return collection of components + */ + Collection allComponents(); + + /** + * Set of all keys in this tracker in no particular order. + * + * @return + */ + Set allKeys(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAware.java b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAware.java index 3c674e2d8f05c748eb9ced561cccb8ae70a15901..6854ad60a22d8e53424933d85c0a668ca12218e6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAware.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAware.java @@ -16,28 +16,27 @@ package ch.qos.logback.core.spi; import ch.qos.logback.core.Context; import ch.qos.logback.core.status.Status; - /** * An object which has a context and add methods for updating internal status messages. */ public interface ContextAware { - void setContext(Context context); + void setContext(Context context); - Context getContext(); + Context getContext(); - void addStatus(Status status); + void addStatus(Status status); - void addInfo(String msg); + void addInfo(String msg); - void addInfo(String msg, Throwable ex); + void addInfo(String msg, Throwable ex); - void addWarn(String msg); + void addWarn(String msg); - void addWarn(String msg, Throwable ex); + void addWarn(String msg, Throwable ex); - void addError(String msg); + void addError(String msg); - void addError(String msg, Throwable ex); + void addError(String msg, Throwable ex); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareBase.java b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareBase.java index 643806578b662238e148831286d7b46eb8585a0b..051d1f0507b49f58e19daaa143992904fca4d766 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareBase.java @@ -27,80 +27,81 @@ import ch.qos.logback.core.status.WarnStatus; * @author Ceki Gülcü */ public class ContextAwareBase implements ContextAware { - private int noContextWarning = 0; - protected Context context; - final Object declaredOrigin; + private int noContextWarning = 0; + protected Context context; + final Object declaredOrigin; - public ContextAwareBase() { - declaredOrigin = this; - } - public ContextAwareBase(ContextAware declaredOrigin) { - this.declaredOrigin = declaredOrigin; - } + public ContextAwareBase() { + declaredOrigin = this; + } - public void setContext(Context context) { - if (this.context == null) { - this.context = context; - } else if (this.context != context) { - throw new IllegalStateException("Context has been already set"); + public ContextAwareBase(ContextAware declaredOrigin) { + this.declaredOrigin = declaredOrigin; } - } - public Context getContext() { - return this.context; - } + public void setContext(Context context) { + if (this.context == null) { + this.context = context; + } else if (this.context != context) { + throw new IllegalStateException("Context has been already set"); + } + } - public StatusManager getStatusManager() { - if (context == null) { - return null; + public Context getContext() { + return this.context; } - return context.getStatusManager(); - } - /** - * The declared origin of status messages. By default 'this'. Derived classes may override this - * method to declare other origin. - * - * @return the declared origin, by default 'this' - */ - protected Object getDeclaredOrigin() { - return declaredOrigin; - } + public StatusManager getStatusManager() { + if (context == null) { + return null; + } + return context.getStatusManager(); + } - public void addStatus(Status status) { - if (context == null) { - if (noContextWarning++ == 0) { - System.out.println("LOGBACK: No context given for " + this); - } - return; + /** + * The declared origin of status messages. By default 'this'. Derived classes may override this + * method to declare other origin. + * + * @return the declared origin, by default 'this' + */ + protected Object getDeclaredOrigin() { + return declaredOrigin; } - StatusManager sm = context.getStatusManager(); - if (sm != null) { - sm.add(status); + + public void addStatus(Status status) { + if (context == null) { + if (noContextWarning++ == 0) { + System.out.println("LOGBACK: No context given for " + this); + } + return; + } + StatusManager sm = context.getStatusManager(); + if (sm != null) { + sm.add(status); + } } - } - public void addInfo(String msg) { - addStatus(new InfoStatus(msg, getDeclaredOrigin())); - } + public void addInfo(String msg) { + addStatus(new InfoStatus(msg, getDeclaredOrigin())); + } - public void addInfo(String msg, Throwable ex) { - addStatus(new InfoStatus(msg, getDeclaredOrigin(), ex)); - } + public void addInfo(String msg, Throwable ex) { + addStatus(new InfoStatus(msg, getDeclaredOrigin(), ex)); + } - public void addWarn(String msg) { - addStatus(new WarnStatus(msg, getDeclaredOrigin())); - } + public void addWarn(String msg) { + addStatus(new WarnStatus(msg, getDeclaredOrigin())); + } - public void addWarn(String msg, Throwable ex) { - addStatus(new WarnStatus(msg, getDeclaredOrigin(), ex)); - } + public void addWarn(String msg, Throwable ex) { + addStatus(new WarnStatus(msg, getDeclaredOrigin(), ex)); + } - public void addError(String msg) { - addStatus(new ErrorStatus(msg, getDeclaredOrigin())); - } + public void addError(String msg) { + addStatus(new ErrorStatus(msg, getDeclaredOrigin())); + } - public void addError(String msg, Throwable ex) { - addStatus(new ErrorStatus(msg, getDeclaredOrigin(), ex)); - } + public void addError(String msg, Throwable ex) { + addStatus(new ErrorStatus(msg, getDeclaredOrigin(), ex)); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareImpl.java b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareImpl.java index 88851284e961a54c1e6dca69a501522f0eab43b7..1ae51103a023589d6e56daf150a0be6e069eedd5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareImpl.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/ContextAwareImpl.java @@ -20,7 +20,6 @@ import ch.qos.logback.core.status.Status; import ch.qos.logback.core.status.StatusManager; import ch.qos.logback.core.status.WarnStatus; - /** * A helper class that implements ContextAware methods. Use this class to * implement the ContextAware interface by composition. @@ -29,74 +28,74 @@ import ch.qos.logback.core.status.WarnStatus; */ public class ContextAwareImpl implements ContextAware { - private int noContextWarning = 0; - protected Context context; - final Object origin; - - public ContextAwareImpl(Context context, Object origin) { - this.context = context; - this.origin = origin; - - } - - protected Object getOrigin() { - return origin; - } - - public void setContext(Context context) { - if (this.context == null) { - this.context = context; - } else if (this.context != context) { - throw new IllegalStateException("Context has been already set"); + private int noContextWarning = 0; + protected Context context; + final Object origin; + + public ContextAwareImpl(Context context, Object origin) { + this.context = context; + this.origin = origin; + } - } - public Context getContext() { - return this.context; - } + protected Object getOrigin() { + return origin; + } - public StatusManager getStatusManager() { - if (context == null) { - return null; + public void setContext(Context context) { + if (this.context == null) { + this.context = context; + } else if (this.context != context) { + throw new IllegalStateException("Context has been already set"); + } } - return context.getStatusManager(); - } - - public void addStatus(Status status) { - if (context == null) { - if (noContextWarning++ == 0) { - System.out.println("LOGBACK: No context given for " + this); - } - return; + + public Context getContext() { + return this.context; + } + + public StatusManager getStatusManager() { + if (context == null) { + return null; + } + return context.getStatusManager(); } - StatusManager sm = context.getStatusManager(); - if (sm != null) { - sm.add(status); + + public void addStatus(Status status) { + if (context == null) { + if (noContextWarning++ == 0) { + System.out.println("LOGBACK: No context given for " + this); + } + return; + } + StatusManager sm = context.getStatusManager(); + if (sm != null) { + sm.add(status); + } } - } - public void addInfo(String msg) { - addStatus(new InfoStatus(msg, getOrigin())); - } + public void addInfo(String msg) { + addStatus(new InfoStatus(msg, getOrigin())); + } - public void addInfo(String msg, Throwable ex) { - addStatus(new InfoStatus(msg, getOrigin(), ex)); - } + public void addInfo(String msg, Throwable ex) { + addStatus(new InfoStatus(msg, getOrigin(), ex)); + } - public void addWarn(String msg) { - addStatus(new WarnStatus(msg, getOrigin())); - } + public void addWarn(String msg) { + addStatus(new WarnStatus(msg, getOrigin())); + } - public void addWarn(String msg, Throwable ex) { - addStatus(new WarnStatus(msg, getOrigin(), ex)); - } + public void addWarn(String msg, Throwable ex) { + addStatus(new WarnStatus(msg, getOrigin(), ex)); + } - public void addError(String msg) { - addStatus(new ErrorStatus(msg, getOrigin())); - } + public void addError(String msg) { + addStatus(new ErrorStatus(msg, getOrigin())); + } - public void addError(String msg, Throwable ex) { - addStatus(new ErrorStatus(msg, getOrigin(), ex)); - } + public void addError(String msg, Throwable ex) { + addStatus(new ErrorStatus(msg, getOrigin(), ex)); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/CyclicBufferTracker.java b/logback-core/src/main/java/ch/qos/logback/core/spi/CyclicBufferTracker.java index 151a66b098c8c422783a1bab430fafda104043d1..6613c1aee5b93af6d636c5194f1204c926ae08bb 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/CyclicBufferTracker.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/CyclicBufferTracker.java @@ -24,48 +24,47 @@ import java.util.*; */ public class CyclicBufferTracker extends AbstractComponentTracker> { - static final int DEFAULT_NUMBER_OF_BUFFERS = 64; + static final int DEFAULT_NUMBER_OF_BUFFERS = 64; - static final int DEFAULT_BUFFER_SIZE = 256; - int bufferSize = DEFAULT_BUFFER_SIZE; + static final int DEFAULT_BUFFER_SIZE = 256; + int bufferSize = DEFAULT_BUFFER_SIZE; + public CyclicBufferTracker() { + super(); + setMaxComponents(DEFAULT_NUMBER_OF_BUFFERS); + } - public CyclicBufferTracker() { - super(); - setMaxComponents(DEFAULT_NUMBER_OF_BUFFERS); - } + public int getBufferSize() { + return bufferSize; + } - public int getBufferSize() { - return bufferSize; - } + public void setBufferSize(int bufferSize) { + this.bufferSize = bufferSize; + } - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } + @Override + protected void processPriorToRemoval(CyclicBuffer component) { + component.clear(); + } - @Override - protected void processPriorToRemoval(CyclicBuffer component) { - component.clear(); - } + @Override + protected CyclicBuffer buildComponent(String key) { + return new CyclicBuffer(bufferSize); + } - @Override - protected CyclicBuffer buildComponent(String key) { - return new CyclicBuffer(bufferSize); - } + @Override + protected boolean isComponentStale(CyclicBuffer eCyclicBuffer) { + return false; + } - @Override - protected boolean isComponentStale(CyclicBuffer eCyclicBuffer) { - return false; - } + // for testing purposes + List liveKeysAsOrderedList() { + return new ArrayList(liveMap.keySet()); + } - // for testing purposes - List liveKeysAsOrderedList() { - return new ArrayList(liveMap.keySet()); - } + List lingererKeysAsOrderedList() { + return new ArrayList(lingerersMap.keySet()); - List lingererKeysAsOrderedList() { - return new ArrayList(lingerersMap.keySet()); - - } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/DeferredProcessingAware.java b/logback-core/src/main/java/ch/qos/logback/core/spi/DeferredProcessingAware.java index 95a5f66301283be74b380a741b29f72f715d1698..6e10640b97a3af663b336e3d16240c7f342256d8 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/DeferredProcessingAware.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/DeferredProcessingAware.java @@ -15,5 +15,5 @@ package ch.qos.logback.core.spi; public interface DeferredProcessingAware { - void prepareForDeferredProcessing(); + void prepareForDeferredProcessing(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachable.java b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachable.java index 3bda00178e414df87e50d38ae814d3bdac62de60..035830284559788b2279308036bf229425c014dd 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachable.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachable.java @@ -23,25 +23,25 @@ import ch.qos.logback.core.filter.Filter; * @author Ceki Gülcü */ public interface FilterAttachable { - /** - * Add a filter. - */ - void addFilter(Filter newFilter); + /** + * Add a filter. + */ + void addFilter(Filter newFilter); - void clearAllFilters(); + void clearAllFilters(); - /** - * Get a copy of all the filters contained within this FilterAttachable - * object. - * - * @return all attached filters as a list - */ - List> getCopyOfAttachedFiltersList(); + /** + * Get a copy of all the filters contained within this FilterAttachable + * object. + * + * @return all attached filters as a list + */ + List> getCopyOfAttachedFiltersList(); - /** - * Loop through the filters in the chain. As soon as a filter decides on - * ACCEPT or DENY, then that value is returned. If all of the filters return - * NEUTRAL, then NEUTRAL is returned. - */ - FilterReply getFilterChainDecision(E event); + /** + * Loop through the filters in the chain. As soon as a filter decides on + * ACCEPT or DENY, then that value is returned. If all of the filters return + * NEUTRAL, then NEUTRAL is returned. + */ + FilterReply getFilterChainDecision(E event); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachableImpl.java b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachableImpl.java index e583df29be943b92dcca9edd9194780a053a9fa1..ac755dd4a99c18aabb9b4581977fd7ed9455096f 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachableImpl.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterAttachableImpl.java @@ -26,38 +26,38 @@ import ch.qos.logback.core.filter.Filter; */ final public class FilterAttachableImpl implements FilterAttachable { - CopyOnWriteArrayList> filterList = new CopyOnWriteArrayList>(); - - /** - * Add a filter to end of the filter list. - */ - public void addFilter(Filter newFilter) { - filterList.add(newFilter); - } - - /** - * Clear the filter chain - */ - public void clearAllFilters() { - filterList.clear(); - } - - /** - * Loop through the filters in the list. As soon as a filter decides on - * ACCEPT or DENY, then that value is returned. If all of the filters return - * NEUTRAL, then NEUTRAL is returned. - */ - public FilterReply getFilterChainDecision(E event) { - for (Filter f : filterList) { - final FilterReply r = f.decide(event); - if (r == FilterReply.DENY || r == FilterReply.ACCEPT) { - return r; - } + CopyOnWriteArrayList> filterList = new CopyOnWriteArrayList>(); + + /** + * Add a filter to end of the filter list. + */ + public void addFilter(Filter newFilter) { + filterList.add(newFilter); + } + + /** + * Clear the filter chain + */ + public void clearAllFilters() { + filterList.clear(); } - return FilterReply.NEUTRAL; - } - public List> getCopyOfAttachedFiltersList() { - return new ArrayList>(filterList); - } + /** + * Loop through the filters in the list. As soon as a filter decides on + * ACCEPT or DENY, then that value is returned. If all of the filters return + * NEUTRAL, then NEUTRAL is returned. + */ + public FilterReply getFilterChainDecision(E event) { + for (Filter f : filterList) { + final FilterReply r = f.decide(event); + if (r == FilterReply.DENY || r == FilterReply.ACCEPT) { + return r; + } + } + return FilterReply.NEUTRAL; + } + + public List> getCopyOfAttachedFiltersList() { + return new ArrayList>(filterList); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterReply.java b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterReply.java index e50b7bb14416afef79ada9db2d19f748f3809187..b7b903d03954da5ba4407939e59fc33d742e46ac 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/FilterReply.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/FilterReply.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.spi; - /** * * This enum represents the possible replies that a filtering component @@ -28,7 +27,5 @@ package ch.qos.logback.core.spi; * @author Sébastien Pennec */ public enum FilterReply { - DENY, - NEUTRAL, - ACCEPT; + DENY, NEUTRAL, ACCEPT; } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/LifeCycle.java b/logback-core/src/main/java/ch/qos/logback/core/spi/LifeCycle.java index 5fd73829966ee7537d19b448fb56a78d9dc946a5..5f970bcabc222366f861f2fb64f4d434b8d3f6f9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/LifeCycle.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/LifeCycle.java @@ -15,8 +15,10 @@ package ch.qos.logback.core.spi; public interface LifeCycle { - void start(); - void stop(); - boolean isStarted(); + void start(); + + void stop(); + + boolean isStarted(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/LogbackLock.java b/logback-core/src/main/java/ch/qos/logback/core/spi/LogbackLock.java index 75095c08ed43c469605d14f14af8e773c1a59c95..5441339b51a6deeaf2775562e69c2489a34e710d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/LogbackLock.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/LogbackLock.java @@ -20,6 +20,5 @@ package ch.qos.logback.core.spi; * @author Ceki Gücü */ public class LogbackLock extends Object { - - + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/PreSerializationTransformer.java b/logback-core/src/main/java/ch/qos/logback/core/spi/PreSerializationTransformer.java index 32809949cda09550a4bf9d740ede50a0b0f262e5..23b6ea047b206d550a9d898e8cc577d7b9029fae 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/PreSerializationTransformer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/PreSerializationTransformer.java @@ -24,5 +24,5 @@ import java.io.Serializable; * @param */ public interface PreSerializationTransformer { - Serializable transform(E event); + Serializable transform(E event); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyContainer.java b/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyContainer.java index 0dc5167fef06ddc9edc9d12c2d0d58282af3c4dd..521909b65011f348d4538d63616dc4d69a2df66a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyContainer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyContainer.java @@ -17,7 +17,7 @@ import java.util.Map; public interface PropertyContainer { - String getProperty(String key); - - Map getCopyOfPropertyMap(); + String getProperty(String key); + + Map getCopyOfPropertyMap(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyDefiner.java b/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyDefiner.java index a7eec8387e99e0f313b869edb475b75e0e891a08..593f7619c0eb576e2a3741fbba747361a22221b9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyDefiner.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/PropertyDefiner.java @@ -15,10 +15,10 @@ package ch.qos.logback.core.spi; public interface PropertyDefiner extends ContextAware { - /** - * Get the property value, defined by this property definer - * - * @return defined property value - */ - String getPropertyValue(); + /** + * Get the property value, defined by this property definer + * + * @return defined property value + */ + String getPropertyValue(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/spi/ScanException.java b/logback-core/src/main/java/ch/qos/logback/core/spi/ScanException.java index 4b5a8877d772dd1415865011ae2268148bf81b7c..c7b42471c1f1f14ae4b2f7574541075dcbd9ccd5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/spi/ScanException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/spi/ScanException.java @@ -15,21 +15,20 @@ package ch.qos.logback.core.spi; public class ScanException extends Exception { - private static final long serialVersionUID = -3132040414328475658L; + private static final long serialVersionUID = -3132040414328475658L; - Throwable cause; + Throwable cause; - public ScanException(String msg) { - super(msg); - } + public ScanException(String msg) { + super(msg); + } - public ScanException(String msg, Throwable rootCause) { - super(msg); - this.cause = rootCause; - } + public ScanException(String msg, Throwable rootCause) { + super(msg); + this.cause = rootCause; + } - public Throwable getCause() { - return cause; - } + public Throwable getCause() { + return cause; + } } - diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/ErrorStatus.java b/logback-core/src/main/java/ch/qos/logback/core/status/ErrorStatus.java index 35724e00b877790365afd43be9e0bb4a563ebb43..f1c095c28c0545c56151d0ac6b8b770e6f401f58 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/ErrorStatus.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/ErrorStatus.java @@ -13,16 +13,14 @@ */ package ch.qos.logback.core.status; - - public class ErrorStatus extends StatusBase { - - public ErrorStatus(String msg, Object origin) { - super(Status.ERROR, msg, origin); - } - public ErrorStatus(String msg, Object origin, Throwable t) { - super(Status.ERROR, msg, origin, t); - } + public ErrorStatus(String msg, Object origin) { + super(Status.ERROR, msg, origin); + } + + public ErrorStatus(String msg, Object origin, Throwable t) { + super(Status.ERROR, msg, origin, t); + } - } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/InfoStatus.java b/logback-core/src/main/java/ch/qos/logback/core/status/InfoStatus.java index 9badcda7a0be823a5aa69f16c7d7536bbb526da2..a03ff6ea9bf1ce8c127e22ef16e573110ca9c110 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/InfoStatus.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/InfoStatus.java @@ -13,15 +13,13 @@ */ package ch.qos.logback.core.status; - - public class InfoStatus extends StatusBase { - public InfoStatus(String msg, Object origin) { - super(Status.INFO, msg, origin); - } + public InfoStatus(String msg, Object origin) { + super(Status.INFO, msg, origin); + } - public InfoStatus(String msg, Object origin, Throwable t) { - super(Status.INFO, msg, origin, t); - } + public InfoStatus(String msg, Object origin, Throwable t) { + super(Status.INFO, msg, origin, t); + } - } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/NopStatusListener.java b/logback-core/src/main/java/ch/qos/logback/core/status/NopStatusListener.java index 26d4f0ebea20598ac68b8a5123e2e4e169c6f29e..98eb8ed30ce077214a5104a95ca639a85fde9ad9 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/NopStatusListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/NopStatusListener.java @@ -21,7 +21,7 @@ package ch.qos.logback.core.status; */ public class NopStatusListener implements StatusListener { - public void addStatusEvent(Status status) { - // nothing to do - } + public void addStatusEvent(Status status) { + // nothing to do + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/OnConsoleStatusListener.java b/logback-core/src/main/java/ch/qos/logback/core/status/OnConsoleStatusListener.java index 591766059b766290b6eff756b19c1bbf28d92b91..d13c404cc8b1d524ff36d3472376355e44ef12e2 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/status/OnConsoleStatusListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/OnConsoleStatusListener.java @@ -22,10 +22,9 @@ import java.io.PrintStream; */ public class OnConsoleStatusListener extends OnPrintStreamStatusListenerBase { - @Override - protected PrintStream getPrintStream() { - return System.out; - } - + @Override + protected PrintStream getPrintStream() { + return System.out; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/OnErrorConsoleStatusListener.java b/logback-core/src/main/java/ch/qos/logback/core/status/OnErrorConsoleStatusListener.java index 3b3212d36b9566776390a1cf337f56e60664903e..b85da6c239c2c86f90153abeb7ad0027f6eed14b 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/OnErrorConsoleStatusListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/OnErrorConsoleStatusListener.java @@ -23,8 +23,8 @@ import java.io.PrintStream; */ public class OnErrorConsoleStatusListener extends OnPrintStreamStatusListenerBase { - @Override - protected PrintStream getPrintStream() { - return System.err; - } + @Override + protected PrintStream getPrintStream() { + return System.err; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/Status.java b/logback-core/src/main/java/ch/qos/logback/core/status/Status.java index 95fd643a03a1d71e9cbdf7783da023be02378bd0..aa08f59e932c68c2893d8b355d5e41c0a70c6056 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/Status.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/Status.java @@ -15,23 +15,30 @@ package ch.qos.logback.core.status; import java.util.Iterator; +public interface Status { -public interface Status { - - int INFO = 0; - int WARN = 1; - int ERROR = 2; - - int getLevel(); - int getEffectiveLevel(); - Object getOrigin(); - String getMessage(); - Throwable getThrowable(); - Long getDate(); - - boolean hasChildren(); - void add(Status child); - boolean remove(Status child); - Iterator iterator(); + int INFO = 0; + int WARN = 1; + int ERROR = 2; + + int getLevel(); + + int getEffectiveLevel(); + + Object getOrigin(); + + String getMessage(); + + Throwable getThrowable(); + + Long getDate(); + + boolean hasChildren(); + + void add(Status child); + + boolean remove(Status child); + + Iterator iterator(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/StatusBase.java b/logback-core/src/main/java/ch/qos/logback/core/status/StatusBase.java index 60202e830185a5ee1a92ce2cb9e5fd03cc8b7da2..a5f3022c64e50f7077c0a74941dabcc35e5bdbaa 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/StatusBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/StatusBase.java @@ -19,157 +19,156 @@ import java.util.List; abstract public class StatusBase implements Status { - static private final List EMPTY_LIST = new ArrayList(0); - - int level; - final String message; - final Object origin; - List childrenList; - Throwable throwable; - long date; - - StatusBase(int level, String msg, Object origin) { - this(level, msg, origin, null); - } - - StatusBase(int level, String msg, Object origin, Throwable t) { - this.level = level; - this.message = msg; - this.origin = origin; - this.throwable = t; - this.date = System.currentTimeMillis(); - } - - public synchronized void add(Status child) { - if (child == null) { - throw new NullPointerException("Null values are not valid Status."); + static private final List EMPTY_LIST = new ArrayList(0); + + int level; + final String message; + final Object origin; + List childrenList; + Throwable throwable; + long date; + + StatusBase(int level, String msg, Object origin) { + this(level, msg, origin, null); + } + + StatusBase(int level, String msg, Object origin, Throwable t) { + this.level = level; + this.message = msg; + this.origin = origin; + this.throwable = t; + this.date = System.currentTimeMillis(); + } + + public synchronized void add(Status child) { + if (child == null) { + throw new NullPointerException("Null values are not valid Status."); + } + if (childrenList == null) { + childrenList = new ArrayList(); + } + childrenList.add(child); + } + + public synchronized boolean hasChildren() { + return ((childrenList != null) && (childrenList.size() > 0)); + } + + public synchronized Iterator iterator() { + if (childrenList != null) { + return childrenList.iterator(); + } else { + return EMPTY_LIST.iterator(); + } } - if (childrenList == null) { - childrenList = new ArrayList(); + + public synchronized boolean remove(Status statusToRemove) { + if (childrenList == null) { + return false; + } + // TODO also search in childrens' children + return childrenList.remove(statusToRemove); + } + + public int getLevel() { + return level; + } + + // status messages are not supposed to contains cycles. + // cyclic status arrangements are like to cause deadlocks + // when this method is called from different thread on + // different status objects lying on the same cycle + public synchronized int getEffectiveLevel() { + int result = level; + int effLevel; + + Iterator it = iterator(); + Status s; + while (it.hasNext()) { + s = (Status) it.next(); + effLevel = s.getEffectiveLevel(); + if (effLevel > result) { + result = effLevel; + } + } + return result; } - childrenList.add(child); - } - - public synchronized boolean hasChildren() { - return ((childrenList != null) && (childrenList.size() > 0)); - } - - public synchronized Iterator iterator() { - if (childrenList != null) { - return childrenList.iterator(); - } else { - return EMPTY_LIST.iterator(); + + public String getMessage() { + return message; } - } - public synchronized boolean remove(Status statusToRemove) { - if (childrenList == null) { - return false; + public Object getOrigin() { + return origin; } - // TODO also search in childrens' children - return childrenList.remove(statusToRemove); - } - - public int getLevel() { - return level; - } - - // status messages are not supposed to contains cycles. - // cyclic status arrangements are like to cause deadlocks - // when this method is called from different thread on - // different status objects lying on the same cycle - public synchronized int getEffectiveLevel() { - int result = level; - int effLevel; - - Iterator it = iterator(); - Status s; - while (it.hasNext()) { - s = (Status) it.next(); - effLevel = s.getEffectiveLevel(); - if (effLevel > result) { - result = effLevel; - } + + public Throwable getThrowable() { + return throwable; } - return result; - } - - public String getMessage() { - return message; - } - - public Object getOrigin() { - return origin; - } - - public Throwable getThrowable() { - return throwable; - } - - public Long getDate() { - return date; - } - - /** - * @Override - */ - public String toString() { - StringBuilder buf = new StringBuilder(); - switch (getEffectiveLevel()) { - case INFO: - buf.append("INFO"); - break; - case WARN: - buf.append("WARN"); - break; - case ERROR: - buf.append("ERROR"); - break; + + public Long getDate() { + return date; } - if (origin != null) { - buf.append(" in "); - buf.append(origin); - buf.append(" -"); + + /** + * @Override + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + switch (getEffectiveLevel()) { + case INFO: + buf.append("INFO"); + break; + case WARN: + buf.append("WARN"); + break; + case ERROR: + buf.append("ERROR"); + break; + } + if (origin != null) { + buf.append(" in "); + buf.append(origin); + buf.append(" -"); + } + + buf.append(" "); + buf.append(message); + + if (throwable != null) { + buf.append(" "); + buf.append(throwable); + } + + return buf.toString(); } - buf.append(" "); - buf.append(message); + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + level; + result = prime * result + ((message == null) ? 0 : message.hashCode()); + return result; + } - if (throwable != null) { - buf.append(" "); - buf.append(throwable); + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final StatusBase other = (StatusBase) obj; + if (level != other.level) + return false; + if (message == null) { + if (other.message != null) + return false; + } else if (!message.equals(other.message)) + return false; + return true; } - return buf.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + level; - result = prime * result + ((message == null) ? 0 : message.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final StatusBase other = (StatusBase) obj; - if (level != other.level) - return false; - if (message == null) { - if (other.message != null) - return false; - } else if (!message.equals(other.message)) - return false; - return true; - } - - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/StatusListener.java b/logback-core/src/main/java/ch/qos/logback/core/status/StatusListener.java index d56874bdc040272f116c38c9589380cee5b01c61..4cbfa250aa55f67233e045540789862f0439b79a 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/StatusListener.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/StatusListener.java @@ -20,5 +20,5 @@ package ch.qos.logback.core.status; * @author Ceki Gülcü */ public interface StatusListener { - void addStatusEvent(Status status); + void addStatusEvent(Status status); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/StatusListenerAsList.java b/logback-core/src/main/java/ch/qos/logback/core/status/StatusListenerAsList.java index 0558d9e773957de2c96666a09aacf7df19e7dd09..ca2db352824bc37f2dfa7b2dba319d1ca353d11d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/StatusListenerAsList.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/StatusListenerAsList.java @@ -24,15 +24,14 @@ import java.util.List; */ public class StatusListenerAsList implements StatusListener { - List statusList = new ArrayList(); + List statusList = new ArrayList(); - public void addStatusEvent(Status status) { - statusList.add(status); - } + public void addStatusEvent(Status status) { + statusList.add(status); + } + + public List getStatusList() { + return statusList; + } - public List getStatusList() { - return statusList; - } - - } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/StatusManager.java b/logback-core/src/main/java/ch/qos/logback/core/status/StatusManager.java index 0658191dc9e3820125ac652cc48e5ac9b566893a..455c02a186f73e37c122a39c25e90291762fb4e8 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/status/StatusManager.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/StatusManager.java @@ -22,69 +22,65 @@ import java.util.List; */ public interface StatusManager { - /** - * Add a new status message. - * - * @param status - */ - void add(Status status); + /** + * Add a new status message. + * + * @param status + */ + void add(Status status); - /** - * Obtain a copy of the status list maintained by this StatusManager. - * - * @return - */ - List getCopyOfStatusList(); + /** + * Obtain a copy of the status list maintained by this StatusManager. + * + * @return + */ + List getCopyOfStatusList(); - /** - * Return the highest level of all the statii. - * - * @return - */ - //int getLevel(); + /** + * Return the highest level of all the statii. + * + * @return + */ + // int getLevel(); - /** - * Return the number of status entries. - * - * @return - */ - int getCount(); + /** + * Return the number of status entries. + * + * @return + */ + int getCount(); - /** - * Add a status listener. - * @param listener - */ - - /** - * Add a status listener. The StatusManager may decide to skip installation if an - * earlier instance was already installed. - * - * @param listener - * @return true if actually added, false if skipped - */ - boolean add(StatusListener listener); + /** + * Add a status listener. + * @param listener + */ - /**); - * Remove a status listener. - * - * @param listener - */ - void remove(StatusListener listener); + /** + * Add a status listener. The StatusManager may decide to skip installation if an + * earlier instance was already installed. + * + * @param listener + * @return true if actually added, false if skipped + */ + boolean add(StatusListener listener); + /**); + * Remove a status listener. + * + * @param listener + */ + void remove(StatusListener listener); - /** - * Clear the list of status messages. - */ - void clear(); - - - /** - * Obtain a copy of the status listener list maintained by this StatusManager - * - * @return - */ - List getCopyOfStatusListenerList(); - + /** + * Clear the list of status messages. + */ + void clear(); + /** + * Obtain a copy of the status listener list maintained by this StatusManager + * + * @return + */ + List getCopyOfStatusListenerList(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/StatusUtil.java b/logback-core/src/main/java/ch/qos/logback/core/status/StatusUtil.java index aebee54abffe0381c9ff18fb57699b1b87875bec..522dc44ab10b96dcb16d1b7c12add76fcc3df9e1 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/status/StatusUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/StatusUtil.java @@ -24,162 +24,161 @@ import java.util.regex.Pattern; public class StatusUtil { - StatusManager sm; - - public StatusUtil(StatusManager sm) { - this.sm = sm; - } - - public StatusUtil(Context context) { - this.sm = context.getStatusManager(); - } - - /** - * Returns true if the StatusManager associated with the context passed - * as parameter has one or more StatusListener instances registered. Returns - * false otherwise. - * - * @param context - * @return true if one or more StatusListeners registered, false otherwise - * @since 1.0.8 - */ - static public boolean contextHasStatusListener(Context context) { - StatusManager sm = context.getStatusManager(); - if(sm == null) - return false; - List listeners = sm.getCopyOfStatusListenerList(); - if(listeners == null || listeners.size() == 0) - return false; - else - return true; - } - - static public List filterStatusListByTimeThreshold(List rawList, long threshold) { - List filteredList = new ArrayList(); - for (Status s : rawList) { - if (s.getDate() >= threshold) - filteredList.add(s); - } - return filteredList; - } - - public void addStatus(Status status) { - if (sm != null) { - sm.add(status); - } - } - - public void addInfo(Object caller, String msg) { - addStatus(new InfoStatus(msg, caller)); - } - - public void addWarn(Object caller, String msg) { - addStatus(new WarnStatus(msg, caller)); - } - - public void addError(Object caller, String msg, - Throwable t) { - addStatus(new ErrorStatus(msg, caller, t)); - } - - public boolean hasXMLParsingErrors(long threshold) { - return containsMatch(threshold, Status.ERROR, CoreConstants.XML_PARSING); - } - - public boolean noXMLParsingErrorsOccurred(long threshold) { - return !hasXMLParsingErrors(threshold); - } - - public int getHighestLevel(long threshold) { - List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); - int maxLevel = Status.INFO; - for (Status s : filteredList) { - if (s.getLevel() > maxLevel) - maxLevel = s.getLevel(); - } - return maxLevel; - } - - public boolean isErrorFree(long threshold) { - return Status.ERROR > getHighestLevel(threshold); - } - - public boolean containsMatch(long threshold, int level, String regex) { - List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); - Pattern p = Pattern.compile(regex); - - for (Status status : filteredList) { - if (level != status.getLevel()) { - continue; - } - String msg = status.getMessage(); - Matcher matcher = p.matcher(msg); - if (matcher.lookingAt()) { - return true; - } - } - return false; - } - - public boolean containsMatch(int level, String regex) { - return containsMatch(0, level, regex); - } - - public boolean containsMatch(String regex) { - Pattern p = Pattern.compile(regex); - for (Status status : sm.getCopyOfStatusList()) { - String msg = status.getMessage(); - Matcher matcher = p.matcher(msg); - if (matcher.lookingAt()) { - return true; - } - } - return false; - } - - public int matchCount(String regex) { - int count = 0; - Pattern p = Pattern.compile(regex); - for (Status status : sm.getCopyOfStatusList()) { - String msg = status.getMessage(); - Matcher matcher = p.matcher(msg); - if (matcher.lookingAt()) { - count++; - } - } - return count; - } - - public boolean containsException(Class exceptionType) { - Iterator stati = sm.getCopyOfStatusList().iterator(); - while (stati.hasNext()) { - Status status = stati.next(); - Throwable t = status.getThrowable(); - if (t != null && t.getClass().getName().equals(exceptionType.getName())) { - return true; - } - } - return false; - } - - /** - * Return the time of last reset. -1 if last reset time could not be found - * - * @return time of last reset or -1 - */ - public long timeOfLastReset() { - List statusList = sm.getCopyOfStatusList(); - if (statusList == null) - return -1; - - int len = statusList.size(); - for (int i = len - 1; i >= 0; i--) { - Status s = statusList.get(i); - if (CoreConstants.RESET_MSG_PREFIX.equals(s.getMessage())) { - return s.getDate(); - } - } - return -1; - } + StatusManager sm; + + public StatusUtil(StatusManager sm) { + this.sm = sm; + } + + public StatusUtil(Context context) { + this.sm = context.getStatusManager(); + } + + /** + * Returns true if the StatusManager associated with the context passed + * as parameter has one or more StatusListener instances registered. Returns + * false otherwise. + * + * @param context + * @return true if one or more StatusListeners registered, false otherwise + * @since 1.0.8 + */ + static public boolean contextHasStatusListener(Context context) { + StatusManager sm = context.getStatusManager(); + if (sm == null) + return false; + List listeners = sm.getCopyOfStatusListenerList(); + if (listeners == null || listeners.size() == 0) + return false; + else + return true; + } + + static public List filterStatusListByTimeThreshold(List rawList, long threshold) { + List filteredList = new ArrayList(); + for (Status s : rawList) { + if (s.getDate() >= threshold) + filteredList.add(s); + } + return filteredList; + } + + public void addStatus(Status status) { + if (sm != null) { + sm.add(status); + } + } + + public void addInfo(Object caller, String msg) { + addStatus(new InfoStatus(msg, caller)); + } + + public void addWarn(Object caller, String msg) { + addStatus(new WarnStatus(msg, caller)); + } + + public void addError(Object caller, String msg, Throwable t) { + addStatus(new ErrorStatus(msg, caller, t)); + } + + public boolean hasXMLParsingErrors(long threshold) { + return containsMatch(threshold, Status.ERROR, CoreConstants.XML_PARSING); + } + + public boolean noXMLParsingErrorsOccurred(long threshold) { + return !hasXMLParsingErrors(threshold); + } + + public int getHighestLevel(long threshold) { + List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); + int maxLevel = Status.INFO; + for (Status s : filteredList) { + if (s.getLevel() > maxLevel) + maxLevel = s.getLevel(); + } + return maxLevel; + } + + public boolean isErrorFree(long threshold) { + return Status.ERROR > getHighestLevel(threshold); + } + + public boolean containsMatch(long threshold, int level, String regex) { + List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); + Pattern p = Pattern.compile(regex); + + for (Status status : filteredList) { + if (level != status.getLevel()) { + continue; + } + String msg = status.getMessage(); + Matcher matcher = p.matcher(msg); + if (matcher.lookingAt()) { + return true; + } + } + return false; + } + + public boolean containsMatch(int level, String regex) { + return containsMatch(0, level, regex); + } + + public boolean containsMatch(String regex) { + Pattern p = Pattern.compile(regex); + for (Status status : sm.getCopyOfStatusList()) { + String msg = status.getMessage(); + Matcher matcher = p.matcher(msg); + if (matcher.lookingAt()) { + return true; + } + } + return false; + } + + public int matchCount(String regex) { + int count = 0; + Pattern p = Pattern.compile(regex); + for (Status status : sm.getCopyOfStatusList()) { + String msg = status.getMessage(); + Matcher matcher = p.matcher(msg); + if (matcher.lookingAt()) { + count++; + } + } + return count; + } + + public boolean containsException(Class exceptionType) { + Iterator stati = sm.getCopyOfStatusList().iterator(); + while (stati.hasNext()) { + Status status = stati.next(); + Throwable t = status.getThrowable(); + if (t != null && t.getClass().getName().equals(exceptionType.getName())) { + return true; + } + } + return false; + } + + /** + * Return the time of last reset. -1 if last reset time could not be found + * + * @return time of last reset or -1 + */ + public long timeOfLastReset() { + List statusList = sm.getCopyOfStatusList(); + if (statusList == null) + return -1; + + int len = statusList.size(); + for (int i = len - 1; i >= 0; i--) { + Status s = statusList.get(i); + if (CoreConstants.RESET_MSG_PREFIX.equals(s.getMessage())) { + return s.getDate(); + } + } + return -1; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/ViewStatusMessagesServletBase.java b/logback-core/src/main/java/ch/qos/logback/core/status/ViewStatusMessagesServletBase.java index 51aa66c242edb6232aaa7413ff377291ee63f575..e1c483b1ab56c52bc9c0f45a544cb2a069b3cbd6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/ViewStatusMessagesServletBase.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/ViewStatusMessagesServletBase.java @@ -31,165 +31,155 @@ import ch.qos.logback.core.util.CachingDateFormatter; abstract public class ViewStatusMessagesServletBase extends HttpServlet { - private static final long serialVersionUID = -3551928133801157219L; - private static CachingDateFormatter SDF = new CachingDateFormatter( - "yyyy-MM-dd HH:mm:ss"); - - static String SUBMIT = "submit"; - static String CLEAR = "Clear"; - - protected abstract StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp); - - protected abstract String getPageTitle(HttpServletRequest req, HttpServletResponse resp); - - int count; + private static final long serialVersionUID = -3551928133801157219L; + private static CachingDateFormatter SDF = new CachingDateFormatter("yyyy-MM-dd HH:mm:ss"); + + static String SUBMIT = "submit"; + static String CLEAR = "Clear"; + + protected abstract StatusManager getStatusManager(HttpServletRequest req, HttpServletResponse resp); + + protected abstract String getPageTitle(HttpServletRequest req, HttpServletResponse resp); + + int count; + + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + count = 0; + StatusManager sm = getStatusManager(req, resp); + + resp.setContentType("text/html"); + PrintWriter output = resp.getWriter(); + + output.append("\r\n"); + output.append("\r\n"); + printCSS(req.getContextPath(), output); + output.append("\r\n"); + output.append("\r\n"); + output.append(getPageTitle(req, resp)); + + output.append("
\r\n"); + output.append(""); + output.append("\r\n"); + + if (CLEAR.equalsIgnoreCase(req.getParameter(SUBMIT))) { + sm.clear(); + sm.add(new InfoStatus("Cleared all status messages", this)); + } + + output.append("

"); + StringBuilder buf = new StringBuilder(); + if (sm != null) { + printList(buf, sm); + } else { + output.append("Could not find status manager"); + } + output.append(buf); + output.append("
"); + output.append("\r\n"); + output.append("\r\n"); + output.flush(); + output.close(); + } - protected void service(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + public void printCSS(String localRef, PrintWriter output) { + output.append(" \r\n"); + } - output.append("
\r\n"); - output.append(""); - output.append("
\r\n"); + public void printList(StringBuilder buf, StatusManager sm) { + buf.append("\r\n"); + printHeader(buf); + List statusList = sm.getCopyOfStatusList(); + for (Status s : statusList) { + count++; + printStatus(buf, s); + } + buf.append("
\r\n"); + } + public void printHeader(StringBuilder buf) { + buf.append(" \r\n"); + buf.append(" Date \r\n"); + buf.append(" Level\r\n"); + buf.append(" Origin\r\n"); + buf.append(" Message\r\n"); + buf.append(" \r\n"); - if(CLEAR.equalsIgnoreCase(req.getParameter(SUBMIT))) { - sm.clear(); - sm.add(new InfoStatus("Cleared all status messages", this)); } - - output.append(""); - StringBuilder buf = new StringBuilder(); - if(sm != null) { - printList(buf, sm); - } else { - output.append("Could not find status manager"); - } - output.append(buf); - output.append("
"); - output.append("\r\n"); - output.append("\r\n"); - output.flush(); - output.close(); - } - - public void printCSS(String localRef, PrintWriter output) { - output.append(" \r\n"); - - } - - public void printList(StringBuilder buf, StatusManager sm) { - buf.append("\r\n"); - printHeader(buf); - List statusList = sm.getCopyOfStatusList(); - for (Status s : statusList) { - count++; - printStatus(buf, s); - } - buf.append("
\r\n"); - } - - public void printHeader(StringBuilder buf) { - buf.append(" \r\n"); - buf.append(" Date \r\n"); - buf.append(" Level\r\n"); - buf.append(" Origin\r\n"); - buf.append(" Message\r\n"); - buf.append(" \r\n"); - - } - - String statusLevelAsString(Status s) { - switch (s.getEffectiveLevel()) { - case Status.INFO: - return "INFO"; - case Status.WARN: - return "WARN"; - case Status.ERROR: - return "ERROR"; - } - return null; - } - String abbreviatedOrigin(Status s) { - Object o = s.getOrigin(); - if (o == null) { - return null; + String statusLevelAsString(Status s) { + switch (s.getEffectiveLevel()) { + case Status.INFO: + return "INFO"; + case Status.WARN: + return "WARN"; + case Status.ERROR: + return "ERROR"; + } + return null; } - String fqClassName = o.getClass().getName(); - int lastIndex = fqClassName.lastIndexOf(CoreConstants.DOT); - if (lastIndex != -1) { - return fqClassName.substring(lastIndex + 1, fqClassName.length()); - } else { - return fqClassName; + + String abbreviatedOrigin(Status s) { + Object o = s.getOrigin(); + if (o == null) { + return null; + } + String fqClassName = o.getClass().getName(); + int lastIndex = fqClassName.lastIndexOf(CoreConstants.DOT); + if (lastIndex != -1) { + return fqClassName.substring(lastIndex + 1, fqClassName.length()); + } else { + return fqClassName; + } } - } - - private void printStatus(StringBuilder buf, Status s) { - String trClass; - if (count % 2 == 0) { - trClass = "even"; - } else { - trClass = "odd"; + + private void printStatus(StringBuilder buf, Status s) { + String trClass; + if (count % 2 == 0) { + trClass = "even"; + } else { + trClass = "odd"; + } + buf.append(" \r\n"); + String dateStr = SDF.format(s.getDate()); + buf.append(" ").append(dateStr).append("\r\n"); + buf.append(" ").append(statusLevelAsString(s)).append("\r\n"); + buf.append(" ").append(abbreviatedOrigin(s)).append("\r\n"); + buf.append(" ").append(s.getMessage()).append("\r\n"); + buf.append(" \r\n"); + if (s.getThrowable() != null) { + printThrowable(buf, s.getThrowable()); + } } - buf.append(" \r\n"); - String dateStr = SDF.format(s.getDate()); - buf.append(" ").append(dateStr).append("\r\n"); - buf.append(" ").append(statusLevelAsString(s)) - .append("\r\n"); - buf.append(" ").append(abbreviatedOrigin(s)).append("\r\n"); - buf.append(" ").append(s.getMessage()).append("\r\n"); - buf.append(" \r\n"); - if (s.getThrowable() != null) { - printThrowable(buf, s.getThrowable()); + + private void printThrowable(StringBuilder buf, Throwable t) { + buf.append(" \r\n"); + buf.append("
");
+        StringWriter sw = new StringWriter();
+        PrintWriter pw = new PrintWriter(sw);
+        t.printStackTrace(pw);
+        buf.append(Transform.escapeTags(sw.getBuffer()));
+        buf.append("    
\r\n"); + buf.append(" \r\n"); + } - } - - private void printThrowable(StringBuilder buf, Throwable t) { - buf.append(" \r\n"); - buf.append("
");
-    StringWriter sw = new StringWriter();
-    PrintWriter pw = new PrintWriter(sw);
-    t.printStackTrace(pw);
-    buf.append(Transform.escapeTags(sw.getBuffer()));
-    buf.append("    
\r\n"); - buf.append(" \r\n"); - - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/status/WarnStatus.java b/logback-core/src/main/java/ch/qos/logback/core/status/WarnStatus.java index 8d801cadca56a24e03adb55dc1af4c8e3e0da8ef..a9d7ab23e286cc659526b0e47bd4ace050b44d12 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/status/WarnStatus.java +++ b/logback-core/src/main/java/ch/qos/logback/core/status/WarnStatus.java @@ -13,17 +13,14 @@ */ package ch.qos.logback.core.status; - - public class WarnStatus extends StatusBase { - - public WarnStatus(String msg, Object origin) { - super(Status.WARN, msg, origin); - } + public WarnStatus(String msg, Object origin) { + super(Status.WARN, msg, origin); + } - public WarnStatus( String msg, Object origin, Throwable t) { - super(Status.WARN, msg, origin, t); - } + public WarnStatus(String msg, Object origin, Throwable t) { + super(Status.WARN, msg, origin, t); + } - } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/subst/Node.java b/logback-core/src/main/java/ch/qos/logback/core/subst/Node.java index c7b42052a35fa5ae74e2f872ebf5970a38f140e9..ba5815c9d90187f85e40f3bb6a736bd067a5e3cf 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/subst/Node.java +++ b/logback-core/src/main/java/ch/qos/logback/core/subst/Node.java @@ -15,110 +15,110 @@ package ch.qos.logback.core.subst; public class Node { - enum Type {LITERAL, VARIABLE} - - Type type; - Object payload; - Object defaultPart; - Node next; - - - public Node(Type type, Object payload) { - this.type = type; - this.payload = payload; - } - - - public Node(Type type, Object payload, Object defaultPart) { - this.type = type; - this.payload = payload; - this.defaultPart = defaultPart; - } - - void append(Node newNode) { - if(newNode == null) - return; - Node n = this; - while(true) { - if(n.next == null) { - n.next = newNode; - return; - } - n = n.next; + enum Type { + LITERAL, VARIABLE } - } - - @Override - public String toString() { - switch (type) { - case LITERAL: - return "Node{" + - "type=" + type + - ", payload='" + payload + - "'}"; - case VARIABLE: - StringBuilder payloadBuf = new StringBuilder(); - StringBuilder defaultPartBuf2 = new StringBuilder(); - if (defaultPart != null) - recursive((Node) defaultPart, defaultPartBuf2); - - recursive((Node) payload, payloadBuf); - String r = "Node{" + - "type=" + type + - ", payload='" + payloadBuf.toString()+"'"; - if (defaultPart != null) - r += ", defaultPart=" + defaultPartBuf2.toString(); - r += '}'; - return r; - } - return null; - } - - public void dump() { - System.out.print(this.toString()); - System.out.print(" -> "); - if(next != null) { - next.dump(); - } else { - System.out.print(" null"); + + Type type; + Object payload; + Object defaultPart; + Node next; + + public Node(Type type, Object payload) { + this.type = type; + this.payload = payload; } - } - void recursive(Node n, StringBuilder sb) { - Node c = n; - while (c != null) { - sb.append(c.toString()).append(" --> "); - c = c.next; + public Node(Type type, Object payload, Object defaultPart) { + this.type = type; + this.payload = payload; + this.defaultPart = defaultPart; } - sb.append("null "); - } - public void setNext(Node n) { - this.next = n; - } + void append(Node newNode) { + if (newNode == null) + return; + Node n = this; + while (true) { + if (n.next == null) { + n.next = newNode; + return; + } + n = n.next; + } + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public String toString() { + switch (type) { + case LITERAL: + return "Node{" + "type=" + type + ", payload='" + payload + "'}"; + case VARIABLE: + StringBuilder payloadBuf = new StringBuilder(); + StringBuilder defaultPartBuf2 = new StringBuilder(); + if (defaultPart != null) + recursive((Node) defaultPart, defaultPartBuf2); + + recursive((Node) payload, payloadBuf); + String r = "Node{" + "type=" + type + ", payload='" + payloadBuf.toString() + "'"; + if (defaultPart != null) + r += ", defaultPart=" + defaultPartBuf2.toString(); + r += '}'; + return r; + } + return null; + } - Node node = (Node) o; + public void dump() { + System.out.print(this.toString()); + System.out.print(" -> "); + if (next != null) { + next.dump(); + } else { + System.out.print(" null"); + } + } - if (type != node.type) return false; - if (payload != null ? !payload.equals(node.payload) : node.payload != null) return false; - if (defaultPart != null ? !defaultPart.equals(node.defaultPart) : node.defaultPart != null) return false; - if (next != null ? !next.equals(node.next) : node.next != null) return false; + void recursive(Node n, StringBuilder sb) { + Node c = n; + while (c != null) { + sb.append(c.toString()).append(" --> "); + c = c.next; + } + sb.append("null "); + } + public void setNext(Node n) { + this.next = n; + } - return true; - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + Node node = (Node) o; + + if (type != node.type) + return false; + if (payload != null ? !payload.equals(node.payload) : node.payload != null) + return false; + if (defaultPart != null ? !defaultPart.equals(node.defaultPart) : node.defaultPart != null) + return false; + if (next != null ? !next.equals(node.next) : node.next != null) + return false; + + return true; + } - @Override - public int hashCode() { - int result = type != null ? type.hashCode() : 0; - result = 31 * result + (payload != null ? payload.hashCode() : 0); - result = 31 * result + (defaultPart != null ? defaultPart.hashCode() : 0); - result = 31 * result + (next != null ? next.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = type != null ? type.hashCode() : 0; + result = 31 * result + (payload != null ? payload.hashCode() : 0); + result = 31 * result + (defaultPart != null ? defaultPart.hashCode() : 0); + result = 31 * result + (next != null ? next.hashCode() : 0); + return result; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/subst/NodeToStringTransformer.java b/logback-core/src/main/java/ch/qos/logback/core/subst/NodeToStringTransformer.java index 77db6aef9ddb3e89bc80a9bc2ebc5aae58ef2395..283c8640a1e6bf49937ac99d4d79deef30627b2c 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/subst/NodeToStringTransformer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/subst/NodeToStringTransformer.java @@ -28,156 +28,159 @@ import java.util.Stack; */ public class NodeToStringTransformer { - final Node node; - final PropertyContainer propertyContainer0; - final PropertyContainer propertyContainer1; - - public NodeToStringTransformer(Node node, PropertyContainer propertyContainer0, PropertyContainer propertyContainer1) { - this.node = node; - this.propertyContainer0 = propertyContainer0; - this.propertyContainer1 = propertyContainer1; - } - - public NodeToStringTransformer(Node node, PropertyContainer propertyContainer0) { - this(node, propertyContainer0, null); - } - - public static String substituteVariable(String input, PropertyContainer pc0, PropertyContainer pc1) throws ScanException { - Node node = tokenizeAndParseString(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, pc0, pc1); - return nodeToStringTransformer.transform(); - } - - private static Node tokenizeAndParseString(String value) throws ScanException { - Tokenizer tokenizer = new Tokenizer(value); - List tokens = tokenizer.tokenize(); - Parser parser = new Parser(tokens); - return parser.parse(); - } - - public String transform() throws ScanException { - StringBuilder stringBuilder = new StringBuilder(); - compileNode(node, stringBuilder, new Stack()); - return stringBuilder.toString(); - } - - private void compileNode(Node inputNode, StringBuilder stringBuilder, Stack cycleCheckStack) throws ScanException { - Node n = inputNode; - while (n != null) { - switch (n.type) { - case LITERAL: - handleLiteral(n, stringBuilder); - break; - case VARIABLE: - handleVariable(n, stringBuilder, cycleCheckStack); - break; - } - n = n.next; + final Node node; + final PropertyContainer propertyContainer0; + final PropertyContainer propertyContainer1; + + public NodeToStringTransformer(Node node, PropertyContainer propertyContainer0, PropertyContainer propertyContainer1) { + this.node = node; + this.propertyContainer0 = propertyContainer0; + this.propertyContainer1 = propertyContainer1; } - } - private void handleVariable(Node n, StringBuilder stringBuilder, Stack cycleCheckStack) throws ScanException { - - // Check for recursion - if (haveVisitedNodeAlready(n, cycleCheckStack)) { - cycleCheckStack.push(n); - String error = constructRecursionErrorMessage(cycleCheckStack); - throw new IllegalArgumentException(error); + public NodeToStringTransformer(Node node, PropertyContainer propertyContainer0) { + this(node, propertyContainer0, null); } - cycleCheckStack.push(n); - - StringBuilder keyBuffer = new StringBuilder(); - Node payload = (Node) n.payload; - compileNode(payload, keyBuffer, cycleCheckStack); - String key = keyBuffer.toString(); - String value = lookupKey(key); - - if (value != null) { - Node innerNode = tokenizeAndParseString(value); - compileNode(innerNode, stringBuilder, cycleCheckStack); - cycleCheckStack.pop(); - return; + + public static String substituteVariable(String input, PropertyContainer pc0, PropertyContainer pc1) throws ScanException { + Node node = tokenizeAndParseString(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, pc0, pc1); + return nodeToStringTransformer.transform(); } - if (n.defaultPart == null) { - stringBuilder.append(key + CoreConstants.UNDEFINED_PROPERTY_SUFFIX); - cycleCheckStack.pop(); - return; + private static Node tokenizeAndParseString(String value) throws ScanException { + Tokenizer tokenizer = new Tokenizer(value); + List tokens = tokenizer.tokenize(); + Parser parser = new Parser(tokens); + return parser.parse(); } - Node defaultPart = (Node) n.defaultPart; - StringBuilder defaultPartBuffer = new StringBuilder(); - compileNode(defaultPart, defaultPartBuffer, cycleCheckStack); - cycleCheckStack.pop(); - String defaultVal = defaultPartBuffer.toString(); - stringBuilder.append(defaultVal); - } - - private String lookupKey(String key) { - String value = propertyContainer0.getProperty(key); - if (value != null) - return value; - - if (propertyContainer1 != null) { - value = propertyContainer1.getProperty(key); - if (value != null) - return value; + public String transform() throws ScanException { + StringBuilder stringBuilder = new StringBuilder(); + compileNode(node, stringBuilder, new Stack()); + return stringBuilder.toString(); } - value = OptionHelper.getSystemProperty(key, null); - if (value != null) - return value; + private void compileNode(Node inputNode, StringBuilder stringBuilder, Stack cycleCheckStack) throws ScanException { + Node n = inputNode; + while (n != null) { + switch (n.type) { + case LITERAL: + handleLiteral(n, stringBuilder); + break; + case VARIABLE: + handleVariable(n, stringBuilder, cycleCheckStack); + break; + } + n = n.next; + } + } - value = OptionHelper.getEnv(key); - if (value != null) { - return value; + private void handleVariable(Node n, StringBuilder stringBuilder, Stack cycleCheckStack) throws ScanException { + + // Check for recursion + if (haveVisitedNodeAlready(n, cycleCheckStack)) { + cycleCheckStack.push(n); + String error = constructRecursionErrorMessage(cycleCheckStack); + throw new IllegalArgumentException(error); + } + cycleCheckStack.push(n); + + StringBuilder keyBuffer = new StringBuilder(); + Node payload = (Node) n.payload; + compileNode(payload, keyBuffer, cycleCheckStack); + String key = keyBuffer.toString(); + String value = lookupKey(key); + + if (value != null) { + Node innerNode = tokenizeAndParseString(value); + compileNode(innerNode, stringBuilder, cycleCheckStack); + cycleCheckStack.pop(); + return; + } + + if (n.defaultPart == null) { + stringBuilder.append(key + CoreConstants.UNDEFINED_PROPERTY_SUFFIX); + cycleCheckStack.pop(); + return; + } + + Node defaultPart = (Node) n.defaultPart; + StringBuilder defaultPartBuffer = new StringBuilder(); + compileNode(defaultPart, defaultPartBuffer, cycleCheckStack); + cycleCheckStack.pop(); + String defaultVal = defaultPartBuffer.toString(); + stringBuilder.append(defaultVal); } - return null; - } + private String lookupKey(String key) { + String value = propertyContainer0.getProperty(key); + if (value != null) + return value; + + if (propertyContainer1 != null) { + value = propertyContainer1.getProperty(key); + if (value != null) + return value; + } + + value = OptionHelper.getSystemProperty(key, null); + if (value != null) + return value; + + value = OptionHelper.getEnv(key); + if (value != null) { + return value; + } + return null; + } - private void handleLiteral(Node n, StringBuilder stringBuilder) { - stringBuilder.append((String) n.payload); - } + private void handleLiteral(Node n, StringBuilder stringBuilder) { + stringBuilder.append((String) n.payload); + } - private String variableNodeValue(Node variableNode) { - Node literalPayload = (Node) variableNode.payload; - return (String) literalPayload.payload; - } + private String variableNodeValue(Node variableNode) { + Node literalPayload = (Node) variableNode.payload; + return (String) literalPayload.payload; + } - private String constructRecursionErrorMessage(Stack recursionNodes) { - StringBuilder errorBuilder = new StringBuilder("Circular variable reference detected while parsing input ["); + private String constructRecursionErrorMessage(Stack recursionNodes) { + StringBuilder errorBuilder = new StringBuilder("Circular variable reference detected while parsing input ["); + + for (Node stackNode : recursionNodes) { + errorBuilder.append("${").append(variableNodeValue(stackNode)).append("}"); + if (recursionNodes.lastElement() != stackNode) { + errorBuilder.append(" --> "); + } + } + errorBuilder.append("]"); + return errorBuilder.toString(); + } - for (Node stackNode : recursionNodes) { - errorBuilder.append("${").append(variableNodeValue(stackNode)).append("}"); - if (recursionNodes.lastElement() != stackNode) { - errorBuilder.append(" --> "); - } + /** + * Determine if a node has already been visited already by checking the cycleDetectionStack + * for it's existence. This method is used -- rather than Stack.contains() -- because + * we want to ignore the Node's 'next' attribute when comparing for equality. + */ + private boolean haveVisitedNodeAlready(Node node, Stack cycleDetectionStack) { + for (Node cycleNode : cycleDetectionStack) { + if (equalNodes(node, cycleNode)) { + return true; + } + } + return false; } - errorBuilder.append("]"); - return errorBuilder.toString(); - } - - /** - * Determine if a node has already been visited already by checking the cycleDetectionStack - * for it's existence. This method is used -- rather than Stack.contains() -- because - * we want to ignore the Node's 'next' attribute when comparing for equality. - */ - private boolean haveVisitedNodeAlready(Node node, Stack cycleDetectionStack) { - for (Node cycleNode : cycleDetectionStack) { - if (equalNodes(node, cycleNode)) { + + private boolean equalNodes(Node node1, Node node2) { + if (node1.type != null && !node1.type.equals(node2.type)) + return false; + if (node1.payload != null && !node1.payload.equals(node2.payload)) + return false; + if (node1.defaultPart != null && !node1.defaultPart.equals(node2.defaultPart)) + return false; + return true; - } } - return false; - } - private boolean equalNodes(Node node1, Node node2) { - if (node1.type != null && !node1.type.equals(node2.type)) return false; - if (node1.payload != null && !node1.payload.equals(node2.payload)) return false; - if (node1.defaultPart != null && !node1.defaultPart.equals(node2.defaultPart)) return false; - - return true; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/subst/Parser.java b/logback-core/src/main/java/ch/qos/logback/core/subst/Parser.java index 3477fdabe4041c645adf6d532123fb5ff06c56b7..5c935c6f19173ee8526eb316889a9ddd3ff76727 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/subst/Parser.java +++ b/logback-core/src/main/java/ch/qos/logback/core/subst/Parser.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.subst; - import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.spi.ScanException; @@ -35,129 +34,128 @@ import java.util.List; */ public class Parser { - final List tokenList; - int pointer = 0; + final List tokenList; + int pointer = 0; - public Parser(List tokenList) { - this.tokenList = tokenList; - } + public Parser(List tokenList) { + this.tokenList = tokenList; + } - public Node parse() throws ScanException { - if(tokenList == null || tokenList.isEmpty()) - return null; - return E(); - } + public Node parse() throws ScanException { + if (tokenList == null || tokenList.isEmpty()) + return null; + return E(); + } - private Node E() throws ScanException { - Node t = T(); - if (t == null) { - return null; + private Node E() throws ScanException { + Node t = T(); + if (t == null) { + return null; + } + Node eOpt = Eopt(); + if (eOpt != null) { + t.append(eOpt); + } + return t; } - Node eOpt = Eopt(); - if (eOpt != null) { - t.append(eOpt); + + // Eopt = E|~ + private Node Eopt() throws ScanException { + Token next = peekAtCurentToken(); + if (next == null) { + return null; + } else { + return E(); + } } - return t; - } - - // Eopt = E|~ - private Node Eopt() throws ScanException { - Token next = peekAtCurentToken(); - if (next == null) { - return null; - } else { - return E(); + + // T = LITERAL | '${' V '}' + private Node T() throws ScanException { + Token t = peekAtCurentToken(); + + switch (t.type) { + case LITERAL: + advanceTokenPointer(); + return makeNewLiteralNode(t.payload); + case CURLY_LEFT: + advanceTokenPointer(); + Node innerNode = C(); + Token right = peekAtCurentToken(); + expectCurlyRight(right); + advanceTokenPointer(); + Node curlyLeft = makeNewLiteralNode(CoreConstants.LEFT_ACCOLADE); + curlyLeft.append(innerNode); + curlyLeft.append(makeNewLiteralNode(CoreConstants.RIGHT_ACCOLADE)); + return curlyLeft; + case START: + advanceTokenPointer(); + Node v = V(); + Token w = peekAtCurentToken(); + expectCurlyRight(w); + advanceTokenPointer(); + return v; + default: + return null; + } } - } - - // T = LITERAL | '${' V '}' - private Node T() throws ScanException { - Token t = peekAtCurentToken(); - - switch (t.type) { - case LITERAL: - advanceTokenPointer(); - return makeNewLiteralNode(t.payload); - case CURLY_LEFT: - advanceTokenPointer(); - Node innerNode = C(); - Token right = peekAtCurentToken(); - expectCurlyRight(right); - advanceTokenPointer(); - Node curlyLeft = makeNewLiteralNode(CoreConstants.LEFT_ACCOLADE); - curlyLeft.append(innerNode); - curlyLeft.append(makeNewLiteralNode(CoreConstants.RIGHT_ACCOLADE)); - return curlyLeft; - case START: - advanceTokenPointer(); - Node v = V(); - Token w = peekAtCurentToken(); - expectCurlyRight(w); - advanceTokenPointer(); - return v; - default: - return null; + + private Node makeNewLiteralNode(String s) { + return new Node(Node.Type.LITERAL, s); } - } - - private Node makeNewLiteralNode(String s) { - return new Node(Node.Type.LITERAL, s); - } - - // V = E(':='E|~) - private Node V() throws ScanException { - Node e = E(); - Node variable = new Node(Node.Type.VARIABLE, e); - Token t = peekAtCurentToken(); - if (isDefaultToken(t)) { - advanceTokenPointer(); - Node def = E(); - variable.defaultPart = def; + + // V = E(':='E|~) + private Node V() throws ScanException { + Node e = E(); + Node variable = new Node(Node.Type.VARIABLE, e); + Token t = peekAtCurentToken(); + if (isDefaultToken(t)) { + advanceTokenPointer(); + Node def = E(); + variable.defaultPart = def; + } + return variable; } - return variable; - } - - // C = E(':='E|~) - private Node C() throws ScanException { - Node e0 = E(); - Token t = peekAtCurentToken(); - if (isDefaultToken(t)) { - advanceTokenPointer(); - Node literal = makeNewLiteralNode(CoreConstants.DEFAULT_VALUE_SEPARATOR); - e0.append(literal); - Node e1 = E(); - e0.append(e1); + + // C = E(':='E|~) + private Node C() throws ScanException { + Node e0 = E(); + Token t = peekAtCurentToken(); + if (isDefaultToken(t)) { + advanceTokenPointer(); + Node literal = makeNewLiteralNode(CoreConstants.DEFAULT_VALUE_SEPARATOR); + e0.append(literal); + Node e1 = E(); + e0.append(e1); + } + return e0; } - return e0; - } - private boolean isDefaultToken(Token t) { - return t != null && t.type == Token.Type.DEFAULT; - } + private boolean isDefaultToken(Token t) { + return t != null && t.type == Token.Type.DEFAULT; + } - void advanceTokenPointer() { - pointer++; - } + void advanceTokenPointer() { + pointer++; + } - void expectNotNull(Token t, String expected) { - if (t == null) { - throw new IllegalArgumentException("All tokens consumed but was expecting \"" - + expected + "\""); + void expectNotNull(Token t, String expected) { + if (t == null) { + throw new IllegalArgumentException("All tokens consumed but was expecting \"" + expected + "\""); + } } - } - void expectCurlyRight(Token t) throws ScanException { - expectNotNull(t, "}"); - if (t.type != Token.Type.CURLY_RIGHT) { - throw new ScanException("Expecting }"); + void expectCurlyRight(Token t) throws ScanException { + expectNotNull(t, "}"); + if (t.type != Token.Type.CURLY_RIGHT) { + throw new ScanException("Expecting }"); + } } - } - Token peekAtCurentToken() { - if (pointer < tokenList.size()) { - return tokenList.get(pointer); + Token peekAtCurentToken() { + if (pointer < tokenList.size()) { + return tokenList.get(pointer); + } + return null; } - return null; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/subst/Token.java b/logback-core/src/main/java/ch/qos/logback/core/subst/Token.java index a4a30c68888755f3eb893cf0cb78b20e2393c9a5..42767bd01e3d7e179e5d4f3167ce15c56477dc6d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/subst/Token.java +++ b/logback-core/src/main/java/ch/qos/logback/core/subst/Token.java @@ -15,49 +15,54 @@ package ch.qos.logback.core.subst; public class Token { - static public final Token START_TOKEN = new Token(Type.START, null); - static public final Token CURLY_LEFT_TOKEN = new Token(Type.CURLY_LEFT, null); - static public final Token CURLY_RIGHT_TOKEN = new Token(Type.CURLY_RIGHT, null); - static public final Token DEFAULT_SEP_TOKEN = new Token(Type.DEFAULT, null); - - public enum Type {LITERAL, START, CURLY_LEFT, CURLY_RIGHT, DEFAULT} - - Type type; - String payload; - - public Token(Type type, String payload) { - this.type = type; - this.payload = payload; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Token token = (Token) o; - - if (type != token.type) return false; - if (payload != null ? !payload.equals(token.payload) : token.payload != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = type != null ? type.hashCode() : 0; - result = 31 * result + (payload != null ? payload.hashCode() : 0); - return result; - } - - @Override - public String toString() { - String result = "Token{" + - "type=" + type; - if (payload != null) - result += ", payload='" + payload + '\''; - - result += '}'; - return result; - } + static public final Token START_TOKEN = new Token(Type.START, null); + static public final Token CURLY_LEFT_TOKEN = new Token(Type.CURLY_LEFT, null); + static public final Token CURLY_RIGHT_TOKEN = new Token(Type.CURLY_RIGHT, null); + static public final Token DEFAULT_SEP_TOKEN = new Token(Type.DEFAULT, null); + + public enum Type { + LITERAL, START, CURLY_LEFT, CURLY_RIGHT, DEFAULT + } + + Type type; + String payload; + + public Token(Type type, String payload) { + this.type = type; + this.payload = payload; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + Token token = (Token) o; + + if (type != token.type) + return false; + if (payload != null ? !payload.equals(token.payload) : token.payload != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = type != null ? type.hashCode() : 0; + result = 31 * result + (payload != null ? payload.hashCode() : 0); + return result; + } + + @Override + public String toString() { + String result = "Token{" + "type=" + type; + if (payload != null) + result += ", payload='" + payload + '\''; + + result += '}'; + return result; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/subst/Tokenizer.java b/logback-core/src/main/java/ch/qos/logback/core/subst/Tokenizer.java index 0d14fde8603e825eef7e4dc472fc6d8e96e01226..15fd74aca1769dc35e6adb413a769f12fc9e1176 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/subst/Tokenizer.java +++ b/logback-core/src/main/java/ch/qos/logback/core/subst/Tokenizer.java @@ -21,108 +21,107 @@ import java.util.List; public class Tokenizer { - enum TokenizerState {LITERAL_STATE, START_STATE, DEFAULT_VAL_STATE} - - final String pattern; - final int patternLength; - - public Tokenizer(String pattern) { - this.pattern = pattern; - patternLength = pattern.length(); - } - - TokenizerState state = TokenizerState.LITERAL_STATE; - int pointer = 0; + enum TokenizerState { + LITERAL_STATE, START_STATE, DEFAULT_VAL_STATE + } - List tokenize() throws ScanException { - List tokenList = new ArrayList(); - StringBuilder buf = new StringBuilder(); + final String pattern; + final int patternLength; - while (pointer < patternLength) { - char c = pattern.charAt(pointer); - pointer++; + public Tokenizer(String pattern) { + this.pattern = pattern; + patternLength = pattern.length(); + } - switch (state) { + TokenizerState state = TokenizerState.LITERAL_STATE; + int pointer = 0; + + List tokenize() throws ScanException { + List tokenList = new ArrayList(); + StringBuilder buf = new StringBuilder(); + + while (pointer < patternLength) { + char c = pattern.charAt(pointer); + pointer++; + + switch (state) { + case LITERAL_STATE: + handleLiteralState(c, tokenList, buf); + break; + case START_STATE: + handleStartState(c, tokenList, buf); + break; + case DEFAULT_VAL_STATE: + handleDefaultValueState(c, tokenList, buf); + default: + } + } + // EOS + switch (state) { case LITERAL_STATE: - handleLiteralState(c, tokenList, buf); - break; + addLiteralToken(tokenList, buf); + break; case START_STATE: - handleStartState(c, tokenList, buf); - break; - case DEFAULT_VAL_STATE: - handleDefaultValueState(c, tokenList, buf); - default: - } + throw new ScanException("Unexpected end of pattern string"); + } + return tokenList; } - // EOS - switch (state) { - case LITERAL_STATE: - addLiteralToken(tokenList, buf); - break; - case START_STATE: - throw new ScanException("Unexpected end of pattern string"); - } - return tokenList; - } - private void handleDefaultValueState(char c, List tokenList, StringBuilder stringBuilder) { - switch(c) { - case CoreConstants.DASH_CHAR: - tokenList.add(Token.DEFAULT_SEP_TOKEN); - state = TokenizerState.LITERAL_STATE; - break; - case CoreConstants.DOLLAR: - stringBuilder.append(CoreConstants.COLON_CHAR); - addLiteralToken(tokenList, stringBuilder); - stringBuilder.setLength(0); - state = TokenizerState.START_STATE; - break; - default: - stringBuilder.append(CoreConstants.COLON_CHAR).append(c); - state = TokenizerState.LITERAL_STATE; - break; + private void handleDefaultValueState(char c, List tokenList, StringBuilder stringBuilder) { + switch (c) { + case CoreConstants.DASH_CHAR: + tokenList.add(Token.DEFAULT_SEP_TOKEN); + state = TokenizerState.LITERAL_STATE; + break; + case CoreConstants.DOLLAR: + stringBuilder.append(CoreConstants.COLON_CHAR); + addLiteralToken(tokenList, stringBuilder); + stringBuilder.setLength(0); + state = TokenizerState.START_STATE; + break; + default: + stringBuilder.append(CoreConstants.COLON_CHAR).append(c); + state = TokenizerState.LITERAL_STATE; + break; + } } - } - private void handleStartState(char c, List tokenList, StringBuilder stringBuilder) { - if (c == CoreConstants.CURLY_LEFT) { - tokenList.add(Token.START_TOKEN); - } else { - stringBuilder.append(CoreConstants.DOLLAR).append(c); - } - state = TokenizerState.LITERAL_STATE; - } - - private void handleLiteralState(char c, List tokenList, StringBuilder stringBuilder) { - if (c == CoreConstants.DOLLAR) { - addLiteralToken(tokenList, stringBuilder); - stringBuilder.setLength(0); - state = TokenizerState.START_STATE; - } else if (c == CoreConstants.COLON_CHAR) { - addLiteralToken(tokenList, stringBuilder); - stringBuilder.setLength(0); - state = TokenizerState.DEFAULT_VAL_STATE; - } else if (c == CoreConstants.CURLY_LEFT) { - addLiteralToken(tokenList, stringBuilder); - tokenList.add(Token.CURLY_LEFT_TOKEN); - stringBuilder.setLength(0); - } else if (c == CoreConstants.CURLY_RIGHT) { - addLiteralToken(tokenList, stringBuilder); - tokenList.add(Token.CURLY_RIGHT_TOKEN); - stringBuilder.setLength(0); - } else { - stringBuilder.append(c); + private void handleStartState(char c, List tokenList, StringBuilder stringBuilder) { + if (c == CoreConstants.CURLY_LEFT) { + tokenList.add(Token.START_TOKEN); + } else { + stringBuilder.append(CoreConstants.DOLLAR).append(c); + } + state = TokenizerState.LITERAL_STATE; } - } + private void handleLiteralState(char c, List tokenList, StringBuilder stringBuilder) { + if (c == CoreConstants.DOLLAR) { + addLiteralToken(tokenList, stringBuilder); + stringBuilder.setLength(0); + state = TokenizerState.START_STATE; + } else if (c == CoreConstants.COLON_CHAR) { + addLiteralToken(tokenList, stringBuilder); + stringBuilder.setLength(0); + state = TokenizerState.DEFAULT_VAL_STATE; + } else if (c == CoreConstants.CURLY_LEFT) { + addLiteralToken(tokenList, stringBuilder); + tokenList.add(Token.CURLY_LEFT_TOKEN); + stringBuilder.setLength(0); + } else if (c == CoreConstants.CURLY_RIGHT) { + addLiteralToken(tokenList, stringBuilder); + tokenList.add(Token.CURLY_RIGHT_TOKEN); + stringBuilder.setLength(0); + } else { + stringBuilder.append(c); + } - private void addLiteralToken(List tokenList, StringBuilder stringBuilder) { - if (stringBuilder.length() == 0) - return; - tokenList.add(new Token(Token.Type.LITERAL, stringBuilder.toString())); - } + } + private void addLiteralToken(List tokenList, StringBuilder stringBuilder) { + if (stringBuilder.length() == 0) + return; + tokenList.add(new Token(Token.Type.LITERAL, stringBuilder.toString())); + } } - - diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/AggregationType.java b/logback-core/src/main/java/ch/qos/logback/core/util/AggregationType.java index b21ccce1877fa69de251248b85751739c8880c5c..4ce5021b0a97b85362e48ac28dbfe004425bb980 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/AggregationType.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/AggregationType.java @@ -25,12 +25,11 @@ package ch.qos.logback.core.util; * @author Ceki Gulcu */ public enum AggregationType { - NOT_FOUND, - AS_BASIC_PROPERTY, // Long, Integer, Double,..., java primitive, String, - // Duration or FileSize - AS_COMPLEX_PROPERTY, // a complex property, a.k.a. attribute, is any attribute - // not covered by basic attributes, i.e. - // object types defined by the user - AS_BASIC_PROPERTY_COLLECTION, // a collection of basic attributes - AS_COMPLEX_PROPERTY_COLLECTION; // a collection of complex attributes + NOT_FOUND, AS_BASIC_PROPERTY, // Long, Integer, Double,..., java primitive, String, + // Duration or FileSize + AS_COMPLEX_PROPERTY, // a complex property, a.k.a. attribute, is any attribute + // not covered by basic attributes, i.e. + // object types defined by the user + AS_BASIC_PROPERTY_COLLECTION, // a collection of basic attributes + AS_COMPLEX_PROPERTY_COLLECTION; // a collection of complex attributes } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/CachingDateFormatter.java b/logback-core/src/main/java/ch/qos/logback/core/util/CachingDateFormatter.java index 1f9615ca20c9a61a53615966f5c58f268a294781..60ad4af8e270679a0d1a7e6bbea93ab1457d0da1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/CachingDateFormatter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/CachingDateFormatter.java @@ -25,34 +25,33 @@ import java.util.TimeZone; */ public class CachingDateFormatter { + long lastTimestamp = -1; + String cachedStr = null; + final SimpleDateFormat sdf; - long lastTimestamp = -1; - String cachedStr = null; - final SimpleDateFormat sdf; - - public CachingDateFormatter(String pattern) { - sdf = new SimpleDateFormat(pattern); - } + public CachingDateFormatter(String pattern) { + sdf = new SimpleDateFormat(pattern); + } - public final String format(long now) { + public final String format(long now) { - // SimpleDateFormat is not thread safe. + // SimpleDateFormat is not thread safe. - // See also the discussion in http://jira.qos.ch/browse/LBCLASSIC-36 - // DateFormattingThreadedThroughputCalculator and SelectiveDateFormattingRunnable - // are also noteworthy + // See also the discussion in http://jira.qos.ch/browse/LBCLASSIC-36 + // DateFormattingThreadedThroughputCalculator and SelectiveDateFormattingRunnable + // are also noteworthy - // The now == lastTimestamp guard minimizes synchronization - synchronized (this) { - if (now != lastTimestamp) { - lastTimestamp = now; - cachedStr = sdf.format(new Date(now)); - } - return cachedStr; + // The now == lastTimestamp guard minimizes synchronization + synchronized (this) { + if (now != lastTimestamp) { + lastTimestamp = now; + cachedStr = sdf.format(new Date(now)); + } + return cachedStr; + } } - } - public void setTimeZone(TimeZone tz) { - sdf.setTimeZone(tz); - } + public void setTimeZone(TimeZone tz) { + sdf.setTimeZone(tz); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceState.java b/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceState.java index ed506ad8fd3a00aac7b468038881e25e7b5293d0..c5dbe3fe93e4faee3f6dbcce3966e5923c802b6d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceState.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceState.java @@ -18,15 +18,15 @@ package ch.qos.logback.core.util; * @author Ceki Gulcu */ class CharSequenceState { - final char c; - int occurrences; + final char c; + int occurrences; - public CharSequenceState(char c) { - this.c = c; - this.occurrences = 1; - } + public CharSequenceState(char c) { + this.c = c; + this.occurrences = 1; + } - void incrementOccurrences() { - occurrences++; - } + void incrementOccurrences() { + occurrences++; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceToRegexMapper.java b/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceToRegexMapper.java index 60a626cd620c08f975e10fb10f5a9ab842e10031..66ccd2207d1ee704e8477834a67be52c2c95db73 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceToRegexMapper.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/CharSequenceToRegexMapper.java @@ -23,104 +23,104 @@ import java.text.DateFormatSymbols; */ class CharSequenceToRegexMapper { - DateFormatSymbols symbols = DateFormatSymbols.getInstance(); + DateFormatSymbols symbols = DateFormatSymbols.getInstance(); - String toRegex(CharSequenceState css) { - final int occurrences = css.occurrences; - final char c = css.c; - switch (css.c) { - case 'G': - case 'z': - return ".*"; - case 'M': - if (occurrences <= 2) - return number(occurrences); - else if (occurrences == 3) - return getRegexForShortMonths(); - else - return getRegexForLongMonths(); - case 'y': - case 'w': - case 'W': - case 'D': - case 'd': - case 'F': - case 'H': - case 'k': - case 'K': - case 'h': - case 'm': - case 's': - case 'S': - return number(occurrences); - case 'E': - if (occurrences >= 4) { - return getRegexForLongDaysOfTheWeek(); - } else { - return getRegexForShortDaysOfTheWeek(); - } - case 'a': - return getRegexForAmPms(); - case 'Z': - return "(\\+|-)\\d{4}"; - case '.': - return "\\."; - case '\\': - throw new IllegalStateException("Forward slashes are not allowed"); - case '\'': - if (occurrences == 1) { - return ""; - } - throw new IllegalStateException("Too many single quotes"); - default: - if (occurrences == 1) { - return "" + c; - } else { - return c + "{" + occurrences + "}"; + String toRegex(CharSequenceState css) { + final int occurrences = css.occurrences; + final char c = css.c; + switch (css.c) { + case 'G': + case 'z': + return ".*"; + case 'M': + if (occurrences <= 2) + return number(occurrences); + else if (occurrences == 3) + return getRegexForShortMonths(); + else + return getRegexForLongMonths(); + case 'y': + case 'w': + case 'W': + case 'D': + case 'd': + case 'F': + case 'H': + case 'k': + case 'K': + case 'h': + case 'm': + case 's': + case 'S': + return number(occurrences); + case 'E': + if (occurrences >= 4) { + return getRegexForLongDaysOfTheWeek(); + } else { + return getRegexForShortDaysOfTheWeek(); + } + case 'a': + return getRegexForAmPms(); + case 'Z': + return "(\\+|-)\\d{4}"; + case '.': + return "\\."; + case '\\': + throw new IllegalStateException("Forward slashes are not allowed"); + case '\'': + if (occurrences == 1) { + return ""; + } + throw new IllegalStateException("Too many single quotes"); + default: + if (occurrences == 1) { + return "" + c; + } else { + return c + "{" + occurrences + "}"; + } } } - } - private String number(int occurrences) { - return "\\d{" + occurrences + "}"; - } + private String number(int occurrences) { + return "\\d{" + occurrences + "}"; + } - private String getRegexForAmPms() { - return symbolArrayToRegex(symbols.getAmPmStrings()); - } + private String getRegexForAmPms() { + return symbolArrayToRegex(symbols.getAmPmStrings()); + } - private String getRegexForLongDaysOfTheWeek() { - return symbolArrayToRegex(symbols.getWeekdays()); - } + private String getRegexForLongDaysOfTheWeek() { + return symbolArrayToRegex(symbols.getWeekdays()); + } - private String getRegexForShortDaysOfTheWeek() { - return symbolArrayToRegex(symbols.getShortWeekdays()); - } + private String getRegexForShortDaysOfTheWeek() { + return symbolArrayToRegex(symbols.getShortWeekdays()); + } - private String getRegexForLongMonths() { - return symbolArrayToRegex(symbols.getMonths()); - } + private String getRegexForLongMonths() { + return symbolArrayToRegex(symbols.getMonths()); + } - String getRegexForShortMonths() { - return symbolArrayToRegex(symbols.getShortMonths()); - } + String getRegexForShortMonths() { + return symbolArrayToRegex(symbols.getShortMonths()); + } - private String symbolArrayToRegex(String[] symbolArray) { - int[] minMax = findMinMaxLengthsInSymbols(symbolArray); - return ".{" + minMax[0] + "," + minMax[1] + "}"; - } + private String symbolArrayToRegex(String[] symbolArray) { + int[] minMax = findMinMaxLengthsInSymbols(symbolArray); + return ".{" + minMax[0] + "," + minMax[1] + "}"; + } - static int[] findMinMaxLengthsInSymbols(String[] symbols) { - int min = Integer.MAX_VALUE; - int max = 0; - for (String symbol : symbols) { - int len = symbol.length(); - // some SENTINEL values can be empty strings, the month at index 12 or the weekday at index 0 - if(len == 0) - continue; - min = Math.min(min, len); - max = Math.max(max, len); + static int[] findMinMaxLengthsInSymbols(String[] symbols) { + int min = Integer.MAX_VALUE; + int max = 0; + for (String symbol : symbols) { + int len = symbol.length(); + // some SENTINEL values can be empty strings, the month at index 12 or the weekday at index 0 + if (len == 0) + continue; + min = Math.min(min, len); + max = Math.max(max, len); + } + return new int[] { min, max }; } - return new int[]{min, max}; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/CloseUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/CloseUtil.java index c94ac97e454fb6966f66524097bb3d0ecfb4d91e..8c0f91b569eb401fe7542a5fa045f051a02ba491 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/CloseUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/CloseUtil.java @@ -25,47 +25,47 @@ import java.net.Socket; */ public class CloseUtil { - /** - * Closes a closeable while suppressing any {@code IOException} that occurs. - * @param closeable the socket to close - */ - public static void closeQuietly(Closeable closeable) { - if (closeable == null) return; - try { - closeable.close(); + /** + * Closes a closeable while suppressing any {@code IOException} that occurs. + * @param closeable the socket to close + */ + public static void closeQuietly(Closeable closeable) { + if (closeable == null) + return; + try { + closeable.close(); + } catch (IOException ex) { + assert true; // avoid an empty catch + } } - catch (IOException ex) { - assert true; // avoid an empty catch - } - } - /** - * Closes a socket while suppressing any {@code IOException} that occurs. - * @param socket the socket to close - */ - public static void closeQuietly(Socket socket) { - if (socket == null) return; - try { - socket.close(); - } - catch (IOException ex) { - assert true; // avoid an empty catch + /** + * Closes a socket while suppressing any {@code IOException} that occurs. + * @param socket the socket to close + */ + public static void closeQuietly(Socket socket) { + if (socket == null) + return; + try { + socket.close(); + } catch (IOException ex) { + assert true; // avoid an empty catch + } } - } - /** - * Closes a server socket while suppressing any {@code IOException} that - * occurs. - * @param serverSocket the socket to close - */ - public static void closeQuietly(ServerSocket serverSocket) { - if (serverSocket == null) return; - try { - serverSocket.close(); - } - catch (IOException ex) { - assert true; // avoid an empty catch + /** + * Closes a server socket while suppressing any {@code IOException} that + * occurs. + * @param serverSocket the socket to close + */ + public static void closeQuietly(ServerSocket serverSocket) { + if (serverSocket == null) + return; + try { + serverSocket.close(); + } catch (IOException ex) { + assert true; // avoid an empty catch + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/ContentTypeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/ContentTypeUtil.java index 0ddc6aee3ae8157044030e4e007e02c10abc6be2..2e065736498fe81f4f67df8a554a6379a9dd18b1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/ContentTypeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/ContentTypeUtil.java @@ -21,27 +21,27 @@ package ch.qos.logback.core.util; */ public class ContentTypeUtil { - public static boolean isTextual(String contextType) { - if (contextType == null) { - return false; + public static boolean isTextual(String contextType) { + if (contextType == null) { + return false; + } + return contextType.startsWith("text"); } - return contextType.startsWith("text"); - } - public static String getSubType(String contextType) { - if (contextType == null) { - return null; + public static String getSubType(String contextType) { + if (contextType == null) { + return null; + } + int index = contextType.indexOf('/'); + if (index == -1) { + return null; + } else { + int subTypeStartIndex = index + 1; + if (subTypeStartIndex < contextType.length()) { + return contextType.substring(subTypeStartIndex); + } else { + return null; + } + } } - int index = contextType.indexOf('/'); - if (index == -1) { - return null; - } else { - int subTypeStartIndex = index + 1; - if (subTypeStartIndex < contextType.length()) { - return contextType.substring(subTypeStartIndex); - } else { - return null; - } - } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/ContextUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/ContextUtil.java index bf5245c177f11d201fce61c49871e497a0e695c6..492a0198f7b19cbba049e1d56195303c5053da8d 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/ContextUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/ContextUtil.java @@ -28,82 +28,73 @@ import java.util.Properties; public class ContextUtil extends ContextAwareBase { - public ContextUtil(Context context) { - setContext(context); - } - - public static String getLocalHostName() throws UnknownHostException, - SocketException { - try { - InetAddress localhost = InetAddress.getLocalHost(); - return localhost.getHostName(); - } catch (UnknownHostException e) { - return getLocalAddressAsString(); + public ContextUtil(Context context) { + setContext(context); } - } - private static String getLocalAddressAsString() throws UnknownHostException, - SocketException { - Enumeration interfaces = - NetworkInterface.getNetworkInterfaces(); - while (interfaces != null && interfaces.hasMoreElements()) { - Enumeration addresses = - interfaces.nextElement().getInetAddresses(); - while (addresses != null && addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (acceptableAddress(address)) { - return address.getHostAddress(); + public static String getLocalHostName() throws UnknownHostException, SocketException { + try { + InetAddress localhost = InetAddress.getLocalHost(); + return localhost.getHostName(); + } catch (UnknownHostException e) { + return getLocalAddressAsString(); } - } } - throw new UnknownHostException(); - } - - private static boolean acceptableAddress(InetAddress address) { - return address != null - && !address.isLoopbackAddress() - && !address.isAnyLocalAddress() - && !address.isLinkLocalAddress(); - } - /** - * Add the local host's name as a property - */ - public void addHostNameAsProperty() { - try { - String localhostName = getLocalHostName(); - context.putProperty(CoreConstants.HOSTNAME_KEY, localhostName); - } catch (UnknownHostException e) { - addError("Failed to get local hostname", e); - } catch (SocketException e) { - addError("Failed to get local hostname", e); - } catch (SecurityException e) { - addError("Failed to get local hostname", e); + private static String getLocalAddressAsString() throws UnknownHostException, SocketException { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces != null && interfaces.hasMoreElements()) { + Enumeration addresses = interfaces.nextElement().getInetAddresses(); + while (addresses != null && addresses.hasMoreElements()) { + InetAddress address = addresses.nextElement(); + if (acceptableAddress(address)) { + return address.getHostAddress(); + } + } + } + throw new UnknownHostException(); } - } - public void addProperties(Properties props) { - if (props == null) { - return; + private static boolean acceptableAddress(InetAddress address) { + return address != null && !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress(); } - Iterator i = props.keySet().iterator(); - while (i.hasNext()) { - String key = (String) i.next(); - context.putProperty(key, props.getProperty(key)); - } - } + /** + * Add the local host's name as a property + */ + public void addHostNameAsProperty() { + try { + String localhostName = getLocalHostName(); + context.putProperty(CoreConstants.HOSTNAME_KEY, localhostName); + } catch (UnknownHostException e) { + addError("Failed to get local hostname", e); + } catch (SocketException e) { + addError("Failed to get local hostname", e); + } catch (SecurityException e) { + addError("Failed to get local hostname", e); + } + } - public void addGroovyPackages(List frameworkPackages) { - //addFrameworkPackage(frameworkPackages, "groovy.lang"); - addFrameworkPackage(frameworkPackages, "org.codehaus.groovy.runtime"); - } + public void addProperties(Properties props) { + if (props == null) { + return; + } + Iterator i = props.keySet().iterator(); + while (i.hasNext()) { + String key = (String) i.next(); + context.putProperty(key, props.getProperty(key)); + } + } - public void addFrameworkPackage(List frameworkPackages, String packageName) { - if (!frameworkPackages.contains(packageName)) { - frameworkPackages.add(packageName); + public void addGroovyPackages(List frameworkPackages) { + // addFrameworkPackage(frameworkPackages, "groovy.lang"); + addFrameworkPackage(frameworkPackages, "org.codehaus.groovy.runtime"); } - } + public void addFrameworkPackage(List frameworkPackages, String packageName) { + if (!frameworkPackages.contains(packageName)) { + frameworkPackages.add(packageName); + } + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/DatePatternToRegexUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/DatePatternToRegexUtil.java index 144d501d133981773eed4c1ed9d8bdd5e5123970..b3d11df350c114d2eb53b377ac5266f8e30b70f3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/DatePatternToRegexUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/DatePatternToRegexUtil.java @@ -25,38 +25,38 @@ import java.util.List; */ public class DatePatternToRegexUtil { - final String datePattern; - final int datePatternLength; - final CharSequenceToRegexMapper regexMapper = new CharSequenceToRegexMapper(); - - public DatePatternToRegexUtil(String datePattern) { - this.datePattern = datePattern; - datePatternLength = datePattern.length(); - } - - public String toRegex() { - List charSequenceList = tokenize(); - StringBuilder sb = new StringBuilder(); - for (CharSequenceState seq : charSequenceList) { - sb.append(regexMapper.toRegex(seq)); + final String datePattern; + final int datePatternLength; + final CharSequenceToRegexMapper regexMapper = new CharSequenceToRegexMapper(); + + public DatePatternToRegexUtil(String datePattern) { + this.datePattern = datePattern; + datePatternLength = datePattern.length(); + } + + public String toRegex() { + List charSequenceList = tokenize(); + StringBuilder sb = new StringBuilder(); + for (CharSequenceState seq : charSequenceList) { + sb.append(regexMapper.toRegex(seq)); + } + return sb.toString(); } - return sb.toString(); - } - - private List tokenize() { - List sequenceList = new ArrayList(); - - CharSequenceState lastCharSequenceState = null; - - for (int i = 0; i < datePatternLength; i++) { - char t = datePattern.charAt(i); - if (lastCharSequenceState == null || lastCharSequenceState.c != t) { - lastCharSequenceState = new CharSequenceState(t); - sequenceList.add(lastCharSequenceState); - } else { - lastCharSequenceState.incrementOccurrences(); - } + + private List tokenize() { + List sequenceList = new ArrayList(); + + CharSequenceState lastCharSequenceState = null; + + for (int i = 0; i < datePatternLength; i++) { + char t = datePattern.charAt(i); + if (lastCharSequenceState == null || lastCharSequenceState.c != t) { + lastCharSequenceState = new CharSequenceState(t); + sequenceList.add(lastCharSequenceState); + } else { + lastCharSequenceState.incrementOccurrences(); + } + } + return sequenceList; } - return sequenceList; - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/DelayStrategy.java b/logback-core/src/main/java/ch/qos/logback/core/util/DelayStrategy.java index 3c98ac91b3fd8c8ed3584543e5b04cd83fa3827b..183a0c0042f89819c36b28b37a464eadca84e64d 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/DelayStrategy.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/DelayStrategy.java @@ -20,9 +20,9 @@ package ch.qos.logback.core.util; * @since 1.1.0 */ public interface DelayStrategy { - /** - * The value computed by this {@code DelayStrategy} for the next delay. - * @return a delay value - */ - long nextDelay(); + /** + * The value computed by this {@code DelayStrategy} for the next delay. + * @return a delay value + */ + long nextDelay(); } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/Duration.java b/logback-core/src/main/java/ch/qos/logback/core/util/Duration.java index aa4709a3c26681238648c14ddc4c89d7fea7680e..8e156dea8b93cecb55ef5ad6f2e033e6d43ea547 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/Duration.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/Duration.java @@ -33,94 +33,90 @@ import java.util.regex.Pattern; */ public class Duration { - private final static String DOUBLE_PART = "([0-9]*(.[0-9]+)?)"; - private final static int DOUBLE_GROUP = 1; - - private final static String UNIT_PART = "(|milli(second)?|second(e)?|minute|hour|day)s?"; - private final static int UNIT_GROUP = 3; - - private static final Pattern DURATION_PATTERN = Pattern.compile(DOUBLE_PART - + "\\s*" + UNIT_PART, Pattern.CASE_INSENSITIVE); - - static final long SECONDS_COEFFICIENT = 1000; - static final long MINUTES_COEFFICIENT = 60 * SECONDS_COEFFICIENT; - static final long HOURS_COEFFICIENT = 60 * MINUTES_COEFFICIENT; - static final long DAYS_COEFFICIENT = 24 * HOURS_COEFFICIENT; - - final long millis; - - public Duration(long millis) { - this.millis = millis; - } - - public static Duration buildByMilliseconds(double value) { - return new Duration((long) (value)); - } - - public static Duration buildBySeconds(double value) { - return new Duration((long) (SECONDS_COEFFICIENT * value)); - } - - public static Duration buildByMinutes(double value) { - return new Duration((long) (MINUTES_COEFFICIENT * value)); - } - - public static Duration buildByHours(double value) { - return new Duration((long) (HOURS_COEFFICIENT * value)); - } - - public static Duration buildByDays(double value) { - return new Duration((long) (DAYS_COEFFICIENT * value)); - } - - public static Duration buildUnbounded() { - return new Duration(Long.MAX_VALUE); - } - - public long getMilliseconds() { - return millis; - } - - public static Duration valueOf(String durationStr) { - Matcher matcher = DURATION_PATTERN.matcher(durationStr); - - if (matcher.matches()) { - String doubleStr = matcher.group(DOUBLE_GROUP); - String unitStr = matcher.group(UNIT_GROUP); - - double doubleValue = Double.valueOf(doubleStr); - if (unitStr.equalsIgnoreCase("milli") - || unitStr.equalsIgnoreCase("millisecond") || unitStr.length() == 0) { - return buildByMilliseconds(doubleValue); - } else if (unitStr.equalsIgnoreCase("second") - || unitStr.equalsIgnoreCase("seconde")) { - return buildBySeconds(doubleValue); - } else if (unitStr.equalsIgnoreCase("minute")) { - return buildByMinutes(doubleValue); - } else if (unitStr.equalsIgnoreCase("hour")) { - return buildByHours(doubleValue); - } else if (unitStr.equalsIgnoreCase("day")) { - return buildByDays(doubleValue); - } else { - throw new IllegalStateException("Unexpected " + unitStr); - } - } else { - throw new IllegalArgumentException("String value [" + durationStr - + "] is not in the expected format."); + private final static String DOUBLE_PART = "([0-9]*(.[0-9]+)?)"; + private final static int DOUBLE_GROUP = 1; + + private final static String UNIT_PART = "(|milli(second)?|second(e)?|minute|hour|day)s?"; + private final static int UNIT_GROUP = 3; + + private static final Pattern DURATION_PATTERN = Pattern.compile(DOUBLE_PART + "\\s*" + UNIT_PART, Pattern.CASE_INSENSITIVE); + + static final long SECONDS_COEFFICIENT = 1000; + static final long MINUTES_COEFFICIENT = 60 * SECONDS_COEFFICIENT; + static final long HOURS_COEFFICIENT = 60 * MINUTES_COEFFICIENT; + static final long DAYS_COEFFICIENT = 24 * HOURS_COEFFICIENT; + + final long millis; + + public Duration(long millis) { + this.millis = millis; + } + + public static Duration buildByMilliseconds(double value) { + return new Duration((long) (value)); + } + + public static Duration buildBySeconds(double value) { + return new Duration((long) (SECONDS_COEFFICIENT * value)); + } + + public static Duration buildByMinutes(double value) { + return new Duration((long) (MINUTES_COEFFICIENT * value)); } - } - - @Override - public String toString() { - if (millis < SECONDS_COEFFICIENT) { - return millis + " milliseconds"; - } else if (millis < MINUTES_COEFFICIENT) { - return millis / SECONDS_COEFFICIENT + " seconds"; - } else if (millis < HOURS_COEFFICIENT) { - return millis / MINUTES_COEFFICIENT + " minutes"; - } else { - return millis / HOURS_COEFFICIENT + " hours"; + + public static Duration buildByHours(double value) { + return new Duration((long) (HOURS_COEFFICIENT * value)); + } + + public static Duration buildByDays(double value) { + return new Duration((long) (DAYS_COEFFICIENT * value)); } - } + public static Duration buildUnbounded() { + return new Duration(Long.MAX_VALUE); + } + + public long getMilliseconds() { + return millis; + } + + public static Duration valueOf(String durationStr) { + Matcher matcher = DURATION_PATTERN.matcher(durationStr); + + if (matcher.matches()) { + String doubleStr = matcher.group(DOUBLE_GROUP); + String unitStr = matcher.group(UNIT_GROUP); + + double doubleValue = Double.valueOf(doubleStr); + if (unitStr.equalsIgnoreCase("milli") || unitStr.equalsIgnoreCase("millisecond") || unitStr.length() == 0) { + return buildByMilliseconds(doubleValue); + } else if (unitStr.equalsIgnoreCase("second") || unitStr.equalsIgnoreCase("seconde")) { + return buildBySeconds(doubleValue); + } else if (unitStr.equalsIgnoreCase("minute")) { + return buildByMinutes(doubleValue); + } else if (unitStr.equalsIgnoreCase("hour")) { + return buildByHours(doubleValue); + } else if (unitStr.equalsIgnoreCase("day")) { + return buildByDays(doubleValue); + } else { + throw new IllegalStateException("Unexpected " + unitStr); + } + } else { + throw new IllegalArgumentException("String value [" + durationStr + "] is not in the expected format."); + } + } + + @Override + public String toString() { + if (millis < SECONDS_COEFFICIENT) { + return millis + " milliseconds"; + } else if (millis < MINUTES_COEFFICIENT) { + return millis / SECONDS_COEFFICIENT + " seconds"; + } else if (millis < HOURS_COEFFICIENT) { + return millis / MINUTES_COEFFICIENT + " minutes"; + } else { + return millis / HOURS_COEFFICIENT + " hours"; + } + + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/DynamicClassLoadingException.java b/logback-core/src/main/java/ch/qos/logback/core/util/DynamicClassLoadingException.java index 23e0100f1d106f4e595a1c11c22e3244f74424da..7d7f9c4862a6ac4b28c3d8c5aacfee921d1e1ef8 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/DynamicClassLoadingException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/DynamicClassLoadingException.java @@ -15,9 +15,9 @@ package ch.qos.logback.core.util; public class DynamicClassLoadingException extends Exception { - private static final long serialVersionUID = 4962278449162476114L; + private static final long serialVersionUID = 4962278449162476114L; - public DynamicClassLoadingException(String desc, Throwable root ) { - super(desc, root); - } + public DynamicClassLoadingException(String desc, Throwable root) { + super(desc, root); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/EnvUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/EnvUtil.java index 451aec164c925f6cf4f3f007b6cad9fe54930ef0..52b700040e2363e14227ca7e89aaf762206661f3 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/EnvUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/EnvUtil.java @@ -21,51 +21,50 @@ import java.util.List; */ public class EnvUtil { + static private boolean isJDK_N_OrHigher(int n) { + List versionList = new ArrayList(); + // this code should work at least until JDK 10 (assuming n parameter is + // always 6 or more) + for (int i = 0; i < 5; i++) { + versionList.add("1." + (n + i)); + } - static private boolean isJDK_N_OrHigher(int n) { - List versionList = new ArrayList(); - // this code should work at least until JDK 10 (assuming n parameter is - // always 6 or more) - for (int i = 0; i < 5; i++) { - versionList.add("1." + (n + i)); - } - - String javaVersion = System.getProperty("java.version"); - if (javaVersion == null) { - return false; - } - for (String v : versionList) { - if (javaVersion.startsWith(v)) - return true; - } - return false; - } + String javaVersion = System.getProperty("java.version"); + if (javaVersion == null) { + return false; + } + for (String v : versionList) { + if (javaVersion.startsWith(v)) + return true; + } + return false; + } - static public boolean isJDK5() { - return isJDK_N_OrHigher(5); - } + static public boolean isJDK5() { + return isJDK_N_OrHigher(5); + } - static public boolean isJDK6OrHigher() { - return isJDK_N_OrHigher(6); - } + static public boolean isJDK6OrHigher() { + return isJDK_N_OrHigher(6); + } - static public boolean isJDK7OrHigher() { - return isJDK_N_OrHigher(7); - } + static public boolean isJDK7OrHigher() { + return isJDK_N_OrHigher(7); + } - static public boolean isJaninoAvailable() { - ClassLoader classLoader = EnvUtil.class.getClassLoader(); - try { - Class bindingClass = classLoader.loadClass("org.codehaus.janino.ScriptEvaluator"); - return (bindingClass != null); - } catch (ClassNotFoundException e) { - return false; + static public boolean isJaninoAvailable() { + ClassLoader classLoader = EnvUtil.class.getClassLoader(); + try { + Class bindingClass = classLoader.loadClass("org.codehaus.janino.ScriptEvaluator"); + return (bindingClass != null); + } catch (ClassNotFoundException e) { + return false; + } } - } - public static boolean isWindows() { - String os = System.getProperty("os.name"); - return os.startsWith("Windows"); - } + public static boolean isWindows() { + String os = System.getProperty("os.name"); + return os.startsWith("Windows"); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/ExecutorServiceUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/ExecutorServiceUtil.java index 4d92447c41958fd1be4985dcf7ec5eda33b0b10f..2e1b2c49eff4a4ccc9e5d48452b197fec154ce45 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/ExecutorServiceUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/ExecutorServiceUtil.java @@ -31,40 +31,37 @@ import ch.qos.logback.core.CoreConstants; */ public class ExecutorServiceUtil { - private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() { + private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() { - private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); - private final AtomicInteger threadNumber = new AtomicInteger(1); + private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); + private final AtomicInteger threadNumber = new AtomicInteger(1); - public Thread newThread(Runnable r) { - Thread thread = defaultFactory.newThread(r); - if (!thread.isDaemon()) { - thread.setDaemon(true); - } - thread.setName("logback-" + threadNumber.getAndIncrement()); - return thread; + public Thread newThread(Runnable r) { + Thread thread = defaultFactory.newThread(r); + if (!thread.isDaemon()) { + thread.setDaemon(true); + } + thread.setName("logback-" + threadNumber.getAndIncrement()); + return thread; + } + }; + + /** + * Creates an executor service suitable for use by logback components. + * @return executor service + */ + static public ExecutorService newExecutorService() { + return new ThreadPoolExecutor(CoreConstants.CORE_POOL_SIZE, CoreConstants.MAX_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue(), + THREAD_FACTORY); } - }; - /** - * Creates an executor service suitable for use by logback components. - * @return executor service - */ - static public ExecutorService newExecutorService() { - return new ThreadPoolExecutor(CoreConstants.CORE_POOL_SIZE, - CoreConstants.MAX_POOL_SIZE, - 0L, TimeUnit.MILLISECONDS, - new SynchronousQueue(), - THREAD_FACTORY); - } - - /** - * Shuts down an executor service. - *

- * @param executorService the executor service to shut down - */ - static public void shutdown(ExecutorService executorService) { - executorService.shutdownNow(); - } + /** + * Shuts down an executor service. + *

+ * @param executorService the executor service to shut down + */ + static public void shutdown(ExecutorService executorService) { + executorService.shutdownNow(); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/FileSize.java b/logback-core/src/main/java/ch/qos/logback/core/util/FileSize.java index 728ac46738c280e6c0ce4bd4fc456af5ae67220e..b94152f4d2a09256bb6a3357f18d22b5e5f3b334 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/FileSize.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/FileSize.java @@ -31,54 +31,52 @@ import java.util.regex.Pattern; */ public class FileSize { - private final static String LENGTH_PART = "([0-9]+)"; - private final static int DOUBLE_GROUP = 1; + private final static String LENGTH_PART = "([0-9]+)"; + private final static int DOUBLE_GROUP = 1; - private final static String UNIT_PART = "(|kb|mb|gb)s?"; - private final static int UNIT_GROUP = 2; + private final static String UNIT_PART = "(|kb|mb|gb)s?"; + private final static int UNIT_GROUP = 2; - private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(LENGTH_PART - + "\\s*" + UNIT_PART, Pattern.CASE_INSENSITIVE); + private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(LENGTH_PART + "\\s*" + UNIT_PART, Pattern.CASE_INSENSITIVE); - static final long KB_COEFFICIENT = 1024; - static final long MB_COEFFICIENT = 1024 * KB_COEFFICIENT; - static final long GB_COEFFICIENT = 1024 * MB_COEFFICIENT; + static final long KB_COEFFICIENT = 1024; + static final long MB_COEFFICIENT = 1024 * KB_COEFFICIENT; + static final long GB_COEFFICIENT = 1024 * MB_COEFFICIENT; - final long size; + final long size; - FileSize(long size) { - this.size = size; - } + FileSize(long size) { + this.size = size; + } + + public long getSize() { + return size; + } - public long getSize() { - return size; - } + static public FileSize valueOf(String fileSizeStr) { + Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr); - static public FileSize valueOf(String fileSizeStr) { - Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr); + long coefficient; + if (matcher.matches()) { + String lenStr = matcher.group(DOUBLE_GROUP); + String unitStr = matcher.group(UNIT_GROUP); - long coefficient; - if (matcher.matches()) { - String lenStr = matcher.group(DOUBLE_GROUP); - String unitStr = matcher.group(UNIT_GROUP); + long lenValue = Long.valueOf(lenStr); + if (unitStr.equalsIgnoreCase("")) { + coefficient = 1; + } else if (unitStr.equalsIgnoreCase("kb")) { + coefficient = KB_COEFFICIENT; + } else if (unitStr.equalsIgnoreCase("mb")) { + coefficient = MB_COEFFICIENT; + } else if (unitStr.equalsIgnoreCase("gb")) { + coefficient = GB_COEFFICIENT; + } else { + throw new IllegalStateException("Unexpected " + unitStr); + } + return new FileSize(lenValue * coefficient); + } else { + throw new IllegalArgumentException("String value [" + fileSizeStr + "] is not in the expected format."); + } - long lenValue = Long.valueOf(lenStr); - if (unitStr.equalsIgnoreCase("")) { - coefficient = 1; - } else if (unitStr.equalsIgnoreCase("kb")) { - coefficient = KB_COEFFICIENT; - } else if (unitStr.equalsIgnoreCase("mb")) { - coefficient = MB_COEFFICIENT; - } else if (unitStr.equalsIgnoreCase("gb")) { - coefficient = GB_COEFFICIENT; - } else { - throw new IllegalStateException("Unexpected " + unitStr); - } - return new FileSize(lenValue * coefficient); - } else { - throw new IllegalArgumentException("String value [" + fileSizeStr - + "] is not in the expected format."); } - - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/FileUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/FileUtil.java index 0951edfe1546f04f9241ca3c7981f5cc5d795081..2c335ffe7cec09bc5a470e6864760e66e7bc03d7 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/FileUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/FileUtil.java @@ -24,113 +24,112 @@ import java.net.URLConnection; public class FileUtil extends ContextAwareBase { - public FileUtil(Context context) { - setContext(context); - } - - public static URL fileToURL(File file) { - try { - return file.toURI().toURL(); - } catch (MalformedURLException e) { - throw new RuntimeException("Unexpected exception on file [" + file + "]", e); + public FileUtil(Context context) { + setContext(context); } - } - /** - * Creates the parent directories of a file. If parent directories not - * specified in file's path, then nothing is done and this returns - * gracefully. - * - * @param file file whose parent directories (if any) should be created - * @return {@code true} if either no parents were specified, or if all - * parent directories were created successfully; {@code false} otherwise - */ - static public boolean createMissingParentDirectories(File file) { - File parent = file.getParentFile(); - if (parent == null) { - // Parent directory not specified, therefore it's a request to - // create nothing. Done! ;) - return true; + public static URL fileToURL(File file) { + try { + return file.toURI().toURL(); + } catch (MalformedURLException e) { + throw new RuntimeException("Unexpected exception on file [" + file + "]", e); + } } - // File.mkdirs() creates the parent directories only if they don't - // already exist; and it's okay if they do. - parent.mkdirs(); - return parent.exists(); - } - + /** + * Creates the parent directories of a file. If parent directories not + * specified in file's path, then nothing is done and this returns + * gracefully. + * + * @param file file whose parent directories (if any) should be created + * @return {@code true} if either no parents were specified, or if all + * parent directories were created successfully; {@code false} otherwise + */ + static public boolean createMissingParentDirectories(File file) { + File parent = file.getParentFile(); + if (parent == null) { + // Parent directory not specified, therefore it's a request to + // create nothing. Done! ;) + return true; + } - public String resourceAsString(ClassLoader classLoader, String resourceName) { - URL url = classLoader.getResource(resourceName); - if (url == null) { - addError("Failed to find resource [" + resourceName + "]"); - return null; + // File.mkdirs() creates the parent directories only if they don't + // already exist; and it's okay if they do. + parent.mkdirs(); + return parent.exists(); } - InputStreamReader isr = null; - try { - URLConnection urlConnection = url.openConnection(); - urlConnection.setUseCaches(false); - isr = new InputStreamReader(urlConnection.getInputStream()); - char[] buf = new char[128]; - StringBuilder builder = new StringBuilder(); - int count = -1; - while ((count = isr.read(buf, 0, buf.length)) != -1) { - builder.append(buf, 0, count); - } - return builder.toString(); - } catch (IOException e) { - addError("Failed to open " + resourceName, e); - } finally { - if (isr != null) { + public String resourceAsString(ClassLoader classLoader, String resourceName) { + URL url = classLoader.getResource(resourceName); + if (url == null) { + addError("Failed to find resource [" + resourceName + "]"); + return null; + } + + InputStreamReader isr = null; try { - isr.close(); + URLConnection urlConnection = url.openConnection(); + urlConnection.setUseCaches(false); + isr = new InputStreamReader(urlConnection.getInputStream()); + char[] buf = new char[128]; + StringBuilder builder = new StringBuilder(); + int count = -1; + while ((count = isr.read(buf, 0, buf.length)) != -1) { + builder.append(buf, 0, count); + } + return builder.toString(); } catch (IOException e) { - // ignore + addError("Failed to open " + resourceName, e); + } finally { + if (isr != null) { + try { + isr.close(); + } catch (IOException e) { + // ignore + } + } } - } + return null; } - return null; - } - static final int BUF_SIZE = 32 * 1024; + static final int BUF_SIZE = 32 * 1024; - public void copy(String src, String destination) throws RolloverFailure { - BufferedInputStream bis = null; - BufferedOutputStream bos = null; - try { - bis = new BufferedInputStream(new FileInputStream(src)); - bos = new BufferedOutputStream(new FileOutputStream(destination)); - byte[] inbuf = new byte[BUF_SIZE]; - int n; + public void copy(String src, String destination) throws RolloverFailure { + BufferedInputStream bis = null; + BufferedOutputStream bos = null; + try { + bis = new BufferedInputStream(new FileInputStream(src)); + bos = new BufferedOutputStream(new FileOutputStream(destination)); + byte[] inbuf = new byte[BUF_SIZE]; + int n; - while ((n = bis.read(inbuf)) != -1) { - bos.write(inbuf, 0, n); - } + while ((n = bis.read(inbuf)) != -1) { + bos.write(inbuf, 0, n); + } - bis.close(); - bis = null; - bos.close(); - bos = null; - } catch (IOException ioe) { - String msg = "Failed to copy [" + src + "] to [" + destination + "]"; - addError(msg, ioe); - throw new RolloverFailure(msg); - } finally { - if (bis != null) { - try { - bis.close(); - } catch (IOException e) { - // ignore - } - } - if (bos != null) { - try { - bos.close(); - } catch (IOException e) { - // ignore + bis.close(); + bis = null; + bos.close(); + bos = null; + } catch (IOException ioe) { + String msg = "Failed to copy [" + src + "] to [" + destination + "]"; + addError(msg, ioe); + throw new RolloverFailure(msg); + } finally { + if (bis != null) { + try { + bis.close(); + } catch (IOException e) { + // ignore + } + } + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + // ignore + } + } } - } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/FixedDelay.java b/logback-core/src/main/java/ch/qos/logback/core/util/FixedDelay.java index 4bc28d11236a2bf742d148364bb6da49c938a1b7..2850c454dd1a5febc4f12214f836fffd16d19ca6 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/FixedDelay.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/FixedDelay.java @@ -21,39 +21,39 @@ package ch.qos.logback.core.util; */ public class FixedDelay implements DelayStrategy { - private final long subsequentDelay; - private long nextDelay; + private final long subsequentDelay; + private long nextDelay; - /** - * Initialize a new {@code FixedDelay} with a given {@code initialDelay} and - * {@code subsequentDelay}. - * - * @param initialDelay value for the initial delay - * @param subsequentDelay value for all other delays - */ - public FixedDelay(long initialDelay, long subsequentDelay) { - String s = new String(); - this.nextDelay = initialDelay; - this.subsequentDelay = subsequentDelay; - } + /** + * Initialize a new {@code FixedDelay} with a given {@code initialDelay} and + * {@code subsequentDelay}. + * + * @param initialDelay value for the initial delay + * @param subsequentDelay value for all other delays + */ + public FixedDelay(long initialDelay, long subsequentDelay) { + String s = new String(); + this.nextDelay = initialDelay; + this.subsequentDelay = subsequentDelay; + } - /** - * Initialize a new {@code FixedDelay} with fixed delay value given by {@code delay} - * parameter. - * - * @param delay value for all delays - */ - public FixedDelay(int delay) { - this(delay, delay); - } + /** + * Initialize a new {@code FixedDelay} with fixed delay value given by {@code delay} + * parameter. + * + * @param delay value for all delays + */ + public FixedDelay(int delay) { + this(delay, delay); + } - /** - * {@inheritDoc} - */ - public long nextDelay() { - long delay = nextDelay; - nextDelay = subsequentDelay; - return delay; - } + /** + * {@inheritDoc} + */ + public long nextDelay() { + long delay = nextDelay; + nextDelay = subsequentDelay; + return delay; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/IncompatibleClassException.java b/logback-core/src/main/java/ch/qos/logback/core/util/IncompatibleClassException.java index 16cf09f09ed6c6f1b0864d034ac5dc684afe5fa1..33412a703507bfca7ddd09e011b48439d00f84b6 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/IncompatibleClassException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/IncompatibleClassException.java @@ -15,14 +15,14 @@ package ch.qos.logback.core.util; public class IncompatibleClassException extends Exception { - private static final long serialVersionUID = -5823372159561159549L; + private static final long serialVersionUID = -5823372159561159549L; - Class requestedClass; - Class obtainedClass; - - IncompatibleClassException(Class requestedClass, Class obtainedClass) { - super(); - this.requestedClass = requestedClass; - this.obtainedClass = obtainedClass; - } + Class requestedClass; + Class obtainedClass; + + IncompatibleClassException(Class requestedClass, Class obtainedClass) { + super(); + this.requestedClass = requestedClass; + this.obtainedClass = obtainedClass; + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/InvocationGate.java b/logback-core/src/main/java/ch/qos/logback/core/util/InvocationGate.java index 166712f0a7b931fa9e7c138cb0bef32170f45085..b3f0fbf16415b3506d44f81603df86670b241372 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/InvocationGate.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/InvocationGate.java @@ -20,42 +20,39 @@ package ch.qos.logback.core.util; */ public class InvocationGate { - // experiments indicate that even for the most CPU intensive applications with 200 or more threads MASK - // values in the order of 0xFFFF is appropriate - private static final int MAX_MASK = 0xFFFF; + // experiments indicate that even for the most CPU intensive applications with 200 or more threads MASK + // values in the order of 0xFFFF is appropriate + private static final int MAX_MASK = 0xFFFF; - private volatile long mask = 0xF; - private volatile long lastMaskCheck = System.currentTimeMillis(); + private volatile long mask = 0xF; + private volatile long lastMaskCheck = System.currentTimeMillis(); + // IMPORTANT: This field can be updated by multiple threads. It follows that + // its values may *not* be incremented sequentially. However, we don't care + // about the actual value of the field except that from time to time the + // expression (invocationCounter++ & mask) == mask) should be true. + private long invocationCounter = 0; - // IMPORTANT: This field can be updated by multiple threads. It follows that - // its values may *not* be incremented sequentially. However, we don't care - // about the actual value of the field except that from time to time the - // expression (invocationCounter++ & mask) == mask) should be true. - private long invocationCounter = 0; + // if less than thresholdForMaskIncrease milliseconds elapse between invocations of updateMaskIfNecessary() + // method, then the mask should be increased + private static final long thresholdForMaskIncrease = 100; + // if more than thresholdForMaskDecrease milliseconds elapse between invocations of updateMaskIfNecessary() method, + // then the mask should be decreased + private final long thresholdForMaskDecrease = thresholdForMaskIncrease * 8; - // if less than thresholdForMaskIncrease milliseconds elapse between invocations of updateMaskIfNecessary() - // method, then the mask should be increased - private static final long thresholdForMaskIncrease = 100; - - // if more than thresholdForMaskDecrease milliseconds elapse between invocations of updateMaskIfNecessary() method, - // then the mask should be decreased - private final long thresholdForMaskDecrease = thresholdForMaskIncrease*8; - - - public boolean skipFurtherWork() { - return ((invocationCounter++) & mask) != mask; - } + public boolean skipFurtherWork() { + return ((invocationCounter++) & mask) != mask; + } - // update the mask so as to execute change detection code about once every 100 to 8000 milliseconds. - public void updateMaskIfNecessary(long now) { - final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck; - lastMaskCheck = now; - if (timeElapsedSinceLastMaskUpdateCheck < thresholdForMaskIncrease && (mask < MAX_MASK)) { - mask = (mask << 1) | 1; - } else if (timeElapsedSinceLastMaskUpdateCheck > thresholdForMaskDecrease) { - mask = mask >>> 2; + // update the mask so as to execute change detection code about once every 100 to 8000 milliseconds. + public void updateMaskIfNecessary(long now) { + final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck; + lastMaskCheck = now; + if (timeElapsedSinceLastMaskUpdateCheck < thresholdForMaskIncrease && (mask < MAX_MASK)) { + mask = (mask << 1) | 1; + } else if (timeElapsedSinceLastMaskUpdateCheck > thresholdForMaskDecrease) { + mask = mask >>> 2; + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/Loader.java b/logback-core/src/main/java/ch/qos/logback/core/util/Loader.java index 1c5e2f5a3e5b05f36eb08c4a0b69f63c7db2a301..8c1352825ff825786fe48309c956f644b2809f6d 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/Loader.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/Loader.java @@ -29,168 +29,163 @@ import ch.qos.logback.core.Context; * @author Ceki Gülcü */ public class Loader { - static final String TSTR = "Caught Exception while in Loader.getResource. This may be innocuous."; + static final String TSTR = "Caught Exception while in Loader.getResource. This may be innocuous."; - private static boolean ignoreTCL = false; - public static final String IGNORE_TCL_PROPERTY_NAME = "logback.ignoreTCL"; - private static boolean HAS_GET_CLASS_LOADER_PERMISSION = false; + private static boolean ignoreTCL = false; + public static final String IGNORE_TCL_PROPERTY_NAME = "logback.ignoreTCL"; + private static boolean HAS_GET_CLASS_LOADER_PERMISSION = false; - static { - String ignoreTCLProp = OptionHelper.getSystemProperty( - IGNORE_TCL_PROPERTY_NAME, null); + static { + String ignoreTCLProp = OptionHelper.getSystemProperty(IGNORE_TCL_PROPERTY_NAME, null); - if (ignoreTCLProp != null) { - ignoreTCL = OptionHelper.toBoolean(ignoreTCLProp, true); - } + if (ignoreTCLProp != null) { + ignoreTCL = OptionHelper.toBoolean(ignoreTCLProp, true); + } - HAS_GET_CLASS_LOADER_PERMISSION = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { + HAS_GET_CLASS_LOADER_PERMISSION = AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { try { - AccessController.checkPermission( - new RuntimePermission("getClassLoader")); - return true; + AccessController.checkPermission(new RuntimePermission("getClassLoader")); + return true; } catch (SecurityException e) { - // Using SecurityException instead of AccessControlException. - // See bug LOGBACK-760. - return false; + // Using SecurityException instead of AccessControlException. + // See bug LOGBACK-760. + return false; } - } - }); - } - - /** - * Compute the number of occurrences a resource can be found by a class - * loader. - * - * @param resource - * @param classLoader - * @return - * @throws IOException - */ - - public static Set getResources(String resource, ClassLoader classLoader) throws IOException { - // See LBCLASSIC-159 - Set urlSet = new HashSet(); - Enumeration urlEnum = classLoader.getResources(resource); - while (urlEnum.hasMoreElements()) { - URL url = urlEnum.nextElement(); - urlSet.add(url); + } + }); } - return urlSet; - } - - /** - * Search for a resource using the classloader passed as parameter. - * - * @param resource the resource name to look for - * @param classLoader the classloader used for the search - */ - public static URL getResource(String resource, ClassLoader classLoader) { - try { - return classLoader.getResource(resource); - } catch (Throwable t) { - return null; + + /** + * Compute the number of occurrences a resource can be found by a class + * loader. + * + * @param resource + * @param classLoader + * @return + * @throws IOException + */ + + public static Set getResources(String resource, ClassLoader classLoader) throws IOException { + // See LBCLASSIC-159 + Set urlSet = new HashSet(); + Enumeration urlEnum = classLoader.getResources(resource); + while (urlEnum.hasMoreElements()) { + URL url = urlEnum.nextElement(); + urlSet.add(url); + } + return urlSet; } - } - - /** - * Attempt to find a resource by using the classloader that loaded this class, - * namely Loader.class. - * - * @param resource - * @return - */ - public static URL getResourceBySelfClassLoader(String resource) { - return getResource(resource, getClassLoaderOfClass(Loader.class)); - } - - // private static URL getResourceByTCL(String resource) { - // return getResource(resource, getTCL()); - // } - - /** - * Get the Thread Context Loader which is a JDK 1.2 feature. If we are running - * under JDK 1.1 or anything else goes wrong the method returns - * null. - */ - public static ClassLoader getTCL() { - return Thread.currentThread().getContextClassLoader(); - } - - public static Class loadClass(String clazz, Context context) - throws ClassNotFoundException { - ClassLoader cl = getClassLoaderOfObject(context); - return cl.loadClass(clazz); - } - - /** - * Get the class loader of the object passed as argument. Return the system - * class loader if appropriate. - * - * @param o - * @return - */ - public static ClassLoader getClassLoaderOfObject(Object o) { - if (o == null) { - throw new NullPointerException("Argument cannot be null"); + + /** + * Search for a resource using the classloader passed as parameter. + * + * @param resource the resource name to look for + * @param classLoader the classloader used for the search + */ + public static URL getResource(String resource, ClassLoader classLoader) { + try { + return classLoader.getResource(resource); + } catch (Throwable t) { + return null; + } } - return getClassLoaderOfClass(o.getClass()); - } - - /** - * Returns the class loader of clazz in an access privileged section. - * - * @param clazz - * @return - */ - public static ClassLoader getClassLoaderAsPrivileged(final Class clazz) { - if (!HAS_GET_CLASS_LOADER_PERMISSION) - return null; - else - return AccessController.doPrivileged( - new PrivilegedAction() { + + /** + * Attempt to find a resource by using the classloader that loaded this class, + * namely Loader.class. + * + * @param resource + * @return + */ + public static URL getResourceBySelfClassLoader(String resource) { + return getResource(resource, getClassLoaderOfClass(Loader.class)); + } + + // private static URL getResourceByTCL(String resource) { + // return getResource(resource, getTCL()); + // } + + /** + * Get the Thread Context Loader which is a JDK 1.2 feature. If we are running + * under JDK 1.1 or anything else goes wrong the method returns + * null. + */ + public static ClassLoader getTCL() { + return Thread.currentThread().getContextClassLoader(); + } + + public static Class loadClass(String clazz, Context context) throws ClassNotFoundException { + ClassLoader cl = getClassLoaderOfObject(context); + return cl.loadClass(clazz); + } + + /** + * Get the class loader of the object passed as argument. Return the system + * class loader if appropriate. + * + * @param o + * @return + */ + public static ClassLoader getClassLoaderOfObject(Object o) { + if (o == null) { + throw new NullPointerException("Argument cannot be null"); + } + return getClassLoaderOfClass(o.getClass()); + } + + /** + * Returns the class loader of clazz in an access privileged section. + * + * @param clazz + * @return + */ + public static ClassLoader getClassLoaderAsPrivileged(final Class clazz) { + if (!HAS_GET_CLASS_LOADER_PERMISSION) + return null; + else + return AccessController.doPrivileged(new PrivilegedAction() { public ClassLoader run() { - return clazz.getClassLoader(); + return clazz.getClassLoader(); } - }); - } - - /** - * Return the class loader which loaded the class passed as argument. Return - * the system class loader if appropriate. - * - * @param clazz - * @return - */ - public static ClassLoader getClassLoaderOfClass(final Class clazz) { - ClassLoader cl = clazz.getClassLoader(); - if (cl == null) { - return ClassLoader.getSystemClassLoader(); - } else { - return cl; + }); + } + + /** + * Return the class loader which loaded the class passed as argument. Return + * the system class loader if appropriate. + * + * @param clazz + * @return + */ + public static ClassLoader getClassLoaderOfClass(final Class clazz) { + ClassLoader cl = clazz.getClassLoader(); + if (cl == null) { + return ClassLoader.getSystemClassLoader(); + } else { + return cl; + } } - } - - /** - * If running under JDK 1.2 load the specified class using the - * Thread contextClassLoader if that fails try - * Class.forname. Under JDK 1.1 only Class.forName is used. - */ - public static Class loadClass(String clazz) throws ClassNotFoundException { - // Just call Class.forName(clazz) if we are running under JDK 1.1 - // or if we are instructed to ignore the TCL. - if (ignoreTCL) { - return Class.forName(clazz); - } else { - try { - return getTCL().loadClass(clazz); - } catch (Throwable e) { - // we reached here because tcl was null or because of a - // security exception, or because clazz could not be loaded... - // In any case we now try one more time - return Class.forName(clazz); - } + + /** + * If running under JDK 1.2 load the specified class using the + * Thread contextClassLoader if that fails try + * Class.forname. Under JDK 1.1 only Class.forName is used. + */ + public static Class loadClass(String clazz) throws ClassNotFoundException { + // Just call Class.forName(clazz) if we are running under JDK 1.1 + // or if we are instructed to ignore the TCL. + if (ignoreTCL) { + return Class.forName(clazz); + } else { + try { + return getTCL().loadClass(clazz); + } catch (Throwable e) { + // we reached here because tcl was null or because of a + // security exception, or because clazz could not be loaded... + // In any case we now try one more time + return Class.forName(clazz); + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/LocationUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/LocationUtil.java index aec91762f41555d051c4ec9fa507a18da9f710d1..9c86a0fd409f41f272d266fdfed8983f28f7554e 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/LocationUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/LocationUtil.java @@ -17,7 +17,6 @@ import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.net.URL; - /** * A static utility method that converts a string that describes the * location of a resource into a {@link URL} object. @@ -26,50 +25,45 @@ import java.net.URL; */ public class LocationUtil { - - /** Regex pattern for a URL scheme (reference RFC 2396 section 3) */ - public static final String SCHEME_PATTERN = - "^\\p{Alpha}[\\p{Alnum}+.-]*:.*$"; + /** Regex pattern for a URL scheme (reference RFC 2396 section 3) */ + public static final String SCHEME_PATTERN = "^\\p{Alpha}[\\p{Alnum}+.-]*:.*$"; - /** Scheme name for a classpath resource */ - public static final String CLASSPATH_SCHEME = "classpath:"; - - /** - * Converts a string describing the location of a resource into a URL object. - * @param location String describing the location - * @return URL object that refers to {@code location} - * @throws MalformedURLException if {@code location} is not a syntatically - * valid URL - * @throws FileNotFoundException if {@code location} specifies a non-existent - * classpath resource - * @throws NullPointerException if {@code location} is {@code null} - */ - public static URL urlForResource(String location) - throws MalformedURLException, FileNotFoundException { - if (location == null) { - throw new NullPointerException("location is required"); - } - URL url = null; - if (!location.matches(SCHEME_PATTERN)) { - url = Loader.getResourceBySelfClassLoader(location); - } - else if (location.startsWith(CLASSPATH_SCHEME)) { - String path = location.substring(CLASSPATH_SCHEME.length()); - if (path.startsWith("/")) { - path = path.substring(1); - } - if (path.length() == 0) { - throw new MalformedURLException("path is required"); - } - url = Loader.getResourceBySelfClassLoader(path); - } - else { - url = new URL(location); - } - if (url == null) { - throw new FileNotFoundException(location); + /** Scheme name for a classpath resource */ + public static final String CLASSPATH_SCHEME = "classpath:"; + + /** + * Converts a string describing the location of a resource into a URL object. + * @param location String describing the location + * @return URL object that refers to {@code location} + * @throws MalformedURLException if {@code location} is not a syntatically + * valid URL + * @throws FileNotFoundException if {@code location} specifies a non-existent + * classpath resource + * @throws NullPointerException if {@code location} is {@code null} + */ + public static URL urlForResource(String location) throws MalformedURLException, FileNotFoundException { + if (location == null) { + throw new NullPointerException("location is required"); + } + URL url = null; + if (!location.matches(SCHEME_PATTERN)) { + url = Loader.getResourceBySelfClassLoader(location); + } else if (location.startsWith(CLASSPATH_SCHEME)) { + String path = location.substring(CLASSPATH_SCHEME.length()); + if (path.startsWith("/")) { + path = path.substring(1); + } + if (path.length() == 0) { + throw new MalformedURLException("path is required"); + } + url = Loader.getResourceBySelfClassLoader(path); + } else { + url = new URL(location); + } + if (url == null) { + throw new FileNotFoundException(location); + } + return url; } - return url; - } - + } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/OptionHelper.java b/logback-core/src/main/java/ch/qos/logback/core/util/OptionHelper.java index f7d12308367900687e1d19db91cb7b6534f7f637..52a141fcb2a7b2613e04ab877560a6f574829ad5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/OptionHelper.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/OptionHelper.java @@ -28,245 +28,237 @@ import ch.qos.logback.core.subst.NodeToStringTransformer; */ public class OptionHelper { - public static Object instantiateByClassName(String className, - Class superClass, Context context) throws IncompatibleClassException, - DynamicClassLoadingException { - ClassLoader classLoader = Loader.getClassLoaderOfObject(context); - return instantiateByClassName(className, superClass, classLoader); - } - - public static Object instantiateByClassNameAndParameter(String className, - Class superClass, Context context, Class type, Object param) throws IncompatibleClassException, - DynamicClassLoadingException { - ClassLoader classLoader = Loader.getClassLoaderOfObject(context); - return instantiateByClassNameAndParameter(className, superClass, classLoader, type, param); - } - - public static Object instantiateByClassName(String className, - Class superClass, ClassLoader classLoader) - throws IncompatibleClassException, DynamicClassLoadingException { - return instantiateByClassNameAndParameter(className, superClass, classLoader, null, null); - } - - public static Object instantiateByClassNameAndParameter(String className, - Class superClass, ClassLoader classLoader, Class type, Object parameter) - throws IncompatibleClassException, DynamicClassLoadingException { - - if (className == null) { - throw new NullPointerException(); - } - try { - Class classObj = null; - classObj = classLoader.loadClass(className); - if (!superClass.isAssignableFrom(classObj)) { - throw new IncompatibleClassException(superClass, classObj); - } - if (type == null) { - return classObj.newInstance(); - } else { - Constructor constructor = classObj.getConstructor(type); - return constructor.newInstance(parameter); - } - } catch (IncompatibleClassException ice) { - throw ice; - } catch (Throwable t) { - throw new DynamicClassLoadingException("Failed to instantiate type " - + className, t); + public static Object instantiateByClassName(String className, Class superClass, Context context) throws IncompatibleClassException, + DynamicClassLoadingException { + ClassLoader classLoader = Loader.getClassLoaderOfObject(context); + return instantiateByClassName(className, superClass, classLoader); } - } - - /** - * Find the value corresponding to key in props. - * Then perform variable substitution on the found value. - */ - // public static String findAndSubst(String key, Properties props) { - // String value = props.getProperty(key); - // - // if (value == null) { - // return null; - // } - // - // try { - // return substVars(value, props); - // } catch (IllegalArgumentException e) { - // return value; - // } - // } - final static String DELIM_START = "${"; - final static char DELIM_STOP = '}'; - final static String DELIM_DEFAULT = ":-"; - - final static int DELIM_START_LEN = 2; - final static int DELIM_STOP_LEN = 1; - final static int DELIM_DEFAULT_LEN = 2; - - final static String _IS_UNDEFINED = "_IS_UNDEFINED"; - - /** - * @see #substVars(String, PropertyContainer, PropertyContainer) - */ - public static String substVars(String val, PropertyContainer pc1) { - return substVars(val, pc1, null); - } - /** - * See http://logback.qos.ch/manual/configuration.html#variableSubstitution - */ - public static String substVars(String input, PropertyContainer pc0, PropertyContainer pc1) { - try { - return NodeToStringTransformer.substituteVariable(input, pc0, pc1); - } catch (ScanException e) { - throw new IllegalArgumentException("Failed to parse input [" + input + "]", e); + public static Object instantiateByClassNameAndParameter(String className, Class superClass, Context context, Class type, Object param) + throws IncompatibleClassException, DynamicClassLoadingException { + ClassLoader classLoader = Loader.getClassLoaderOfObject(context); + return instantiateByClassNameAndParameter(className, superClass, classLoader, type, param); } - } - public static String propertyLookup(String key, PropertyContainer pc1, - PropertyContainer pc2) { - String value = null; - // first try the props passed as parameter - value = pc1.getProperty(key); - - // then try the pc2 - if (value == null && pc2 != null) { - value = pc2.getProperty(key); - } - // then try in System properties - if (value == null) { - value = getSystemProperty(key, null); - } - if (value == null) { - value = getEnv(key); + public static Object instantiateByClassName(String className, Class superClass, ClassLoader classLoader) throws IncompatibleClassException, + DynamicClassLoadingException { + return instantiateByClassNameAndParameter(className, superClass, classLoader, null, null); } - return value; - } - /** - * Very similar to System.getProperty except that the - * {@link SecurityException} is absorbed. - * - * @param key The key to search for. - * @param def The default value to return. - * @return the string value of the system property, or the default value if - * there is no property with that key. - */ - public static String getSystemProperty(String key, String def) { - try { - return System.getProperty(key, def); - } catch (SecurityException e) { - return def; + public static Object instantiateByClassNameAndParameter(String className, Class superClass, ClassLoader classLoader, Class type, Object parameter) + throws IncompatibleClassException, DynamicClassLoadingException { + + if (className == null) { + throw new NullPointerException(); + } + try { + Class classObj = null; + classObj = classLoader.loadClass(className); + if (!superClass.isAssignableFrom(classObj)) { + throw new IncompatibleClassException(superClass, classObj); + } + if (type == null) { + return classObj.newInstance(); + } else { + Constructor constructor = classObj.getConstructor(type); + return constructor.newInstance(parameter); + } + } catch (IncompatibleClassException ice) { + throw ice; + } catch (Throwable t) { + throw new DynamicClassLoadingException("Failed to instantiate type " + className, t); + } } - } - /** - * Lookup a key from the environment. - * - * @param key - * @return value corresponding to key from the OS environment - */ - public static String getEnv(String key) { - try { - return System.getenv(key); - } catch (SecurityException e) { - return null; + /** + * Find the value corresponding to key in props. + * Then perform variable substitution on the found value. + */ + // public static String findAndSubst(String key, Properties props) { + // String value = props.getProperty(key); + // + // if (value == null) { + // return null; + // } + // + // try { + // return substVars(value, props); + // } catch (IllegalArgumentException e) { + // return value; + // } + // } + final static String DELIM_START = "${"; + final static char DELIM_STOP = '}'; + final static String DELIM_DEFAULT = ":-"; + + final static int DELIM_START_LEN = 2; + final static int DELIM_STOP_LEN = 1; + final static int DELIM_DEFAULT_LEN = 2; + + final static String _IS_UNDEFINED = "_IS_UNDEFINED"; + + /** + * @see #substVars(String, PropertyContainer, PropertyContainer) + */ + public static String substVars(String val, PropertyContainer pc1) { + return substVars(val, pc1, null); } - } - - /** - * Very similar to System.getProperty except that the - * {@link SecurityException} is absorbed. - * - * @param key The key to search for. - * @return the string value of the system property. - */ - public static String getSystemProperty(String key) { - try { - return System.getProperty(key); - } catch (SecurityException e) { - return null; + /** + * See http://logback.qos.ch/manual/configuration.html#variableSubstitution + */ + public static String substVars(String input, PropertyContainer pc0, PropertyContainer pc1) { + try { + return NodeToStringTransformer.substituteVariable(input, pc0, pc1); + } catch (ScanException e) { + throw new IllegalArgumentException("Failed to parse input [" + input + "]", e); + } } - } - public static void setSystemProperties(ContextAware contextAware, Properties props) { - for (Object o : props.keySet()) { - String key = (String) o; - String value = props.getProperty(key); - setSystemProperty(contextAware, key, value); + public static String propertyLookup(String key, PropertyContainer pc1, PropertyContainer pc2) { + String value = null; + // first try the props passed as parameter + value = pc1.getProperty(key); + + // then try the pc2 + if (value == null && pc2 != null) { + value = pc2.getProperty(key); + } + // then try in System properties + if (value == null) { + value = getSystemProperty(key, null); + } + if (value == null) { + value = getEnv(key); + } + return value; } - } - public static void setSystemProperty(ContextAware contextAware, String key, String value) { - try { - System.setProperty(key, value); - } catch (SecurityException e) { - contextAware.addError("Failed to set system property [" + key + "]", e); + /** + * Very similar to System.getProperty except that the + * {@link SecurityException} is absorbed. + * + * @param key The key to search for. + * @param def The default value to return. + * @return the string value of the system property, or the default value if + * there is no property with that key. + */ + public static String getSystemProperty(String key, String def) { + try { + return System.getProperty(key, def); + } catch (SecurityException e) { + return def; + } } - } - /** - * Very similar to {@link System#getProperties()} except that the - * {@link SecurityException} is absorbed. - * - * @return the system properties - */ - public static Properties getSystemProperties() { - try { - return System.getProperties(); - } catch (SecurityException e) { - return new Properties(); + /** + * Lookup a key from the environment. + * + * @param key + * @return value corresponding to key from the OS environment + */ + public static String getEnv(String key) { + try { + return System.getenv(key); + } catch (SecurityException e) { + return null; + } } - } - - /** - * Return a String[] of size two. The first item containing the key part and the second item - * containing a default value specified by the user. The second item will be null if no default value - * is specified. - * - * @param key - * @return - */ - static public String[] extractDefaultReplacement(String key) { - String[] result = new String[2]; - if(key == null) - return result; - result[0] = key; - int d = key.indexOf(DELIM_DEFAULT); - if (d != -1) { - result[0] = key.substring(0, d); - result[1] = key.substring(d + DELIM_DEFAULT_LEN); + /** + * Very similar to System.getProperty except that the + * {@link SecurityException} is absorbed. + * + * @param key The key to search for. + * @return the string value of the system property. + */ + public static String getSystemProperty(String key) { + try { + return System.getProperty(key); + } catch (SecurityException e) { + return null; + } } - return result; - } - /** - * If value is "true", then true is returned. If - * value is "false", then true is returned. - * Otherwise, default is returned. - *

- *

Case of value is unimportant. - */ - public static boolean toBoolean(String value, boolean dEfault) { - if (value == null) { - return dEfault; + public static void setSystemProperties(ContextAware contextAware, Properties props) { + for (Object o : props.keySet()) { + String key = (String) o; + String value = props.getProperty(key); + setSystemProperty(contextAware, key, value); + } } - String trimmedVal = value.trim(); - - if ("true".equalsIgnoreCase(trimmedVal)) { - return true; + public static void setSystemProperty(ContextAware contextAware, String key, String value) { + try { + System.setProperty(key, value); + } catch (SecurityException e) { + contextAware.addError("Failed to set system property [" + key + "]", e); + } } - if ("false".equalsIgnoreCase(trimmedVal)) { - return false; + /** + * Very similar to {@link System#getProperties()} except that the + * {@link SecurityException} is absorbed. + * + * @return the system properties + */ + public static Properties getSystemProperties() { + try { + return System.getProperties(); + } catch (SecurityException e) { + return new Properties(); + } } - return dEfault; - } + /** + * Return a String[] of size two. The first item containing the key part and the second item + * containing a default value specified by the user. The second item will be null if no default value + * is specified. + * + * @param key + * @return + */ + static public String[] extractDefaultReplacement(String key) { + String[] result = new String[2]; + if (key == null) + return result; + + result[0] = key; + int d = key.indexOf(DELIM_DEFAULT); + if (d != -1) { + result[0] = key.substring(0, d); + result[1] = key.substring(d + DELIM_DEFAULT_LEN); + } + return result; + } - public static boolean isEmpty(String str) { - return ((str == null) || CoreConstants.EMPTY_STRING.equals(str)); - } + /** + * If value is "true", then true is returned. If + * value is "false", then true is returned. + * Otherwise, default is returned. + *

+ *

Case of value is unimportant. + */ + public static boolean toBoolean(String value, boolean dEfault) { + if (value == null) { + return dEfault; + } + + String trimmedVal = value.trim(); + + if ("true".equalsIgnoreCase(trimmedVal)) { + return true; + } + + if ("false".equalsIgnoreCase(trimmedVal)) { + return false; + } + + return dEfault; + } + public static boolean isEmpty(String str) { + return ((str == null) || CoreConstants.EMPTY_STRING.equals(str)); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/PropertySetterException.java b/logback-core/src/main/java/ch/qos/logback/core/util/PropertySetterException.java index e66743d019dd1b5074ddc338b94df77c5a8a800a..b97142703f7024719aaac4028e0916d7683f8920 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/PropertySetterException.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/PropertySetterException.java @@ -21,17 +21,17 @@ package ch.qos.logback.core.util; */ public class PropertySetterException extends Exception { - private static final long serialVersionUID = -2771077768281663949L; + private static final long serialVersionUID = -2771077768281663949L; - public PropertySetterException(String msg) { - super(msg); - } + public PropertySetterException(String msg) { + super(msg); + } - public PropertySetterException(Throwable rootCause) { - super(rootCause); - } + public PropertySetterException(Throwable rootCause) { + super(rootCause); + } - public PropertySetterException(String message, Throwable cause) { - super(message, cause); - } + public PropertySetterException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/StatusListenerConfigHelper.java b/logback-core/src/main/java/ch/qos/logback/core/util/StatusListenerConfigHelper.java index 1ad0c572151b7f75b913ab8f88659b3d9a489cd2..b23db40760ca93e60e19c648691c260bdb3b7fa7 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/StatusListenerConfigHelper.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/StatusListenerConfigHelper.java @@ -72,7 +72,7 @@ public class StatusListenerConfigHelper { static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) { onConsoleStatusListener.setContext(context); boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener); - if(effectivelyAdded) { + if (effectivelyAdded) { onConsoleStatusListener.start(); } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/StatusPrinter.java b/logback-core/src/main/java/ch/qos/logback/core/util/StatusPrinter.java index f6dc5cc155b94e79a648737a317edde90252fa87..8c07be0e1cf9df6b2036873525ebd9d14c21d875 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/util/StatusPrinter.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/StatusPrinter.java @@ -26,170 +26,163 @@ import static ch.qos.logback.core.status.StatusUtil.filterStatusListByTimeThresh public class StatusPrinter { - private static PrintStream ps = System.out; - - static CachingDateFormatter cachingDateFormat = new CachingDateFormatter( - "HH:mm:ss,SSS"); - - public static void setPrintStream(PrintStream printStream) { - ps = printStream; - } - - /** - * Print the contents of the context statuses, but only if they contain - * warnings or errors. - * - * @param context - */ - public static void printInCaseOfErrorsOrWarnings(Context context) { - printInCaseOfErrorsOrWarnings(context, 0); - } - - /** - * Print the contents of the context status, but only if they contain - * warnings or errors occurring later then the threshold. - * - * @param context - */ - public static void printInCaseOfErrorsOrWarnings(Context context, long threshold) { - if (context == null) { - throw new IllegalArgumentException("Context argument cannot be null"); + private static PrintStream ps = System.out; + + static CachingDateFormatter cachingDateFormat = new CachingDateFormatter("HH:mm:ss,SSS"); + + public static void setPrintStream(PrintStream printStream) { + ps = printStream; } - StatusManager sm = context.getStatusManager(); - if (sm == null) { - ps.println("WARN: Context named \"" + context.getName() - + "\" has no status manager"); - } else { - StatusUtil statusUtil = new StatusUtil(context); - if (statusUtil.getHighestLevel(threshold) >= ErrorStatus.WARN) { - print(sm, threshold); - } + /** + * Print the contents of the context statuses, but only if they contain + * warnings or errors. + * + * @param context + */ + public static void printInCaseOfErrorsOrWarnings(Context context) { + printInCaseOfErrorsOrWarnings(context, 0); } - } - - /** - * Print the contents of the context statuses, but only if they contain - * errors. - * - * @param context - */ - public static void printIfErrorsOccured(Context context) { - if (context == null) { - throw new IllegalArgumentException("Context argument cannot be null"); + + /** + * Print the contents of the context status, but only if they contain + * warnings or errors occurring later then the threshold. + * + * @param context + */ + public static void printInCaseOfErrorsOrWarnings(Context context, long threshold) { + if (context == null) { + throw new IllegalArgumentException("Context argument cannot be null"); + } + + StatusManager sm = context.getStatusManager(); + if (sm == null) { + ps.println("WARN: Context named \"" + context.getName() + "\" has no status manager"); + } else { + StatusUtil statusUtil = new StatusUtil(context); + if (statusUtil.getHighestLevel(threshold) >= ErrorStatus.WARN) { + print(sm, threshold); + } + } } - StatusManager sm = context.getStatusManager(); - if (sm == null) { - ps.println("WARN: Context named \"" + context.getName() - + "\" has no status manager"); - } else { - StatusUtil statusUtil = new StatusUtil(context); - if (statusUtil.getHighestLevel(0) == ErrorStatus.ERROR) { - print(sm); - } + /** + * Print the contents of the context statuses, but only if they contain + * errors. + * + * @param context + */ + public static void printIfErrorsOccured(Context context) { + if (context == null) { + throw new IllegalArgumentException("Context argument cannot be null"); + } + + StatusManager sm = context.getStatusManager(); + if (sm == null) { + ps.println("WARN: Context named \"" + context.getName() + "\" has no status manager"); + } else { + StatusUtil statusUtil = new StatusUtil(context); + if (statusUtil.getHighestLevel(0) == ErrorStatus.ERROR) { + print(sm); + } + } } - } - - /** - * Print the contents of the context's status data. - * - * @param context - */ - public static void print(Context context) { - print(context, 0); - } - - /** - * Print context's status data with a timestamp higher than the threshold. - * @param context - */ - public static void print(Context context, long threshold) { - if (context == null) { - throw new IllegalArgumentException("Context argument cannot be null"); - } - - StatusManager sm = context.getStatusManager(); - if (sm == null) { - ps.println("WARN: Context named \"" + context.getName() - + "\" has no status manager"); - } else { - print(sm, threshold); - } - } - - public static void print(StatusManager sm) { - print(sm, 0); - } - - public static void print(StatusManager sm, long threshold) { - StringBuilder sb = new StringBuilder(); - List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); - buildStrFromStatusList(sb, filteredList); - ps.println(sb.toString()); - } - - - public static void print(List statusList) { - StringBuilder sb = new StringBuilder(); - buildStrFromStatusList(sb, statusList); - ps.println(sb.toString()); - } - - - private static void buildStrFromStatusList(StringBuilder sb, List statusList) { - if(statusList == null) - return; - for(Status s : statusList) { - buildStr(sb, "", s); + + /** + * Print the contents of the context's status data. + * + * @param context + */ + public static void print(Context context) { + print(context, 0); } - } - -// private static void buildStrFromStatusManager(StringBuilder sb, StatusManager sm) { -// } - - - private static void appendThrowable(StringBuilder sb, Throwable t) { - String[] stringRep = ThrowableToStringArray.convert(t); - - for (String s : stringRep) { - if (s.startsWith(CoreConstants.CAUSED_BY)) { - // nothing - } else if (Character.isDigit(s.charAt(0))) { - // if line resembles "48 common frames omitted" - sb.append("\t... "); - } else { - // most of the time. just add a tab+"at" - sb.append("\tat "); - } - sb.append(s).append(CoreConstants.LINE_SEPARATOR); + + /** + * Print context's status data with a timestamp higher than the threshold. + * @param context + */ + public static void print(Context context, long threshold) { + if (context == null) { + throw new IllegalArgumentException("Context argument cannot be null"); + } + + StatusManager sm = context.getStatusManager(); + if (sm == null) { + ps.println("WARN: Context named \"" + context.getName() + "\" has no status manager"); + } else { + print(sm, threshold); + } } - } - - public static void buildStr(StringBuilder sb, String indentation, Status s) { - String prefix; - if (s.hasChildren()) { - prefix = indentation + "+ "; - } else { - prefix = indentation + "|-"; + + public static void print(StatusManager sm) { + print(sm, 0); } - if (cachingDateFormat != null) { - String dateStr = cachingDateFormat.format(s.getDate()); - sb.append(dateStr).append(" "); + public static void print(StatusManager sm, long threshold) { + StringBuilder sb = new StringBuilder(); + List filteredList = filterStatusListByTimeThreshold(sm.getCopyOfStatusList(), threshold); + buildStrFromStatusList(sb, filteredList); + ps.println(sb.toString()); } - sb.append(prefix).append(s).append(CoreConstants.LINE_SEPARATOR); - if (s.getThrowable() != null) { - appendThrowable(sb, s.getThrowable()); + public static void print(List statusList) { + StringBuilder sb = new StringBuilder(); + buildStrFromStatusList(sb, statusList); + ps.println(sb.toString()); } - if (s.hasChildren()) { - Iterator ite = s.iterator(); - while (ite.hasNext()) { - Status child = ite.next(); - buildStr(sb, indentation + " ", child); - } + + private static void buildStrFromStatusList(StringBuilder sb, List statusList) { + if (statusList == null) + return; + for (Status s : statusList) { + buildStr(sb, "", s); + } + } + + // private static void buildStrFromStatusManager(StringBuilder sb, StatusManager sm) { + // } + + private static void appendThrowable(StringBuilder sb, Throwable t) { + String[] stringRep = ThrowableToStringArray.convert(t); + + for (String s : stringRep) { + if (s.startsWith(CoreConstants.CAUSED_BY)) { + // nothing + } else if (Character.isDigit(s.charAt(0))) { + // if line resembles "48 common frames omitted" + sb.append("\t... "); + } else { + // most of the time. just add a tab+"at" + sb.append("\tat "); + } + sb.append(s).append(CoreConstants.LINE_SEPARATOR); + } + } + + public static void buildStr(StringBuilder sb, String indentation, Status s) { + String prefix; + if (s.hasChildren()) { + prefix = indentation + "+ "; + } else { + prefix = indentation + "|-"; + } + + if (cachingDateFormat != null) { + String dateStr = cachingDateFormat.format(s.getDate()); + sb.append(dateStr).append(" "); + } + sb.append(prefix).append(s).append(CoreConstants.LINE_SEPARATOR); + + if (s.getThrowable() != null) { + appendThrowable(sb, s.getThrowable()); + } + if (s.hasChildren()) { + Iterator ite = s.iterator(); + while (ite.hasNext()) { + Status child = ite.next(); + buildStr(sb, indentation + " ", child); + } + } } - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/StringCollectionUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/StringCollectionUtil.java index 666f8506da10aeccb0580a16bff6f75b03aa18f8..7cd42f0de4ed6372fe8d3c250af3f4dfa719fa50 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/StringCollectionUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/StringCollectionUtil.java @@ -26,87 +26,84 @@ import java.util.regex.Pattern; */ public class StringCollectionUtil { - /** - * Retains all values in the subject collection that are matched by - * at least one of a collection of regular expressions. - *

- * This method is a convenience overload for - * {@link #retainMatching(Collection, Collection)}. - * - * @param values subject value collection - * @param patterns patterns to match - */ - @SuppressWarnings("unchecked") - public static void retainMatching(Collection values, - String... patterns) { - retainMatching(values, Arrays.asList(patterns)); - } + /** + * Retains all values in the subject collection that are matched by + * at least one of a collection of regular expressions. + *

+ * This method is a convenience overload for + * {@link #retainMatching(Collection, Collection)}. + * + * @param values subject value collection + * @param patterns patterns to match + */ + @SuppressWarnings("unchecked") + public static void retainMatching(Collection values, String... patterns) { + retainMatching(values, Arrays.asList(patterns)); + } - /** - * Retains all values in the subject collection that are matched by - * at least one of a collection of regular expressions. - *

- * The semantics of this method are conceptually similar to - * {@link Collection#retainAll(Collection)}, but uses pattern matching - * instead of exact matching. - * - * @param values subject value collection - * @param patterns patterns to match - */ - public static void retainMatching(Collection values, - Collection patterns) { - if (patterns.isEmpty()) return; - List matches = new ArrayList(values.size()); - for (String p : patterns) { - Pattern pattern = Pattern.compile(p); - for (String value : values) { - if (pattern.matcher(value).matches()) { - matches.add(value); + /** + * Retains all values in the subject collection that are matched by + * at least one of a collection of regular expressions. + *

+ * The semantics of this method are conceptually similar to + * {@link Collection#retainAll(Collection)}, but uses pattern matching + * instead of exact matching. + * + * @param values subject value collection + * @param patterns patterns to match + */ + public static void retainMatching(Collection values, Collection patterns) { + if (patterns.isEmpty()) + return; + List matches = new ArrayList(values.size()); + for (String p : patterns) { + Pattern pattern = Pattern.compile(p); + for (String value : values) { + if (pattern.matcher(value).matches()) { + matches.add(value); + } + } } - } + values.retainAll(matches); + } + + /** + * Removes all values in the subject collection that are matched by + * at least one of a collection of regular expressions. + *

+ * This method is a convenience overload for + * {@link #removeMatching(Collection, Collection)}. + * + * @param values subject value collection + * @param patterns patterns to match + */ + @SuppressWarnings("unchecked") + public static void removeMatching(Collection values, String... patterns) { + removeMatching(values, Arrays.asList(patterns)); } - values.retainAll(matches); - } - - /** - * Removes all values in the subject collection that are matched by - * at least one of a collection of regular expressions. - *

- * This method is a convenience overload for - * {@link #removeMatching(Collection, Collection)}. - * - * @param values subject value collection - * @param patterns patterns to match - */ - @SuppressWarnings("unchecked") - public static void removeMatching(Collection values, - String... patterns) { - removeMatching(values, Arrays.asList(patterns)); - } - /** - * Removes all values in the subject collection that are matched by - * at least one of a collection of regular expressions. - *

- * The semantics of this method are conceptually similar to - * {@link Collection#removeAll(Collection)}, but uses pattern matching - * instead of exact matching. - * - * @param values subject value collection - * @param patterns patterns to match - */ - public static void removeMatching(Collection values, - Collection patterns) { - List matches = new ArrayList(values.size()); - for (String p : patterns) { - Pattern pattern = Pattern.compile(p); - for (String value : values) { - if (pattern.matcher(value).matches()) { - matches.add(value); + /** + * Removes all values in the subject collection that are matched by + * at least one of a collection of regular expressions. + *

+ * The semantics of this method are conceptually similar to + * {@link Collection#removeAll(Collection)}, but uses pattern matching + * instead of exact matching. + * + * @param values subject value collection + * @param patterns patterns to match + */ + public static void removeMatching(Collection values, Collection patterns) { + List matches = new ArrayList(values.size()); + for (String p : patterns) { + Pattern pattern = Pattern.compile(p); + for (String value : values) { + if (pattern.matcher(value).matches()) { + matches.add(value); + } + } } - } + values.removeAll(matches); } - values.removeAll(matches); - } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/SystemInfo.java b/logback-core/src/main/java/ch/qos/logback/core/util/SystemInfo.java index 57f7c4a675f2e7fcaf4949e42fe4b245961ed9e0..2e8134abb9191c5981ddee39494abc2e117ac1bf 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/SystemInfo.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/SystemInfo.java @@ -13,12 +13,10 @@ */ package ch.qos.logback.core.util; - - public class SystemInfo { - - public static String getJavaVendor() { - return OptionHelper.getSystemProperty("java.vendor", null); - } + + public static String getJavaVendor() { + return OptionHelper.getSystemProperty("java.vendor", null); + } } diff --git a/logback-core/src/main/java/ch/qos/logback/core/util/TimeUtil.java b/logback-core/src/main/java/ch/qos/logback/core/util/TimeUtil.java index e32247d9f82d9cd5a9e097388fd5c35324828087..de6740dd49ca4b7a2bbfc7387874f5a36126f1df 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/util/TimeUtil.java +++ b/logback-core/src/main/java/ch/qos/logback/core/util/TimeUtil.java @@ -18,72 +18,69 @@ import java.util.Date; public class TimeUtil { - - public static long computeStartOfNextSecond(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); - cal.set(Calendar.MILLISECOND, 0); - cal.add(Calendar.SECOND, 1); - return cal.getTime().getTime(); - } + public static long computeStartOfNextSecond(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + cal.set(Calendar.MILLISECOND, 0); + cal.add(Calendar.SECOND, 1); + return cal.getTime().getTime(); + } - public static long computeStartOfNextMinute(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); - cal.set(Calendar.MILLISECOND, 0); - cal.set(Calendar.SECOND, 0); - cal.add(Calendar.MINUTE, 1); - return cal.getTime().getTime(); - } + public static long computeStartOfNextMinute(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + cal.set(Calendar.MILLISECOND, 0); + cal.set(Calendar.SECOND, 0); + cal.add(Calendar.MINUTE, 1); + return cal.getTime().getTime(); + } - public static long computeStartOfNextHour(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); - cal.set(Calendar.MILLISECOND, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MINUTE, 0); - cal.add(Calendar.HOUR, 1); - return cal.getTime().getTime(); - } - - public static long computeStartOfNextDay(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); + public static long computeStartOfNextHour(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + cal.set(Calendar.MILLISECOND, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MINUTE, 0); + cal.add(Calendar.HOUR, 1); + return cal.getTime().getTime(); + } - cal.add(Calendar.DAY_OF_MONTH, 1); - cal.set(Calendar.MILLISECOND, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.HOUR_OF_DAY, 0); - return cal.getTime().getTime(); - } - - public static long computeStartOfNextWeek(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); - - cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - cal.add(Calendar.WEEK_OF_YEAR, 1); - return cal.getTime().getTime(); - } + public static long computeStartOfNextDay(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); - public static long computeStartOfNextMonth(long now) { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); + cal.add(Calendar.DAY_OF_MONTH, 1); + cal.set(Calendar.MILLISECOND, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.HOUR_OF_DAY, 0); + return cal.getTime().getTime(); + } - cal.set(Calendar.DATE, 1); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - cal.add(Calendar.MONTH, 1); - return cal.getTime().getTime(); - } - - + public static long computeStartOfNextWeek(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + + cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + cal.add(Calendar.WEEK_OF_YEAR, 1); + return cal.getTime().getTime(); + } + + public static long computeStartOfNextMonth(long now) { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + + cal.set(Calendar.DATE, 1); + cal.set(Calendar.HOUR_OF_DAY, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + cal.add(Calendar.MONTH, 1); + return cal.getTime().getTime(); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/AllCoreTest.java b/logback-core/src/test/java/ch/qos/logback/core/AllCoreTest.java index 2f8115f078362b4ea9e8c897f34f6dfd5291dfce..d5bfbdcc5c7d777b66551903b19a839b75fdc44a 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/AllCoreTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/AllCoreTest.java @@ -18,20 +18,10 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({BasicStatusManagerTest.class, - ch.qos.logback.core.status.PackageTest.class, - ch.qos.logback.core.util.PackageTest.class, - ch.qos.logback.core.helpers.PackageTest.class, - ch.qos.logback.core.subst.PackageTest.class, - ch.qos.logback.core.pattern.PackageTest.class, - ch.qos.logback.core.PackageTest.class, - ch.qos.logback.core.joran.PackageTest.class, - ch.qos.logback.core.appender.PackageTest.class, - ch.qos.logback.core.spi.PackageTest.class, - ch.qos.logback.core.rolling.PackageTest.class, - ch.qos.logback.core.net.PackageTest.class, - ch.qos.logback.core.sift.PackageTest.class, - ch.qos.logback.core.encoder.PackageTest.class, - ch.qos.logback.core.recovery.PackageTest.class}) +@SuiteClasses({ BasicStatusManagerTest.class, ch.qos.logback.core.status.PackageTest.class, ch.qos.logback.core.util.PackageTest.class, + ch.qos.logback.core.helpers.PackageTest.class, ch.qos.logback.core.subst.PackageTest.class, ch.qos.logback.core.pattern.PackageTest.class, + ch.qos.logback.core.PackageTest.class, ch.qos.logback.core.joran.PackageTest.class, ch.qos.logback.core.appender.PackageTest.class, + ch.qos.logback.core.spi.PackageTest.class, ch.qos.logback.core.rolling.PackageTest.class, ch.qos.logback.core.net.PackageTest.class, + ch.qos.logback.core.sift.PackageTest.class, ch.qos.logback.core.encoder.PackageTest.class, ch.qos.logback.core.recovery.PackageTest.class }) public class AllCoreTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/BasicStatusManagerTest.java b/logback-core/src/test/java/ch/qos/logback/core/BasicStatusManagerTest.java index 92d52eb429c34c0a0e1e0dbfa75eb47157470d55..9d49f48657e268cf63a219660cc1d0544cbccc48 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/BasicStatusManagerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/BasicStatusManagerTest.java @@ -28,64 +28,61 @@ import org.junit.Test; import ch.qos.logback.core.status.ErrorStatus; import ch.qos.logback.core.status.Status; - public class BasicStatusManagerTest { + BasicStatusManager bsm = new BasicStatusManager(); - BasicStatusManager bsm = new BasicStatusManager(); - - @Test - public void smoke() { - bsm.add(new ErrorStatus("hello", this)); - assertEquals(Status.ERROR, bsm.getLevel()); - - List statusList = bsm.getCopyOfStatusList(); - assertNotNull(statusList); - assertEquals(1, statusList.size()); - assertEquals("hello", statusList.get(0).getMessage()); - } + @Test + public void smoke() { + bsm.add(new ErrorStatus("hello", this)); + assertEquals(Status.ERROR, bsm.getLevel()); - @Test - public void many() { - int margin = 300; - int len = MAX_HEADER_COUNT + TAIL_SIZE + margin; - for (int i = 0; i < len; i++) { - bsm.add(new ErrorStatus("" + i, this)); + List statusList = bsm.getCopyOfStatusList(); + assertNotNull(statusList); + assertEquals(1, statusList.size()); + assertEquals("hello", statusList.get(0).getMessage()); } - List statusList = bsm.getCopyOfStatusList(); - assertNotNull(statusList); - assertEquals(MAX_HEADER_COUNT + TAIL_SIZE, statusList.size()); - List witness = new ArrayList(); - for (int i = 0; i < MAX_HEADER_COUNT; i++) { - witness.add(new ErrorStatus("" + i, this)); + @Test + public void many() { + int margin = 300; + int len = MAX_HEADER_COUNT + TAIL_SIZE + margin; + for (int i = 0; i < len; i++) { + bsm.add(new ErrorStatus("" + i, this)); + } + + List statusList = bsm.getCopyOfStatusList(); + assertNotNull(statusList); + assertEquals(MAX_HEADER_COUNT + TAIL_SIZE, statusList.size()); + List witness = new ArrayList(); + for (int i = 0; i < MAX_HEADER_COUNT; i++) { + witness.add(new ErrorStatus("" + i, this)); + } + for (int i = 0; i < TAIL_SIZE; i++) { + witness.add(new ErrorStatus("" + (MAX_HEADER_COUNT + margin + i), this)); + } + assertEquals(witness, statusList); } - for (int i = 0; i < TAIL_SIZE; i++) { - witness.add(new ErrorStatus("" + (MAX_HEADER_COUNT + margin + i), this)); - } - assertEquals(witness, statusList); - } - - @Test - public void duplicateInstallationsOfOnConsoleListener() { - OnConsoleStatusListener sl0 = new OnConsoleStatusListener(); - sl0.start(); - OnConsoleStatusListener sl1 = new OnConsoleStatusListener(); - sl1.start(); - assertTrue(bsm.add(sl0)); - - { - List listeners = bsm.getCopyOfStatusListenerList(); - assertEquals(1, listeners.size()); - } - - assertFalse(bsm.add(sl1)); - { - List listeners = bsm.getCopyOfStatusListenerList(); - assertEquals(1, listeners.size()); + @Test + public void duplicateInstallationsOfOnConsoleListener() { + OnConsoleStatusListener sl0 = new OnConsoleStatusListener(); + sl0.start(); + OnConsoleStatusListener sl1 = new OnConsoleStatusListener(); + sl1.start(); + + assertTrue(bsm.add(sl0)); + + { + List listeners = bsm.getCopyOfStatusListenerList(); + assertEquals(1, listeners.size()); + } + + assertFalse(bsm.add(sl1)); + { + List listeners = bsm.getCopyOfStatusListenerList(); + assertEquals(1, listeners.size()); + } } - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/ContextBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/ContextBaseTest.java index f8dd05fb3d1347a8480dde40341487dd6d5bbcc6..03ccb88a5d7442d8ad5185d4cdabd4004f8307a4 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/ContextBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/ContextBaseTest.java @@ -28,123 +28,120 @@ import java.util.concurrent.ExecutorService; public class ContextBaseTest { - private InstrumentedLifeCycleManager lifeCycleManager = - new InstrumentedLifeCycleManager(); - - private InstrumentedContextBase context = - new InstrumentedContextBase(lifeCycleManager); - - @Test - public void renameDefault() { - context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); - context.setName("hello"); - } - - - @Test - public void idempotentNameTest() { - context.setName("hello"); - context.setName("hello"); - } - - @Test - public void renameTest() { - context.setName("hello"); - try { - context.setName("x"); - fail("renaming is not allowed"); - } catch (IllegalStateException ise) { + private InstrumentedLifeCycleManager lifeCycleManager = new InstrumentedLifeCycleManager(); + + private InstrumentedContextBase context = new InstrumentedContextBase(lifeCycleManager); + + @Test + public void renameDefault() { + context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); + context.setName("hello"); } - } - - @Test - public void resetTest() { - context.setName("hello"); - context.putProperty("keyA", "valA"); - context.putObject("keyA", "valA"); - assertEquals("valA", context.getProperty("keyA")); - assertEquals("valA", context.getObject("keyA")); - MockLifeCycleComponent component = new MockLifeCycleComponent(); - context.register(component); - assertSame(component, lifeCycleManager.getLastComponent()); - context.reset(); - assertNull(context.getProperty("keyA")); - assertNull(context.getObject("keyA")); - assertTrue(lifeCycleManager.isReset()); - } - - @Test - public void contextNameProperty() { - assertNull(context.getProperty(CoreConstants.CONTEXT_NAME_KEY)); - String HELLO = "hello"; - context.setName(HELLO); - assertEquals(HELLO, context.getProperty(CoreConstants.CONTEXT_NAME_KEY)); - // good to have a raw reference to the "CONTEXT_NAME" as most clients would - // not go through CoreConstants - assertEquals(HELLO, context.getProperty("CONTEXT_NAME")); - } - - private static class InstrumentedContextBase extends ContextBase { - - private final LifeCycleManager lifeCycleManager; - - public InstrumentedContextBase(LifeCycleManager lifeCycleManager) { - this.lifeCycleManager = lifeCycleManager; + + @Test + public void idempotentNameTest() { + context.setName("hello"); + context.setName("hello"); } - - @Override - protected LifeCycleManager getLifeCycleManager() { - return lifeCycleManager; + + @Test + public void renameTest() { + context.setName("hello"); + try { + context.setName("x"); + fail("renaming is not allowed"); + } catch (IllegalStateException ise) { + } } - - } - - private static class InstrumentedLifeCycleManager extends LifeCycleManager { - - private LifeCycle lastComponent; - private boolean reset; - - @Override - public void register(LifeCycle component) { - lastComponent = component; - super.register(component); + + @Test + public void resetTest() { + context.setName("hello"); + context.putProperty("keyA", "valA"); + context.putObject("keyA", "valA"); + assertEquals("valA", context.getProperty("keyA")); + assertEquals("valA", context.getObject("keyA")); + MockLifeCycleComponent component = new MockLifeCycleComponent(); + context.register(component); + assertSame(component, lifeCycleManager.getLastComponent()); + context.reset(); + assertNull(context.getProperty("keyA")); + assertNull(context.getObject("keyA")); + assertTrue(lifeCycleManager.isReset()); } - - @Override - public void reset() { - reset = true; - super.reset(); + + @Test + public void contextNameProperty() { + assertNull(context.getProperty(CoreConstants.CONTEXT_NAME_KEY)); + String HELLO = "hello"; + context.setName(HELLO); + assertEquals(HELLO, context.getProperty(CoreConstants.CONTEXT_NAME_KEY)); + // good to have a raw reference to the "CONTEXT_NAME" as most clients would + // not go through CoreConstants + assertEquals(HELLO, context.getProperty("CONTEXT_NAME")); } - public LifeCycle getLastComponent() { - return lastComponent; + private static class InstrumentedContextBase extends ContextBase { + + private final LifeCycleManager lifeCycleManager; + + public InstrumentedContextBase(LifeCycleManager lifeCycleManager) { + this.lifeCycleManager = lifeCycleManager; + } + + @Override + protected LifeCycleManager getLifeCycleManager() { + return lifeCycleManager; + } + } - public boolean isReset() { - return reset; + private static class InstrumentedLifeCycleManager extends LifeCycleManager { + + private LifeCycle lastComponent; + private boolean reset; + + @Override + public void register(LifeCycle component) { + lastComponent = component; + super.register(component); + } + + @Override + public void reset() { + reset = true; + super.reset(); + } + + public LifeCycle getLastComponent() { + return lastComponent; + } + + public boolean isReset() { + return reset; + } + } - - } - - @Test - public void contextThreadpoolIsDaemonized() throws InterruptedException { - ExecutorService execSvc = context.getExecutorService(); - final ArrayList executingThreads = new ArrayList(); - execSvc.execute(new Runnable() { - @Override - public void run() { + + @Test + public void contextThreadpoolIsDaemonized() throws InterruptedException { + ExecutorService execSvc = context.getExecutorService(); + final ArrayList executingThreads = new ArrayList(); + execSvc.execute(new Runnable() { + @Override + public void run() { + synchronized (executingThreads) { + executingThreads.add(Thread.currentThread()); + executingThreads.notifyAll(); + } + } + }); synchronized (executingThreads) { - executingThreads.add(Thread.currentThread()); - executingThreads.notifyAll(); + while (executingThreads.isEmpty()) { + executingThreads.wait(); + } } - } - }); - synchronized (executingThreads) { - while (executingThreads.isEmpty()) { - executingThreads.wait(); - } + assertTrue("executing thread should be a daemon thread.", executingThreads.get(0).isDaemon()); } - assertTrue("executing thread should be a daemon thread.", executingThreads.get(0).isDaemon()); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/FileAppenderResilience_AS_ROOT_Test.java b/logback-core/src/test/java/ch/qos/logback/core/FileAppenderResilience_AS_ROOT_Test.java index d3e55c5100de47007f46a5292dffef782c962113..afbd93a61530261f2fb6469e9380b043af132b79 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/FileAppenderResilience_AS_ROOT_Test.java +++ b/logback-core/src/test/java/ch/qos/logback/core/FileAppenderResilience_AS_ROOT_Test.java @@ -29,109 +29,107 @@ import ch.qos.logback.core.util.StatusPrinter; public class FileAppenderResilience_AS_ROOT_Test { - static String MOUNT_POINT = "/mnt/loop/"; + static String MOUNT_POINT = "/mnt/loop/"; - static String LONG_STR = " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; + static String LONG_STR = " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; - static String PATH_LOOPFS_SCRIPT = "/home/ceki/java/logback/logback-core/src/test/loopfs.sh"; + static String PATH_LOOPFS_SCRIPT = "/home/ceki/java/logback/logback-core/src/test/loopfs.sh"; - enum LoopFSCommand { - setup, shake, teardown; - } - - Context context = new ContextBase(); - int diff = RandomUtil.getPositiveInt(); - String outputDirStr = MOUNT_POINT + "resilience-" + diff + "/"; - String logfileStr = outputDirStr + "output.log"; + enum LoopFSCommand { + setup, shake, teardown; + } - FileAppender fa = new FileAppender(); + Context context = new ContextBase(); + int diff = RandomUtil.getPositiveInt(); + String outputDirStr = MOUNT_POINT + "resilience-" + diff + "/"; + String logfileStr = outputDirStr + "output.log"; - static boolean isConformingHost() { - return EnvUtilForTests.isLocalHostNameInList(new String[]{"haro"}); - } + FileAppender fa = new FileAppender(); - @Before - public void setUp() throws IOException, InterruptedException { - if (!isConformingHost()) { - return; + static boolean isConformingHost() { + return EnvUtilForTests.isLocalHostNameInList(new String[] { "haro" }); } - Process p = runLoopFSScript(LoopFSCommand.setup); - p.waitFor(); - - dump("/tmp/loopfs.log"); - - fa.setContext(context); - File outputDir = new File(outputDirStr); - outputDir.mkdirs(); - System.out.println("FileAppenderResilienceTest output dir [" + outputDirStr - + "]"); - - fa.setName("FILE"); - fa.setEncoder(new EchoEncoder()); - fa.setFile(logfileStr); - fa.start(); - } - - void dump(String file) throws IOException { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); - int r; - while ((r = fis.read()) != -1) { - char c = (char) r; - System.out.print(c); - } - } finally { - if (fis != null) { - fis.close(); - } + + @Before + public void setUp() throws IOException, InterruptedException { + if (!isConformingHost()) { + return; + } + Process p = runLoopFSScript(LoopFSCommand.setup); + p.waitFor(); + + dump("/tmp/loopfs.log"); + + fa.setContext(context); + File outputDir = new File(outputDirStr); + outputDir.mkdirs(); + System.out.println("FileAppenderResilienceTest output dir [" + outputDirStr + "]"); + + fa.setName("FILE"); + fa.setEncoder(new EchoEncoder()); + fa.setFile(logfileStr); + fa.start(); } - } - @After - public void tearDown() throws IOException, InterruptedException { - if (!isConformingHost()) { - return; + void dump(String file) throws IOException { + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + int r; + while ((r = fis.read()) != -1) { + char c = (char) r; + System.out.print(c); + } + } finally { + if (fis != null) { + fis.close(); + } + } } - StatusPrinter.print(context); - fa.stop(); - Process p = runLoopFSScript(LoopFSCommand.teardown); - p.waitFor(); - System.out.println("Tearing down"); - } - - static int TOTAL_DURATION = 5000; - static int NUM_STEPS = 500; - static int DELAY = TOTAL_DURATION / NUM_STEPS; - - @Test - public void go() throws IOException, InterruptedException { - if (!isConformingHost()) { - return; + + @After + public void tearDown() throws IOException, InterruptedException { + if (!isConformingHost()) { + return; + } + StatusPrinter.print(context); + fa.stop(); + Process p = runLoopFSScript(LoopFSCommand.teardown); + p.waitFor(); + System.out.println("Tearing down"); } - Process p = runLoopFSScript(LoopFSCommand.shake); - for (int i = 0; i < NUM_STEPS; i++) { - fa.append(String.valueOf(i) + LONG_STR); - Thread.sleep(DELAY); + + static int TOTAL_DURATION = 5000; + static int NUM_STEPS = 500; + static int DELAY = TOTAL_DURATION / NUM_STEPS; + + @Test + public void go() throws IOException, InterruptedException { + if (!isConformingHost()) { + return; + } + Process p = runLoopFSScript(LoopFSCommand.shake); + for (int i = 0; i < NUM_STEPS; i++) { + fa.append(String.valueOf(i) + LONG_STR); + Thread.sleep(DELAY); + } + p.waitFor(); + // the extrernal script has the file system ready for IO 50% of the time + double bestCase = 0.5; + ResilienceUtil.verify(logfileStr, "^(\\d{1,3}) x*$", NUM_STEPS, bestCase * 0.6); + System.out.println("Done go"); } - p.waitFor(); - // the extrernal script has the file system ready for IO 50% of the time - double bestCase = 0.5; - ResilienceUtil.verify(logfileStr, "^(\\d{1,3}) x*$", NUM_STEPS, bestCase*0.6); - System.out.println("Done go"); - } - - // the loopfs script is tightly coupled with the host machine - // it needs to be Unix, with sudo privileges granted to the script - Process runLoopFSScript(LoopFSCommand cmd) throws IOException, - InterruptedException { - // causing a NullPointerException is better than locking the whole - // machine which the next operation can and will do. - if (!isConformingHost()) { - return null; + + // the loopfs script is tightly coupled with the host machine + // it needs to be Unix, with sudo privileges granted to the script + Process runLoopFSScript(LoopFSCommand cmd) throws IOException, InterruptedException { + // causing a NullPointerException is better than locking the whole + // machine which the next operation can and will do. + if (!isConformingHost()) { + return null; + } + ProcessBuilder pb = new ProcessBuilder(); + pb.command("/usr/bin/sudo", PATH_LOOPFS_SCRIPT, cmd.toString()); + return pb.start(); } - ProcessBuilder pb = new ProcessBuilder(); - pb.command("/usr/bin/sudo", PATH_LOOPFS_SCRIPT, cmd.toString()); - return pb.start(); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/LifeCycleManagerTest.java b/logback-core/src/test/java/ch/qos/logback/core/LifeCycleManagerTest.java index 98b64a2d97d2b1e9b851fdf692a3c30868896f0a..0fe44b773395fdcc2d7cb5f506e4bb5073a5a8a9 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/LifeCycleManagerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/LifeCycleManagerTest.java @@ -17,7 +17,6 @@ import static org.junit.Assert.assertFalse; import org.junit.Test; - /** * Unit tests for {@link LifeCycleManager}. * @@ -25,15 +24,15 @@ import org.junit.Test; */ public class LifeCycleManagerTest { - private LifeCycleManager manager = new LifeCycleManager(); - - @Test - public void testRegisterAndReset() { - MockLifeCycleComponent component = new MockLifeCycleComponent(); - manager.register(component); - component.start(); - manager.reset(); - assertFalse(component.isStarted()); - } + private LifeCycleManager manager = new LifeCycleManager(); + + @Test + public void testRegisterAndReset() { + MockLifeCycleComponent component = new MockLifeCycleComponent(); + manager.register(component); + component.start(); + manager.reset(); + assertFalse(component.isStarted()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/MockLifeCycleComponent.java b/logback-core/src/test/java/ch/qos/logback/core/MockLifeCycleComponent.java index 00352462f96910df346e512de113579ec1be2189..b3549af616bd392b7f9219b641fdacd0ed38b1d7 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/MockLifeCycleComponent.java +++ b/logback-core/src/test/java/ch/qos/logback/core/MockLifeCycleComponent.java @@ -17,18 +17,18 @@ import ch.qos.logback.core.spi.LifeCycle; public class MockLifeCycleComponent implements LifeCycle { - private boolean started; - - public void start() { - started = true; - } + private boolean started; - public void stop() { - started = false; - } + public void start() { + started = true; + } + + public void stop() { + started = false; + } + + public boolean isStarted() { + return started; + } - public boolean isStarted() { - return started; - } - } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/OutputStreamAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/OutputStreamAppenderTest.java index a4fa7f49aa890d28bab6fb8bf3fb43f92f080eb0..a0bf43eabb1077682ee97fcf8bc00b20731d8e0b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/OutputStreamAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/OutputStreamAppenderTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core; - import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; @@ -27,96 +26,96 @@ import ch.qos.logback.core.pattern.parser.SamplePatternLayout; public class OutputStreamAppenderTest { - Context context = new ContextBase(); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void smoke() { - String FILE_HEADER = "FILE_HEADER "; - String PRESENTATION_HEADER = "PRESENTATION_HEADER"; - String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; - String FILE_FOOTER = "FILE_FOOTER"; - headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); - } - - @Test - public void nullFileHeader() { - String FILE_HEADER = null; - String PRESENTATION_HEADER = "PRESENTATION_HEADER"; - String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; - String FILE_FOOTER = "FILE_FOOTER"; - headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); - } - - @Test - public void nullPresentationHeader() { - String FILE_HEADER = "FILE_HEADER "; - String PRESENTATION_HEADER = null; - String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; - String FILE_FOOTER = "FILE_FOOTER"; - headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); - } - - @Test - public void nullPresentationFooter() { - String FILE_HEADER = "FILE_HEADER "; - String PRESENTATION_HEADER = "PRESENTATION_HEADER"; - String PRESENTATION_FOOTER = null; - String FILE_FOOTER = "FILE_FOOTER"; - headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); - } - - @Test - public void nullFileFooter() { - String FILE_HEADER = "FILE_HEADER "; - String PRESENTATION_HEADER = "PRESENTATION_HEADER"; - String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; - String FILE_FOOTER = null; - headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); - } - - public void headerFooterCheck(String fileHeader, String presentationHeader, String presentationFooter, String fileFooter) { - OutputStreamAppender wa = new OutputStreamAppender(); - wa.setContext(context); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - SamplePatternLayout spl = new SamplePatternLayout(); - spl.setContext(context); - - spl.setFileHeader(fileHeader); - spl.setPresentationHeader(presentationHeader); - spl.setPresentationFooter(presentationFooter); - spl.setFileFooter(fileFooter); - - spl.start(); - LayoutWrappingEncoder encoder = new LayoutWrappingEncoder(); - encoder.setLayout(spl); - encoder.setContext(context); - - wa.setEncoder(encoder); - wa.setOutputStream(baos); - wa.start(); - - wa.stop(); - String result = baos.toString(); - - String expectedHeader = emtptyIfNull(fileHeader) + emtptyIfNull(presentationHeader); - - System.out.println(result); - assertTrue(result, result.startsWith(expectedHeader)); - - String expectedFooter = emtptyIfNull(presentationFooter) + emtptyIfNull(fileFooter); - assertTrue(result, result.endsWith(expectedFooter)); - } - - String emtptyIfNull(String s) { - return s == null ? "" : s; - } + Context context = new ContextBase(); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void smoke() { + String FILE_HEADER = "FILE_HEADER "; + String PRESENTATION_HEADER = "PRESENTATION_HEADER"; + String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; + String FILE_FOOTER = "FILE_FOOTER"; + headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); + } + + @Test + public void nullFileHeader() { + String FILE_HEADER = null; + String PRESENTATION_HEADER = "PRESENTATION_HEADER"; + String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; + String FILE_FOOTER = "FILE_FOOTER"; + headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); + } + + @Test + public void nullPresentationHeader() { + String FILE_HEADER = "FILE_HEADER "; + String PRESENTATION_HEADER = null; + String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; + String FILE_FOOTER = "FILE_FOOTER"; + headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); + } + + @Test + public void nullPresentationFooter() { + String FILE_HEADER = "FILE_HEADER "; + String PRESENTATION_HEADER = "PRESENTATION_HEADER"; + String PRESENTATION_FOOTER = null; + String FILE_FOOTER = "FILE_FOOTER"; + headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); + } + + @Test + public void nullFileFooter() { + String FILE_HEADER = "FILE_HEADER "; + String PRESENTATION_HEADER = "PRESENTATION_HEADER"; + String PRESENTATION_FOOTER = "PRESENTATION_FOOTER "; + String FILE_FOOTER = null; + headerFooterCheck(FILE_HEADER, PRESENTATION_HEADER, PRESENTATION_FOOTER, FILE_FOOTER); + } + + public void headerFooterCheck(String fileHeader, String presentationHeader, String presentationFooter, String fileFooter) { + OutputStreamAppender wa = new OutputStreamAppender(); + wa.setContext(context); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + SamplePatternLayout spl = new SamplePatternLayout(); + spl.setContext(context); + + spl.setFileHeader(fileHeader); + spl.setPresentationHeader(presentationHeader); + spl.setPresentationFooter(presentationFooter); + spl.setFileFooter(fileFooter); + + spl.start(); + LayoutWrappingEncoder encoder = new LayoutWrappingEncoder(); + encoder.setLayout(spl); + encoder.setContext(context); + + wa.setEncoder(encoder); + wa.setOutputStream(baos); + wa.start(); + + wa.stop(); + String result = baos.toString(); + + String expectedHeader = emtptyIfNull(fileHeader) + emtptyIfNull(presentationHeader); + + System.out.println(result); + assertTrue(result, result.startsWith(expectedHeader)); + + String expectedFooter = emtptyIfNull(presentationFooter) + emtptyIfNull(fileFooter); + assertTrue(result, result.endsWith(expectedFooter)); + } + + String emtptyIfNull(String s) { + return s == null ? "" : s; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/PackageTest.java index 98dfd5358cced3a36bc82f1061c05357b8056d41..d5ffd24975f4b74c8ac39bfdd6fa1d300be42023 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/PackageTest.java @@ -18,10 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ContextBaseTest.class, - OutputStreamAppenderTest.class, - FileAppenderResilienceTest.class, - FileAppenderResilience_AS_ROOT_Test.class, - AsyncAppenderBaseTest.class}) +@SuiteClasses({ ContextBaseTest.class, OutputStreamAppenderTest.class, FileAppenderResilienceTest.class, FileAppenderResilience_AS_ROOT_Test.class, + AsyncAppenderBaseTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/PrudentFileAppenderInterruptTest.java b/logback-core/src/test/java/ch/qos/logback/core/PrudentFileAppenderInterruptTest.java index b840156089e74da654cedee0ba37da917177abd9..e2e5e4ad3164b989fa283a9ca9b0e2c9e6a53117 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/PrudentFileAppenderInterruptTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/PrudentFileAppenderInterruptTest.java @@ -30,63 +30,64 @@ import ch.qos.logback.core.util.CoreTestConstants; public class PrudentFileAppenderInterruptTest { - FileAppender fa = new FileAppender(); - Context context = new ContextBase(); - int diff = RandomUtil.getPositiveInt(); - String outputDirStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "resilience-" + diff + "/"; - String logfileStr = outputDirStr + "output.log"; - - @Before - public void setUp() throws InterruptedException { - context.getStatusManager().add(new OnConsoleStatusListener()); - - File outputDir = new File(outputDirStr); - outputDir.mkdirs(); - - fa.setContext(context); - fa.setName("FILE"); - fa.setPrudent(true); - fa.setEncoder(new EchoEncoder()); - fa.setFile(logfileStr); - fa.start(); - } - - @Test - public void smoke() throws InterruptedException, IOException { - Runner runner = new Runner(fa); - Thread t = new Thread(runner); - t.start(); - - runner.latch.await(); - - fa.doAppend("hello not interrupted"); - - FileReader fr = new FileReader(logfileStr); - BufferedReader br = new BufferedReader(fr); - - int totalLines = 0; - while (br.readLine() != null) { - totalLines++; // In this test, the content of the file does not matter + FileAppender fa = new FileAppender(); + Context context = new ContextBase(); + int diff = RandomUtil.getPositiveInt(); + String outputDirStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "resilience-" + diff + "/"; + String logfileStr = outputDirStr + "output.log"; + + @Before + public void setUp() throws InterruptedException { + context.getStatusManager().add(new OnConsoleStatusListener()); + + File outputDir = new File(outputDirStr); + outputDir.mkdirs(); + + fa.setContext(context); + fa.setName("FILE"); + fa.setPrudent(true); + fa.setEncoder(new EchoEncoder()); + fa.setFile(logfileStr); + fa.start(); } - fr.close(); - br.close(); - assertEquals("Incorrect number of logged lines", 2, totalLines); - } + @Test + public void smoke() throws InterruptedException, IOException { + Runner runner = new Runner(fa); + Thread t = new Thread(runner); + t.start(); - class Runner extends RunnableWithCounterAndDone { - FileAppender fa; - CountDownLatch latch = new CountDownLatch(1); // Just to make sure this is executed before we log in the test method + runner.latch.await(); - Runner(FileAppender fa) { - this.fa = fa; + fa.doAppend("hello not interrupted"); + + FileReader fr = new FileReader(logfileStr); + BufferedReader br = new BufferedReader(fr); + + int totalLines = 0; + while (br.readLine() != null) { + totalLines++; // In this test, the content of the file does not matter + } + fr.close(); + br.close(); + + assertEquals("Incorrect number of logged lines", 2, totalLines); } - public void run() { - Thread.currentThread().interrupt(); - fa.doAppend("hello interrupted"); - latch.countDown(); + class Runner extends RunnableWithCounterAndDone { + FileAppender fa; + CountDownLatch latch = new CountDownLatch(1); // Just to make sure this is executed before we log in the test + // method + + Runner(FileAppender fa) { + this.fa = fa; + } + + public void run() { + Thread.currentThread().interrupt(); + fa.doAppend("hello interrupted"); + latch.countDown(); + } } - } } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/AbstractAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/AbstractAppenderTest.java index 282cb5d4eb29ab3c104e2314ee5f0c981b41a21b..f5bfe105037cb8a057b96c2119d83ef08309844c 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/AbstractAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/AbstractAppenderTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.appender; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -25,44 +24,41 @@ import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.status.StatusChecker; import ch.qos.logback.core.util.StatusPrinter; +abstract public class AbstractAppenderTest { + abstract protected Appender getAppender(); -abstract public class AbstractAppenderTest { - - - abstract protected Appender getAppender(); - abstract protected Appender getConfiguredAppender(); - Context context = new ContextBase(); - - @Test - public void testNewAppender() { - // new appenders should be inactive - Appender appender = getAppender(); - assertFalse( appender.isStarted()); - } - - @Test - public void testConfiguredAppender() { - Appender appender = getConfiguredAppender(); - appender.start(); - assertTrue(appender.isStarted()); - - appender.stop(); - assertFalse(appender.isStarted()); - - } - - @Test - public void testNoStart() { - Appender appender = getAppender(); - appender.setContext(context); - appender.setName("doh"); - // is null OK? - appender.doAppend(null); - StatusChecker checker = new StatusChecker(context.getStatusManager()); - StatusPrinter.print(context); - checker.assertContainsMatch("Attempted to append to non started appender \\[doh\\]."); - } -} + abstract protected Appender getConfiguredAppender(); + + Context context = new ContextBase(); + + @Test + public void testNewAppender() { + // new appenders should be inactive + Appender appender = getAppender(); + assertFalse(appender.isStarted()); + } + @Test + public void testConfiguredAppender() { + Appender appender = getConfiguredAppender(); + appender.start(); + assertTrue(appender.isStarted()); + appender.stop(); + assertFalse(appender.isStarted()); + + } + + @Test + public void testNoStart() { + Appender appender = getAppender(); + appender.setContext(context); + appender.setName("doh"); + // is null OK? + appender.doAppend(null); + StatusChecker checker = new StatusChecker(context.getStatusManager()); + StatusPrinter.print(context); + checker.assertContainsMatch("Attempted to append to non started appender \\[doh\\]."); + } +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/ConsoleAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/ConsoleAppenderTest.java index 29daab81aeb91155f2198b483cc8e53d602c61bd..34b81f92ca2eaa07a14bcb676fd580000b08f775 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/ConsoleAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/ConsoleAppenderTest.java @@ -37,123 +37,124 @@ import static org.junit.Assert.assertFalse; */ public class ConsoleAppenderTest extends AbstractAppenderTest { - XTeeOutputStream tee; - PrintStream original; - - @Before - public void setUp() { - original = System.out; - // tee will output bytes on System out but it will also - // collect them so that the output can be compared against - // some expected output data - // tee = new TeeOutputStream(original); - - // keep the console quiet - tee = new XTeeOutputStream(null); - - // redirect System.out to tee - System.setOut(new PrintStream(tee)); - } - - @After - public void tearDown() { - System.setOut(original); - } - - @Override - public Appender getAppender() { - return new ConsoleAppender(); - } - - protected Appender getConfiguredAppender() { - ConsoleAppender ca = new ConsoleAppender(); - ca.setEncoder(new NopEncoder()); - ca.start(); - return ca; - } - - @Test - public void smoke() { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - ca.setEncoder(new DummyEncoder()); - ca.start(); - ca.doAppend(new Object()); - assertEquals(DummyLayout.DUMMY, tee.toString()); - } - - @Test - public void open() { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - DummyEncoder dummyEncoder = new DummyEncoder(); - dummyEncoder.setFileHeader("open"); - ca.setEncoder(dummyEncoder); - ca.start(); - ca.doAppend(new Object()); - ca.stop(); - assertEquals("open" + CoreConstants.LINE_SEPARATOR + DummyLayout.DUMMY, tee - .toString()); - } - - @Test - public void testClose() { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - DummyEncoder dummyEncoder = new DummyEncoder(); - dummyEncoder.setFileFooter("CLOSED"); - ca.setEncoder(dummyEncoder); - ca.start(); - ca.doAppend(new Object()); - ca.stop(); - // ConsoleAppender must keep the underlying stream open. - // The console is not ours to close. - assertFalse(tee.isClosed()); - assertEquals(DummyLayout.DUMMY + "CLOSED", tee.toString()); - } - - // See http://jira.qos.ch/browse/LBCORE-143 - @Test - public void changeInConsole() { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - EchoEncoder encoder = new EchoEncoder(); - ca.setEncoder(encoder); - ca.start(); - ca.doAppend("a"); - assertEquals("a" + CoreConstants.LINE_SEPARATOR, tee.toString()); - - XTeeOutputStream newTee = new XTeeOutputStream(null); - System.setOut(new PrintStream(newTee)); - ca.doAppend("b"); - assertEquals("b" + CoreConstants.LINE_SEPARATOR, newTee.toString()); - } - - @Test - public void testUTF16BE() throws UnsupportedEncodingException { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - DummyEncoder dummyEncoder = new DummyEncoder(); - String encodingName = "UTF-16BE"; - dummyEncoder.setEncodingName(encodingName); - ca.setEncoder(dummyEncoder); - ca.start(); - ca.doAppend(new Object()); - assertEquals(DummyLayout.DUMMY, new String(tee.toByteArray(), encodingName)); - } - - @Test - public void wrongTarget() { - ConsoleAppender ca = (ConsoleAppender) getAppender(); - EchoEncoder encoder = new EchoEncoder(); - encoder.setContext(context); - ca.setContext(context); - ca.setTarget("foo"); - ca.setEncoder(encoder); - ca.start(); - ca.doAppend("a"); - StatusChecker checker = new StatusChecker(context); - //21:28:01,246 + WARN in ch.qos.logback.core.ConsoleAppender[null] - [foo] should be one of [System.out, System.err] - //21:28:01,246 |-WARN in ch.qos.logback.core.ConsoleAppender[null] - Using previously set target, System.out by default. -// StatusPrinter.print(context); - - checker.assertContainsMatch(Status.WARN, "\\[foo\\] should be one of \\[System.out, System.err\\]"); - - } + XTeeOutputStream tee; + PrintStream original; + + @Before + public void setUp() { + original = System.out; + // tee will output bytes on System out but it will also + // collect them so that the output can be compared against + // some expected output data + // tee = new TeeOutputStream(original); + + // keep the console quiet + tee = new XTeeOutputStream(null); + + // redirect System.out to tee + System.setOut(new PrintStream(tee)); + } + + @After + public void tearDown() { + System.setOut(original); + } + + @Override + public Appender getAppender() { + return new ConsoleAppender(); + } + + protected Appender getConfiguredAppender() { + ConsoleAppender ca = new ConsoleAppender(); + ca.setEncoder(new NopEncoder()); + ca.start(); + return ca; + } + + @Test + public void smoke() { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + ca.setEncoder(new DummyEncoder()); + ca.start(); + ca.doAppend(new Object()); + assertEquals(DummyLayout.DUMMY, tee.toString()); + } + + @Test + public void open() { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + DummyEncoder dummyEncoder = new DummyEncoder(); + dummyEncoder.setFileHeader("open"); + ca.setEncoder(dummyEncoder); + ca.start(); + ca.doAppend(new Object()); + ca.stop(); + assertEquals("open" + CoreConstants.LINE_SEPARATOR + DummyLayout.DUMMY, tee.toString()); + } + + @Test + public void testClose() { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + DummyEncoder dummyEncoder = new DummyEncoder(); + dummyEncoder.setFileFooter("CLOSED"); + ca.setEncoder(dummyEncoder); + ca.start(); + ca.doAppend(new Object()); + ca.stop(); + // ConsoleAppender must keep the underlying stream open. + // The console is not ours to close. + assertFalse(tee.isClosed()); + assertEquals(DummyLayout.DUMMY + "CLOSED", tee.toString()); + } + + // See http://jira.qos.ch/browse/LBCORE-143 + @Test + public void changeInConsole() { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + EchoEncoder encoder = new EchoEncoder(); + ca.setEncoder(encoder); + ca.start(); + ca.doAppend("a"); + assertEquals("a" + CoreConstants.LINE_SEPARATOR, tee.toString()); + + XTeeOutputStream newTee = new XTeeOutputStream(null); + System.setOut(new PrintStream(newTee)); + ca.doAppend("b"); + assertEquals("b" + CoreConstants.LINE_SEPARATOR, newTee.toString()); + } + + @Test + public void testUTF16BE() throws UnsupportedEncodingException { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + DummyEncoder dummyEncoder = new DummyEncoder(); + String encodingName = "UTF-16BE"; + dummyEncoder.setEncodingName(encodingName); + ca.setEncoder(dummyEncoder); + ca.start(); + ca.doAppend(new Object()); + assertEquals(DummyLayout.DUMMY, new String(tee.toByteArray(), encodingName)); + } + + @Test + public void wrongTarget() { + ConsoleAppender ca = (ConsoleAppender) getAppender(); + EchoEncoder encoder = new EchoEncoder(); + encoder.setContext(context); + ca.setContext(context); + ca.setTarget("foo"); + ca.setEncoder(encoder); + ca.start(); + ca.doAppend("a"); + StatusChecker checker = new StatusChecker(context); + // 21:28:01,246 + WARN in ch.qos.logback.core.ConsoleAppender[null] - [foo] should be one of [System.out, + // System.err] + // 21:28:01,246 |-WARN in ch.qos.logback.core.ConsoleAppender[null] - Using previously set target, System.out by + // default. + // StatusPrinter.print(context); + + checker.assertContainsMatch(Status.WARN, "\\[foo\\] should be one of \\[System.out, System.err\\]"); + + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/DummyAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/DummyAppenderTest.java index 91f453242335c3bb50186210e4dab540216b786f..9e135a9cec6ef5fe6da8f956da13a653bf17086d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/DummyAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/DummyAppenderTest.java @@ -25,30 +25,29 @@ import ch.qos.logback.core.encoder.DummyEncoder; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.layout.DummyLayout; - public class DummyAppenderTest extends AbstractAppenderTest { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DummyWriterAppender da = new DummyWriterAppender(baos); - - protected Appender getAppender() { - return da; - } - - protected Appender getConfiguredAppender() { - da.setEncoder(new DummyEncoder()); - da.start(); - return da; - } - - @Test - public void testBasic() throws IOException { - Encoder encoder = new DummyEncoder(); - encoder.init(baos); - da.setEncoder(encoder); - da.start(); - da.doAppend(new Object()); - assertEquals(DummyLayout.DUMMY, baos.toString()); - } - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DummyWriterAppender da = new DummyWriterAppender(baos); + + protected Appender getAppender() { + return da; + } + + protected Appender getConfiguredAppender() { + da.setEncoder(new DummyEncoder()); + da.start(); + return da; + } + + @Test + public void testBasic() throws IOException { + Encoder encoder = new DummyEncoder(); + encoder.init(baos); + da.setEncoder(encoder); + da.start(); + da.doAppend(new Object()); + assertEquals(DummyLayout.DUMMY, baos.toString()); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/DummyWriterAppender.java b/logback-core/src/test/java/ch/qos/logback/core/appender/DummyWriterAppender.java index f8b7c224a14cd98d0fa162a105d577b62f19f3bb..ad6497d511fadd9d7164b122f5cb88ca1d82f79c 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/DummyWriterAppender.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/DummyWriterAppender.java @@ -17,10 +17,9 @@ import java.io.OutputStream; import ch.qos.logback.core.OutputStreamAppender; -public class DummyWriterAppender extends - OutputStreamAppender { +public class DummyWriterAppender extends OutputStreamAppender { - DummyWriterAppender(OutputStream os) { - this.setOutputStream(os); - } + DummyWriterAppender(OutputStream os) { + this.setOutputStream(os); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java index eb6ee5ac0381fbfd3a1aa5af19b3600409b78d9c..ced22ceb88c4ef76cd0af18b06d7feb00e8c0303 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/FileAppenderTest.java @@ -36,125 +36,122 @@ import ch.qos.logback.core.util.StatusPrinter; public class FileAppenderTest extends AbstractAppenderTest { - int diff = RandomUtil.getPositiveInt(); - - protected Appender getAppender() { - return new FileAppender(); - } - - protected Appender getConfiguredAppender() { - FileAppender appender = new FileAppender(); - appender.setEncoder(new NopEncoder()); - appender.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX+"temp.log"); - appender.setName("test"); - appender.setContext(context); - appender.start(); - return appender; - } - - @Test - public void smoke() { - String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fat-smoke.log"; - - FileAppender appender = new FileAppender(); - appender.setEncoder(new DummyEncoder()); - appender.setAppend(false); - appender.setFile(filename); - appender.setName("smoke"); - appender.setContext(context); - appender.start(); - appender.doAppend(new Object()); - appender.stop(); - - File file = new File(filename); - assertTrue(file.exists()); - assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); - } - - @Test - public void testCreateParentFolders() { - String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fat-testCreateParentFolders-" + diff - + "/testCreateParentFolders.txt"; - File file = new File(filename); - assertFalse(file.getParentFile().exists()); - assertFalse(file.exists()); - - FileAppender appender = new FileAppender(); - appender.setEncoder(new DummyEncoder()); - appender.setAppend(false); - appender.setFile(filename); - appender.setName("testCreateParentFolders"); - appender.setContext(context); - appender.start(); - appender.doAppend(new Object()); - appender.stop(); - assertTrue(file.getParentFile().exists()); - assertTrue(file.exists()); - - // cleanup - assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); - File parent = file.getParentFile(); - assertTrue("failed to delete " + parent.getAbsolutePath(), parent.delete()); - } - - @Test - public void testPrudentModeLogicalImplications() { - String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "fat-testPrudentModeLogicalImplications.txt"; - File file = new File(filename); - FileAppender appender = new FileAppender(); - appender.setEncoder(new DummyEncoder()); - appender.setFile(filename); - appender.setName("testPrudentModeLogicalImplications"); - appender.setContext(context); - - appender.setAppend(false); - appender.setPrudent(true); - appender.start(); - - assertTrue(appender.isAppend()); - - StatusManager sm = context.getStatusManager(); - //StatusPrinter.print(context); - StatusChecker statusChecker = new StatusChecker(context); - assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); - List statusList = sm.getCopyOfStatusList(); - assertTrue("Expecting status list size to be 2 or larger, but was " - + statusList.size(), statusList.size() >= 2); - String msg1 = statusList.get(1).getMessage(); - - assertTrue("Got message [" + msg1 + "]", msg1 - .startsWith("Setting \"Append\" property")); - - appender.doAppend(new Object()); - appender.stop(); - assertTrue(file.exists()); - assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); - } - - @Test - public void fileNameCollision() { - String fileName = CoreTestConstants.OUTPUT_DIR_PREFIX + diff+ "fileNameCollision"; - - FileAppender appender0 = new FileAppender(); - appender0.setName("FA0"); - appender0.setFile(fileName); - appender0.setContext(context); - appender0.setEncoder(new DummyEncoder()); - appender0.start(); - assertTrue(appender0.isStarted()); - - FileAppender appender1 = new FileAppender(); - appender1.setName("FA1"); - appender1.setFile(fileName); - appender1.setContext(context); - appender1.setEncoder(new DummyEncoder()); - appender1.start(); - - assertFalse(appender1.isStarted()); - - StatusPrinter.print(context); - StatusChecker checker = new StatusChecker(context); - checker.assertContainsMatch(Status.ERROR, "'File' option has the same value"); - - } + int diff = RandomUtil.getPositiveInt(); + + protected Appender getAppender() { + return new FileAppender(); + } + + protected Appender getConfiguredAppender() { + FileAppender appender = new FileAppender(); + appender.setEncoder(new NopEncoder()); + appender.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX + "temp.log"); + appender.setName("test"); + appender.setContext(context); + appender.start(); + return appender; + } + + @Test + public void smoke() { + String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fat-smoke.log"; + + FileAppender appender = new FileAppender(); + appender.setEncoder(new DummyEncoder()); + appender.setAppend(false); + appender.setFile(filename); + appender.setName("smoke"); + appender.setContext(context); + appender.start(); + appender.doAppend(new Object()); + appender.stop(); + + File file = new File(filename); + assertTrue(file.exists()); + assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); + } + + @Test + public void testCreateParentFolders() { + String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fat-testCreateParentFolders-" + diff + "/testCreateParentFolders.txt"; + File file = new File(filename); + assertFalse(file.getParentFile().exists()); + assertFalse(file.exists()); + + FileAppender appender = new FileAppender(); + appender.setEncoder(new DummyEncoder()); + appender.setAppend(false); + appender.setFile(filename); + appender.setName("testCreateParentFolders"); + appender.setContext(context); + appender.start(); + appender.doAppend(new Object()); + appender.stop(); + assertTrue(file.getParentFile().exists()); + assertTrue(file.exists()); + + // cleanup + assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); + File parent = file.getParentFile(); + assertTrue("failed to delete " + parent.getAbsolutePath(), parent.delete()); + } + + @Test + public void testPrudentModeLogicalImplications() { + String filename = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "fat-testPrudentModeLogicalImplications.txt"; + File file = new File(filename); + FileAppender appender = new FileAppender(); + appender.setEncoder(new DummyEncoder()); + appender.setFile(filename); + appender.setName("testPrudentModeLogicalImplications"); + appender.setContext(context); + + appender.setAppend(false); + appender.setPrudent(true); + appender.start(); + + assertTrue(appender.isAppend()); + + StatusManager sm = context.getStatusManager(); + // StatusPrinter.print(context); + StatusChecker statusChecker = new StatusChecker(context); + assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); + List statusList = sm.getCopyOfStatusList(); + assertTrue("Expecting status list size to be 2 or larger, but was " + statusList.size(), statusList.size() >= 2); + String msg1 = statusList.get(1).getMessage(); + + assertTrue("Got message [" + msg1 + "]", msg1.startsWith("Setting \"Append\" property")); + + appender.doAppend(new Object()); + appender.stop(); + assertTrue(file.exists()); + assertTrue("failed to delete " + file.getAbsolutePath(), file.delete()); + } + + @Test + public void fileNameCollision() { + String fileName = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "fileNameCollision"; + + FileAppender appender0 = new FileAppender(); + appender0.setName("FA0"); + appender0.setFile(fileName); + appender0.setContext(context); + appender0.setEncoder(new DummyEncoder()); + appender0.start(); + assertTrue(appender0.isStarted()); + + FileAppender appender1 = new FileAppender(); + appender1.setName("FA1"); + appender1.setFile(fileName); + appender1.setContext(context); + appender1.setEncoder(new DummyEncoder()); + appender1.start(); + + assertFalse(appender1.isStarted()); + + StatusPrinter.print(context); + StatusChecker checker = new StatusChecker(context); + checker.assertContainsMatch(Status.ERROR, "'File' option has the same value"); + + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/appender/PackageTest.java index 4a1ca1f128428408b8f908acecf591f976174423..7c2883b9ae261948e17a403a03662ed774344f2d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/PackageTest.java @@ -16,11 +16,7 @@ package ch.qos.logback.core.appender; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({DummyAppenderTest.class, - ConsoleAppenderTest.class, - FileAppenderTest.class}) - +@Suite.SuiteClasses({ DummyAppenderTest.class, ConsoleAppenderTest.class, FileAppenderTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/appender/XTeeOutputStream.java b/logback-core/src/test/java/ch/qos/logback/core/appender/XTeeOutputStream.java index 10d2f7f2f821aae5fb9c591ec9a4611e8f40bb23..1702afdfa972042b9dd20636d98832a0083880fa 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/appender/XTeeOutputStream.java +++ b/logback-core/src/test/java/ch/qos/logback/core/appender/XTeeOutputStream.java @@ -20,19 +20,19 @@ import ch.qos.logback.core.util.TeeOutputStream; public class XTeeOutputStream extends TeeOutputStream { - boolean closed = false; - public XTeeOutputStream(PrintStream targetPS) { - super(targetPS); - } + boolean closed = false; - @Override - public void close() throws IOException { - closed = true; - super.close(); - } - - - public boolean isClosed() { - return closed; - } + public XTeeOutputStream(PrintStream targetPS) { + super(targetPS); + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + + public boolean isClosed() { + return closed; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/boolex/MatcherTest.java b/logback-core/src/test/java/ch/qos/logback/core/boolex/MatcherTest.java index 9216895ca49a60f70e0e922838979302b2cbd320..ffb35c4bdf90e2012af7591b14eb33fef9c31ea2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/boolex/MatcherTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/boolex/MatcherTest.java @@ -19,59 +19,59 @@ import ch.qos.logback.core.ContextBase; public class MatcherTest extends TestCase { - Context context; - Matcher matcher; - - public void setUp() throws Exception { - context = new ContextBase(); - matcher = new Matcher(); - matcher.setContext(context); - matcher.setName("testMatcher"); - super.setUp(); - } - - public void tearDown() throws Exception { - matcher = null; - super.tearDown(); - } - - public void testFullRegion() throws Exception { - matcher.setRegex(".*test.*"); - matcher.start(); - assertTrue(matcher.matches("test")); - assertTrue(matcher.matches("xxxxtest")); - assertTrue(matcher.matches("testxxxx")); - assertTrue(matcher.matches("xxxxtestxxxx")); - } - - public void testPartRegion() throws Exception { - matcher.setRegex("test"); - matcher.start(); - assertTrue(matcher.matches("test")); - assertTrue(matcher.matches("xxxxtest")); - assertTrue(matcher.matches("testxxxx")); - assertTrue(matcher.matches("xxxxtestxxxx")); - } - - public void testCaseInsensitive() throws Exception { - matcher.setRegex("test"); - matcher.setCaseSensitive(false); - matcher.start(); - - assertTrue(matcher.matches("TEST")); - assertTrue(matcher.matches("tEst")); - assertTrue(matcher.matches("tESt")); - assertTrue(matcher.matches("TesT")); - } - - public void testCaseSensitive() throws Exception { - matcher.setRegex("test"); - matcher.setCaseSensitive(true); - matcher.start(); - - assertFalse(matcher.matches("TEST")); - assertFalse(matcher.matches("tEst")); - assertFalse(matcher.matches("tESt")); - assertFalse(matcher.matches("TesT")); - } + Context context; + Matcher matcher; + + public void setUp() throws Exception { + context = new ContextBase(); + matcher = new Matcher(); + matcher.setContext(context); + matcher.setName("testMatcher"); + super.setUp(); + } + + public void tearDown() throws Exception { + matcher = null; + super.tearDown(); + } + + public void testFullRegion() throws Exception { + matcher.setRegex(".*test.*"); + matcher.start(); + assertTrue(matcher.matches("test")); + assertTrue(matcher.matches("xxxxtest")); + assertTrue(matcher.matches("testxxxx")); + assertTrue(matcher.matches("xxxxtestxxxx")); + } + + public void testPartRegion() throws Exception { + matcher.setRegex("test"); + matcher.start(); + assertTrue(matcher.matches("test")); + assertTrue(matcher.matches("xxxxtest")); + assertTrue(matcher.matches("testxxxx")); + assertTrue(matcher.matches("xxxxtestxxxx")); + } + + public void testCaseInsensitive() throws Exception { + matcher.setRegex("test"); + matcher.setCaseSensitive(false); + matcher.start(); + + assertTrue(matcher.matches("TEST")); + assertTrue(matcher.matches("tEst")); + assertTrue(matcher.matches("tESt")); + assertTrue(matcher.matches("TesT")); + } + + public void testCaseSensitive() throws Exception { + matcher.setRegex("test"); + matcher.setCaseSensitive(true); + matcher.start(); + + assertFalse(matcher.matches("TEST")); + assertFalse(matcher.matches("tEst")); + assertFalse(matcher.matches("tESt")); + assertFalse(matcher.matches("TesT")); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/contention/AbstractMultiThreadedHarness.java b/logback-core/src/test/java/ch/qos/logback/core/contention/AbstractMultiThreadedHarness.java index babbc4b04f83f211e470db5e90dc5312503b17f6..b49a26a5054193c61cba23a6aa80a1b95aca906f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/contention/AbstractMultiThreadedHarness.java +++ b/logback-core/src/test/java/ch/qos/logback/core/contention/AbstractMultiThreadedHarness.java @@ -15,28 +15,27 @@ package ch.qos.logback.core.contention; abstract public class AbstractMultiThreadedHarness { - RunnableWithCounterAndDone[] runnableArray; + RunnableWithCounterAndDone[] runnableArray; - abstract void waitUntilEndCondition() throws InterruptedException; + abstract void waitUntilEndCondition() throws InterruptedException; - public void execute(RunnableWithCounterAndDone[] runnableArray) - throws InterruptedException { - this.runnableArray = runnableArray; - Thread[] threadArray = new Thread[runnableArray.length]; + public void execute(RunnableWithCounterAndDone[] runnableArray) throws InterruptedException { + this.runnableArray = runnableArray; + Thread[] threadArray = new Thread[runnableArray.length]; - for (int i = 0; i < runnableArray.length; i++) { - threadArray[i] = new Thread(runnableArray[i], "Harness["+i+"]"); - } - for (Thread t : threadArray) { - t.start(); - } + for (int i = 0; i < runnableArray.length; i++) { + threadArray[i] = new Thread(runnableArray[i], "Harness[" + i + "]"); + } + for (Thread t : threadArray) { + t.start(); + } - waitUntilEndCondition(); - for (RunnableWithCounterAndDone r : runnableArray) { - r.setDone(true); - } - for (Thread t : threadArray) { - t.join(); + waitUntilEndCondition(); + for (RunnableWithCounterAndDone r : runnableArray) { + r.setDone(true); + } + for (Thread t : threadArray) { + t.join(); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/contention/MultiThreadedHarness.java b/logback-core/src/test/java/ch/qos/logback/core/contention/MultiThreadedHarness.java index e55afad7129c9cd26b7d6a50e7bbd0035af9b231..a68496f331ead6210dc7e1829fde798c45081b01 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/contention/MultiThreadedHarness.java +++ b/logback-core/src/test/java/ch/qos/logback/core/contention/MultiThreadedHarness.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.contention; - /** * Useful scaffolding/harness to start and processPriorToRemoval multiple threads. * @@ -23,27 +22,22 @@ package ch.qos.logback.core.contention; */ public class MultiThreadedHarness extends AbstractMultiThreadedHarness { - final long overallDurationInMillis; + final long overallDurationInMillis; - public MultiThreadedHarness(long overallDurationInMillis) { - this.overallDurationInMillis = overallDurationInMillis; - } + public MultiThreadedHarness(long overallDurationInMillis) { + this.overallDurationInMillis = overallDurationInMillis; + } - public void printEnvironmentInfo(String msg) { - System.out.println("=== " + msg + " ==="); - System.out.println("java.runtime.version = " - + System.getProperty("java.runtime.version")); - System.out.println("java.vendor = " - + System.getProperty("java.vendor")); - System.out.println("java.version = " - + System.getProperty("java.version")); - System.out.println("os.name = " - + System.getProperty("os.name")); - System.out.println("os.version = " - + System.getProperty("os.version")); - } + public void printEnvironmentInfo(String msg) { + System.out.println("=== " + msg + " ==="); + System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version")); + System.out.println("java.vendor = " + System.getProperty("java.vendor")); + System.out.println("java.version = " + System.getProperty("java.version")); + System.out.println("os.name = " + System.getProperty("os.name")); + System.out.println("os.version = " + System.getProperty("os.version")); + } - void waitUntilEndCondition() throws InterruptedException { - Thread.sleep(overallDurationInMillis); - } + void waitUntilEndCondition() throws InterruptedException { + Thread.sleep(overallDurationInMillis); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/contention/RunnableWithCounterAndDone.java b/logback-core/src/test/java/ch/qos/logback/core/contention/RunnableWithCounterAndDone.java index 25561946f7bd609cb6184ab2bc34fa58fefbca70..10bab5aba01f8591e2a6ebb59755ae8020f0cf74 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/contention/RunnableWithCounterAndDone.java +++ b/logback-core/src/test/java/ch/qos/logback/core/contention/RunnableWithCounterAndDone.java @@ -21,19 +21,19 @@ package ch.qos.logback.core.contention; */ abstract public class RunnableWithCounterAndDone implements Runnable { - protected boolean done = false; - protected long counter = 0; - - public long getCounter() { - return counter; - } + protected boolean done = false; + protected long counter = 0; - public void setDone(boolean done) { - this.done = done; - } + public long getCounter() { + return counter; + } + + public void setDone(boolean done) { + this.done = done; + } + + public boolean isDone() { + return done; + } - public boolean isDone() { - return done; - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/contention/ThreadedThroughputCalculator.java b/logback-core/src/test/java/ch/qos/logback/core/contention/ThreadedThroughputCalculator.java index 65e64fef55ca0d58f2d16e1e206f26772576c10f..126ab283d1c7dc068e7e32b5a4a395f267594c49 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/contention/ThreadedThroughputCalculator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/contention/ThreadedThroughputCalculator.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.contention; - /** * Useful scaffolding to measure the throughput of certain operations when * invoked by multiple threads. @@ -24,25 +23,23 @@ package ch.qos.logback.core.contention; */ public class ThreadedThroughputCalculator extends MultiThreadedHarness { + public ThreadedThroughputCalculator(long overallDurationInMillis) { + super(overallDurationInMillis); + } + + public void printThroughput(String msg) throws InterruptedException { + printThroughput(msg, false); + } - public ThreadedThroughputCalculator(long overallDurationInMillis) { - super(overallDurationInMillis); - } + public void printThroughput(String msg, boolean detailed) throws InterruptedException { + long sum = 0; + for (RunnableWithCounterAndDone r : runnableArray) { + if (detailed) { + System.out.println(r + " count=" + r.getCounter()); + } + sum += r.getCounter(); + } - public void printThroughput(String msg) throws InterruptedException { - printThroughput(msg, false); - } - - public void printThroughput(String msg, boolean detailed) throws InterruptedException { - long sum = 0; - for (RunnableWithCounterAndDone r : runnableArray) { - if(detailed) { - System.out.println(r +" count="+r.getCounter()); - } - sum += r.getCounter(); + System.out.println(msg + "total of " + sum + " operations, or " + ((sum) / overallDurationInMillis) + " operations per millisecond"); } - - System.out.println(msg + "total of " + sum + " operations, or " - + ((sum) / overallDurationInMillis) + " operations per millisecond"); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/contention/WaitOnExecutionMultiThreadedHarness.java b/logback-core/src/test/java/ch/qos/logback/core/contention/WaitOnExecutionMultiThreadedHarness.java index 2032228587560cf0f66353c312beec65b7dc298f..5c33a276422123f48e9f765fff9da6c86c406d98 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/contention/WaitOnExecutionMultiThreadedHarness.java +++ b/logback-core/src/test/java/ch/qos/logback/core/contention/WaitOnExecutionMultiThreadedHarness.java @@ -24,10 +24,11 @@ public class WaitOnExecutionMultiThreadedHarness extends AbstractMultiThreadedHa this.count = count; } + @Override void waitUntilEndCondition() throws InterruptedException { - while(threadPoolExecutor.getCompletedTaskCount() < count) { - Thread.yield(); - } + while (threadPoolExecutor.getCompletedTaskCount() < count) { + Thread.yield(); + } } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/encoder/ByteArrayUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/encoder/ByteArrayUtilTest.java index 1b9e29f90bcbfec014b7e97f8aacca68c6a081d9..41a6ffb9889a590f9aee01772f50d77919ee440f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/encoder/ByteArrayUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/encoder/ByteArrayUtilTest.java @@ -21,33 +21,33 @@ import org.junit.Test; public class ByteArrayUtilTest { - int BA_SIZE = 16; - byte[] byteArray = new byte[BA_SIZE]; - - Random random = new Random(18532235); - - @Test - public void smoke() { - verifyLoop(byteArray, 0, 0); - verifyLoop(byteArray, 0, 10); - verifyLoop(byteArray, 0, Integer.MAX_VALUE); - verifyLoop(byteArray, 0, Integer.MIN_VALUE); - } - - @Test - public void random() { - for(int i = 0; i < 100000; i++) { - int rOffset = random.nextInt(BA_SIZE-4); - int rInt = random.nextInt(); - verifyLoop(byteArray, rOffset, rInt); + int BA_SIZE = 16; + byte[] byteArray = new byte[BA_SIZE]; + + Random random = new Random(18532235); + + @Test + public void smoke() { + verifyLoop(byteArray, 0, 0); + verifyLoop(byteArray, 0, 10); + verifyLoop(byteArray, 0, Integer.MAX_VALUE); + verifyLoop(byteArray, 0, Integer.MIN_VALUE); + } + + @Test + public void random() { + for (int i = 0; i < 100000; i++) { + int rOffset = random.nextInt(BA_SIZE - 4); + int rInt = random.nextInt(); + verifyLoop(byteArray, rOffset, rInt); + } + } + + void verifyLoop(byte[] ba, int offset, int expected) { + ByteArrayUtil.writeInt(byteArray, offset, expected); + int back = ByteArrayUtil.readInt(byteArray, offset); + assertEquals(expected, back); + } - } - - void verifyLoop(byte[] ba, int offset, int expected) { - ByteArrayUtil.writeInt(byteArray, offset, expected); - int back = ByteArrayUtil.readInt(byteArray, offset); - assertEquals(expected, back); - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/encoder/DummyEncoder.java b/logback-core/src/test/java/ch/qos/logback/core/encoder/DummyEncoder.java index 25306f829b6b31e4103a7354fb3a4f401a47d14f..9754657d4bcaae27713068bb2fe4d8525f5acabb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/encoder/DummyEncoder.java +++ b/logback-core/src/test/java/ch/qos/logback/core/encoder/DummyEncoder.java @@ -20,87 +20,87 @@ import ch.qos.logback.core.CoreConstants; public class DummyEncoder extends EncoderBase { - public static final String DUMMY = "dummy" + CoreConstants.LINE_SEPARATOR; - String val = DUMMY; - String fileHeader; - String fileFooter; - String encodingName; - - public String getEncodingName() { - return encodingName; - } - - public void setEncodingName(String encodingName) { - this.encodingName = encodingName; - } - - public DummyEncoder() { - } - - public DummyEncoder(String val) { - this.val = val; - } - - public void doEncode(E event) throws IOException { - writeOut(val); - } - - private void appendIfNotNull(StringBuilder sb, String s) { - if (s != null) { - sb.append(s); + public static final String DUMMY = "dummy" + CoreConstants.LINE_SEPARATOR; + String val = DUMMY; + String fileHeader; + String fileFooter; + String encodingName; + + public String getEncodingName() { + return encodingName; } - } - void writeOut(String s) throws IOException { - if (encodingName == null) { - outputStream.write(s.getBytes()); - } else { - outputStream.write(s.getBytes(encodingName)); + public void setEncodingName(String encodingName) { + this.encodingName = encodingName; } - } - - void writeHeader() throws IOException { - StringBuilder sb = new StringBuilder(); - appendIfNotNull(sb, fileHeader); - if (sb.length() > 0) { - sb.append(CoreConstants.LINE_SEPARATOR); - // If at least one of file header or presentation header were not - // null, then append a line separator. - // This should be useful in most cases and should not hurt. - writeOut(sb.toString()); + + public DummyEncoder() { + } + + public DummyEncoder(String val) { + this.val = val; } - } - public void init(OutputStream os) throws IOException { - super.init(os); - writeHeader(); - } + public void doEncode(E event) throws IOException { + writeOut(val); + } - public void close() throws IOException { - if (fileFooter == null) { - return; + private void appendIfNotNull(StringBuilder sb, String s) { + if (s != null) { + sb.append(s); + } } - if (encodingName == null) { - outputStream.write(fileFooter.getBytes()); - } else { - outputStream.write(fileFooter.getBytes(encodingName)); + + void writeOut(String s) throws IOException { + if (encodingName == null) { + outputStream.write(s.getBytes()); + } else { + outputStream.write(s.getBytes(encodingName)); + } } - } - public String getFileHeader() { - return fileHeader; - } + void writeHeader() throws IOException { + StringBuilder sb = new StringBuilder(); + appendIfNotNull(sb, fileHeader); + if (sb.length() > 0) { + sb.append(CoreConstants.LINE_SEPARATOR); + // If at least one of file header or presentation header were not + // null, then append a line separator. + // This should be useful in most cases and should not hurt. + writeOut(sb.toString()); + } + } - public void setFileHeader(String fileHeader) { - this.fileHeader = fileHeader; - } + public void init(OutputStream os) throws IOException { + super.init(os); + writeHeader(); + } - public String getFileFooter() { - return fileFooter; - } + public void close() throws IOException { + if (fileFooter == null) { + return; + } + if (encodingName == null) { + outputStream.write(fileFooter.getBytes()); + } else { + outputStream.write(fileFooter.getBytes(encodingName)); + } + } - public void setFileFooter(String fileFooter) { - this.fileFooter = fileFooter; - } + public String getFileHeader() { + return fileHeader; + } + + public void setFileHeader(String fileHeader) { + this.fileHeader = fileHeader; + } + + public String getFileFooter() { + return fileFooter; + } + + public void setFileFooter(String fileFooter) { + this.fileFooter = fileFooter; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/encoder/NopEncoder.java b/logback-core/src/test/java/ch/qos/logback/core/encoder/NopEncoder.java index f5c3953c74c04ec0e769f8dec8bf7a23fef59c47..dbc500867d12727a4b4a9a05410202e11f10cec7 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/encoder/NopEncoder.java +++ b/logback-core/src/test/java/ch/qos/logback/core/encoder/NopEncoder.java @@ -17,13 +17,13 @@ import java.io.IOException; import java.io.OutputStream; public class NopEncoder extends EncoderBase { - - public void close() throws IOException { - } - public void doEncode(E event) throws IOException { - } + public void close() throws IOException { + } - public void init(OutputStream os) throws IOException { - } + public void doEncode(E event) throws IOException { + } + + public void init(OutputStream os) throws IOException { + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/encoder/ObjectEncodeDecodeTest.java b/logback-core/src/test/java/ch/qos/logback/core/encoder/ObjectEncodeDecodeTest.java index 35aba59ffce5bb566a643a7abad47d8df9de7f40..3d2eedb28d28e359462b67963eb2f0bccfb6cca8 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/encoder/ObjectEncodeDecodeTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/encoder/ObjectEncodeDecodeTest.java @@ -30,65 +30,63 @@ import ch.qos.logback.core.util.CoreTestConstants; public class ObjectEncodeDecodeTest { - ObjectStreamEncoder encoder = new ObjectStreamEncoder(); - EventObjectInputStream eventStream; + ObjectStreamEncoder encoder = new ObjectStreamEncoder(); + EventObjectInputStream eventStream; - int diff = RandomUtil.getPositiveInt(); - protected String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff - + "/"; + int diff = RandomUtil.getPositiveInt(); + protected String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; - @Before - public void setUp() { - File randomOupurDirFile = new File(randomOutputDir); - randomOupurDirFile.mkdirs(); - } + @Before + public void setUp() { + File randomOupurDirFile = new File(randomOutputDir); + randomOupurDirFile.mkdirs(); + } - void encodeList(File file, List list) throws IOException { - FileOutputStream fos = new FileOutputStream(file); - encoder.init(fos); - for (String s: list) { - encoder.doEncode(s); + void encodeList(File file, List list) throws IOException { + FileOutputStream fos = new FileOutputStream(file); + encoder.init(fos); + for (String s : list) { + encoder.doEncode(s); + } + encoder.close(); + fos.close(); } - encoder.close(); - fos.close(); - } - - - List decodeList(File file) throws IOException { - FileInputStream fis = new FileInputStream(file); - eventStream = new EventObjectInputStream(fis); - List back = new ArrayList(); - String e; - while((e=eventStream.readEvent()) != null) { - back.add(e); + + List decodeList(File file) throws IOException { + FileInputStream fis = new FileInputStream(file); + eventStream = new EventObjectInputStream(fis); + List back = new ArrayList(); + String e; + while ((e = eventStream.readEvent()) != null) { + back.add(e); + } + return back; } - return back; - } - @Test - public void singleBatch() throws IOException { - File file = new File(randomOutputDir + "x.lbo"); + @Test + public void singleBatch() throws IOException { + File file = new File(randomOutputDir + "x.lbo"); - List witness = new ArrayList(); - for (int i = 0; i < 10; i++) { - witness.add("hello" + i); + List witness = new ArrayList(); + for (int i = 0; i < 10; i++) { + witness.add("hello" + i); + } + encodeList(file, witness); + List back = decodeList(file); + assertEquals(witness, back); } - encodeList(file, witness); - List back = decodeList(file); - assertEquals(witness, back); - } - @Test - public void multipleBatches() throws IOException { - File file = new File(randomOutputDir + "m.lbo"); + @Test + public void multipleBatches() throws IOException { + File file = new File(randomOutputDir + "m.lbo"); - List witness = new ArrayList(); - for (int i = 0; i < 100*10; i++) { - witness.add("hello" + i); + List witness = new ArrayList(); + for (int i = 0; i < 100 * 10; i++) { + witness.add("hello" + i); + } + encodeList(file, witness); + List back = decodeList(file); + assertEquals(witness, back); } - encodeList(file, witness); - List back = decodeList(file); - assertEquals(witness, back); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/encoder/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/encoder/PackageTest.java index 450409867703fc053953407d4ce912e9d3f65152..74e20f2736dd70067dda737e07a775a60f1e72a9 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/encoder/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/encoder/PackageTest.java @@ -17,6 +17,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses( { ByteArrayUtilTest.class, ObjectEncodeDecodeTest.class }) +@Suite.SuiteClasses({ ByteArrayUtilTest.class, ObjectEncodeDecodeTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/helpers/CyclicBufferTest.java b/logback-core/src/test/java/ch/qos/logback/core/helpers/CyclicBufferTest.java index 1dba0a9917d0779ebe001b0e7c9a7659543b566e..e15363d3a4f0ad02b2937a1fe4d7f228ec16fc32 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/helpers/CyclicBufferTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/helpers/CyclicBufferTest.java @@ -22,40 +22,39 @@ import static org.junit.Assert.assertEquals; public class CyclicBufferTest { - - void assertSize(CyclicBuffer cb, int size) { - assertEquals(size, cb.length()); - } - @Test - public void smoke() { - CyclicBuffer cb = new CyclicBuffer(2); - assertSize(cb, 0); - cb.add("zero"); - assertSize(cb, 1); - cb.add("one"); - assertSize(cb, 2); - cb.add("two"); - assertSize(cb, 2); - assertEquals("one", cb.get()); - assertSize(cb, 1); - assertEquals("two",cb.get()); - assertSize(cb, 0); - } - - - @Test - public void cloning() { - CyclicBuffer cb = new CyclicBuffer(2); - cb.add("zero"); - cb.add("one"); - - CyclicBuffer clone = new CyclicBuffer(cb); - assertSize(clone, 2); - cb.clear(); - assertSize(cb, 0); - - List witness = Arrays.asList("zero", "one"); - assertEquals(witness, clone.asList()); - - } + void assertSize(CyclicBuffer cb, int size) { + assertEquals(size, cb.length()); + } + + @Test + public void smoke() { + CyclicBuffer cb = new CyclicBuffer(2); + assertSize(cb, 0); + cb.add("zero"); + assertSize(cb, 1); + cb.add("one"); + assertSize(cb, 2); + cb.add("two"); + assertSize(cb, 2); + assertEquals("one", cb.get()); + assertSize(cb, 1); + assertEquals("two", cb.get()); + assertSize(cb, 0); + } + + @Test + public void cloning() { + CyclicBuffer cb = new CyclicBuffer(2); + cb.add("zero"); + cb.add("one"); + + CyclicBuffer clone = new CyclicBuffer(cb); + assertSize(clone, 2); + cb.clear(); + assertSize(cb, 0); + + List witness = Arrays.asList("zero", "one"); + assertEquals(witness, clone.asList()); + + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/helpers/FileFilterUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/helpers/FileFilterUtilTest.java index cfab40fdd3bb3851994a1d079060480e98bbcfcf..632a814409c4d4f82cea04d93798f36151637181 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/helpers/FileFilterUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/helpers/FileFilterUtilTest.java @@ -27,30 +27,27 @@ import static junit.framework.Assert.assertEquals; public class FileFilterUtilTest { - - Context context = new ContextBase(); - - // see also http://jira.qos.ch/browse/LBCORE-164 - @Test - public void findHighestCounterTest() throws ParseException { - String[] sa = new String[]{"c:/log/debug-old-2010-08-10.0.log", - "c:/log/debug-old-2010-08-10.1.log", "c:/log/debug-old-2010-08-10.10.log", - "c:/log/debug-old-2010-08-10.11.log", "c:/log/debug-old-2010-08-10.12.log", - "c:/log/debug-old-2010-08-10.2.log", "c:/log/debug-old-2010-08-10.3.log", - "c:/log/debug-old-2010-08-10.4.log", "c:/log/debug-old-2010-08-10.5.log", - "c:/log/debug-old-2010-08-10.6.log", "c:/log/debug-old-2010-08-10.7.log", - "c:/log/debug-old-2010-08-10.8.log", "c:/log/debug-old-2010-08-10.9.log"}; - - File[] matchingFileArray = new File[sa.length]; - for (int i = 0; i < sa.length; i++) { - matchingFileArray[i] = new File(sa[i]); + Context context = new ContextBase(); + + // see also http://jira.qos.ch/browse/LBCORE-164 + @Test + public void findHighestCounterTest() throws ParseException { + String[] sa = new String[] { "c:/log/debug-old-2010-08-10.0.log", "c:/log/debug-old-2010-08-10.1.log", "c:/log/debug-old-2010-08-10.10.log", + "c:/log/debug-old-2010-08-10.11.log", "c:/log/debug-old-2010-08-10.12.log", "c:/log/debug-old-2010-08-10.2.log", + "c:/log/debug-old-2010-08-10.3.log", "c:/log/debug-old-2010-08-10.4.log", "c:/log/debug-old-2010-08-10.5.log", + "c:/log/debug-old-2010-08-10.6.log", "c:/log/debug-old-2010-08-10.7.log", "c:/log/debug-old-2010-08-10.8.log", + "c:/log/debug-old-2010-08-10.9.log" }; + + File[] matchingFileArray = new File[sa.length]; + for (int i = 0; i < sa.length; i++) { + matchingFileArray[i] = new File(sa[i]); + } + FileNamePattern fnp = new FileNamePattern("c:/log/debug-old-%d{yyyy-MM-dd}.%i.log", context); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String rexexp = null; + rexexp = fnp.toRegexForFixedDate(sdf.parse("2010-08-10")); + String stemRegex = FileFilterUtil.afterLastSlash(rexexp); + int result = FileFilterUtil.findHighestCounter(matchingFileArray, stemRegex); + assertEquals(12, result); } - FileNamePattern fnp = new FileNamePattern("c:/log/debug-old-%d{yyyy-MM-dd}.%i.log", context); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - String rexexp = null; - rexexp = fnp.toRegexForFixedDate(sdf.parse("2010-08-10")); - String stemRegex = FileFilterUtil.afterLastSlash(rexexp); - int result = FileFilterUtil.findHighestCounter(matchingFileArray, stemRegex); - assertEquals(12, result); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/helpers/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/helpers/PackageTest.java index 617cfeb12ef7b93d5afbf39a94c1917c68a61224..411b08c478b6b0ea854a9d4915e086d7eb16d1d0 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/helpers/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/helpers/PackageTest.java @@ -19,7 +19,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ThrowableToStringArrayTest.class, FileUtilTest.class, CyclicBufferTest.class}) +@SuiteClasses({ ThrowableToStringArrayTest.class, FileUtilTest.class, CyclicBufferTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/helpers/ThrowableToStringArrayTest.java b/logback-core/src/test/java/ch/qos/logback/core/helpers/ThrowableToStringArrayTest.java index 4fe7ec16102b6e788570d0e666f8f5644f6fe384..8c38ebd4467625360948fe046bf030f8bf8868f2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/helpers/ThrowableToStringArrayTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/helpers/ThrowableToStringArrayTest.java @@ -26,68 +26,68 @@ import ch.qos.logback.core.CoreConstants; public class ThrowableToStringArrayTest { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + public void verify(Throwable t) { + t.printStackTrace(pw); - @After - public void tearDown() throws Exception { - } + String[] sa = ThrowableToStringArray.convert(t); + StringBuilder sb = new StringBuilder(); + for (String tdp : sa) { + sb.append(tdp); + sb.append(CoreConstants.LINE_SEPARATOR); + } + String expected = sw.toString(); + String result = sb.toString().replace("common frames omitted", "more"); + assertEquals(expected, result); + } + + @Test + public void smoke() { + Exception e = new Exception("smoke"); + verify(e); + } - public void verify(Throwable t) { - t.printStackTrace(pw); - - String[] sa = ThrowableToStringArray.convert(t); - StringBuilder sb = new StringBuilder(); - for (String tdp : sa) { - sb.append(tdp); - sb.append(CoreConstants.LINE_SEPARATOR); + @Test + public void nested() { + Exception w = null; + try { + someMethod(); + } catch (Exception e) { + w = new Exception("wrapping", e); + } + verify(w); } - String expected = sw.toString(); - String result = sb.toString().replace("common frames omitted", "more"); - assertEquals(expected, result); - } - - @Test - public void smoke() { - Exception e = new Exception("smoke"); - verify(e); - } - @Test - public void nested() { - Exception w = null; - try { - someMethod(); - } catch (Exception e) { - w = new Exception("wrapping", e); + @Test + public void multiNested() { + Exception w = null; + try { + someOtherMethod(); + } catch (Exception e) { + w = new Exception("wrapping", e); + } + verify(w); } - verify(w); - } - @Test - public void multiNested() { - Exception w = null; - try { - someOtherMethod(); - } catch (Exception e) { - w = new Exception("wrapping", e); + void someMethod() throws Exception { + throw new Exception("someMethod"); } - verify(w); - } - - void someMethod() throws Exception { - throw new Exception("someMethod"); - } - void someOtherMethod() throws Exception { - try { - someMethod(); - } catch (Exception e) { - throw new Exception("someOtherMethod", e); + void someOtherMethod() throws Exception { + try { + someMethod(); + } catch (Exception e) { + throw new Exception("someOtherMethod", e); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/LBCORE97.java b/logback-core/src/test/java/ch/qos/logback/core/issue/LBCORE97.java index 4c48802065b3a89152b8ce54dbd233ad4a62ab6c..328a572ece580123c3a074238f690e515f554fa0 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/LBCORE97.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/LBCORE97.java @@ -24,168 +24,155 @@ import java.util.concurrent.locks.ReentrantLock; */ public class LBCORE97 { - static int THREAD_COUNT = 10; - - public static void main(String args[]) throws InterruptedException { - - System.out.println("Environment:"); - System.out.println("java.runtime.name = " - + System.getProperty("java.runtime.name")); - System.out.println("java.runtime.version = " - + System.getProperty("java.runtime.version")); - System.out.println("java.vendor = " - + System.getProperty("java.vendor")); - System.out.println("java.version = " - + System.getProperty("java.version")); - System.out.println("java.vm.name = " - + System.getProperty("java.vm.name")); - System.out.println("java.vm.info = " - + System.getProperty("java.vm.info")); - - System.out.println("os.name = " - + System.getProperty("os.name")); - System.out.println("os.version = " - + System.getProperty("os.version")); - System.out.println("os.arch = " - + System.getProperty("os.arch")); - System.out.println("##########################################"); - - usingSynchronized(THREAD_COUNT); - usingUnfairLock(THREAD_COUNT); - usingFairLock(THREAD_COUNT); - } - - public static void execute(String text, Thread[] threads) - throws InterruptedException { - System.out.println("About to execute " + text + "..."); - int threadCount = threads.length; - for (int i = 0; i < threadCount; i++) { - threads[i].start(); + static int THREAD_COUNT = 10; + + public static void main(String args[]) throws InterruptedException { + + System.out.println("Environment:"); + System.out.println("java.runtime.name = " + System.getProperty("java.runtime.name")); + System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version")); + System.out.println("java.vendor = " + System.getProperty("java.vendor")); + System.out.println("java.version = " + System.getProperty("java.version")); + System.out.println("java.vm.name = " + System.getProperty("java.vm.name")); + System.out.println("java.vm.info = " + System.getProperty("java.vm.info")); + + System.out.println("os.name = " + System.getProperty("os.name")); + System.out.println("os.version = " + System.getProperty("os.version")); + System.out.println("os.arch = " + System.getProperty("os.arch")); + System.out.println("##########################################"); + + usingSynchronized(THREAD_COUNT); + usingUnfairLock(THREAD_COUNT); + usingFairLock(THREAD_COUNT); } - Thread.sleep(10000); + public static void execute(String text, Thread[] threads) throws InterruptedException { + System.out.println("About to execute " + text + "..."); + int threadCount = threads.length; + for (int i = 0; i < threadCount; i++) { + threads[i].start(); + } - for (int i = 0; i < threadCount; i++) { - threads[i].interrupt(); - } - Thread.sleep(1000); // wait a moment for termination, to lazy for join ;) - } + Thread.sleep(10000); - public static void print(String text, Runnable[] runnables) { - System.out.println("Results for " + text + ":"); - for (int i = 0; i < runnables.length; i++) { - System.out.println("runnables[" + i + "]: " + runnables[i]); + for (int i = 0; i < threadCount; i++) { + threads[i].interrupt(); + } + Thread.sleep(1000); // wait a moment for termination, to lazy for join ;) } - System.out.println("##########################################"); - } - - public static void usingSynchronized(int threadCount) - throws InterruptedException { - Object lockObject = new Object(); - Runnable[] runnables = new Runnable[threadCount]; - Thread[] threads = new Thread[threadCount]; - - for (int i = 0; i < threadCount; i++) { - runnables[i] = new SynchronizedRunnable(lockObject); - threads[i] = new Thread(runnables[i]); + + public static void print(String text, Runnable[] runnables) { + System.out.println("Results for " + text + ":"); + for (int i = 0; i < runnables.length; i++) { + System.out.println("runnables[" + i + "]: " + runnables[i]); + } + System.out.println("##########################################"); } - String text = "usingSynchronized"; - execute(text, threads); - print(text, runnables); - } - - public static void usingUnfairLock(int threadCount) - throws InterruptedException { - Lock lock = new ReentrantLock(); - Runnable[] runnables = new Runnable[threadCount]; - Thread[] threads = new Thread[threadCount]; - - for (int i = 0; i < threadCount; i++) { - runnables[i] = new LockRunnable(lock); - threads[i] = new Thread(runnables[i]); + + public static void usingSynchronized(int threadCount) throws InterruptedException { + Object lockObject = new Object(); + Runnable[] runnables = new Runnable[threadCount]; + Thread[] threads = new Thread[threadCount]; + + for (int i = 0; i < threadCount; i++) { + runnables[i] = new SynchronizedRunnable(lockObject); + threads[i] = new Thread(runnables[i]); + } + String text = "usingSynchronized"; + execute(text, threads); + print(text, runnables); } - String text = "usingUnfairLock"; - execute(text, threads); - print(text, runnables); - } + public static void usingUnfairLock(int threadCount) throws InterruptedException { + Lock lock = new ReentrantLock(); + Runnable[] runnables = new Runnable[threadCount]; + Thread[] threads = new Thread[threadCount]; - public static void usingFairLock(int threadCount) throws InterruptedException { - Lock lock = new ReentrantLock(true); - Runnable[] runnables = new Runnable[threadCount]; - Thread[] threads = new Thread[threadCount]; + for (int i = 0; i < threadCount; i++) { + runnables[i] = new LockRunnable(lock); + threads[i] = new Thread(runnables[i]); + } - for (int i = 0; i < threadCount; i++) { - runnables[i] = new LockRunnable(lock); - threads[i] = new Thread(runnables[i]); + String text = "usingUnfairLock"; + execute(text, threads); + print(text, runnables); } - String text = "usingFairLock"; - execute(text, threads); - print(text, runnables); - } + public static void usingFairLock(int threadCount) throws InterruptedException { + Lock lock = new ReentrantLock(true); + Runnable[] runnables = new Runnable[threadCount]; + Thread[] threads = new Thread[threadCount]; - public static class SynchronizedRunnable implements Runnable { - private final Object lockObject; - private int counter; - private boolean running; + for (int i = 0; i < threadCount; i++) { + runnables[i] = new LockRunnable(lock); + threads[i] = new Thread(runnables[i]); + } - public SynchronizedRunnable(Object lockObject) { - this.lockObject = lockObject; - this.counter = 0; - this.running = false; + String text = "usingFairLock"; + execute(text, threads); + print(text, runnables); } - public void run() { - running = true; - for (;;) { - synchronized (lockObject) { - counter++; - try { - Thread.sleep(10); - } catch (InterruptedException ex) { - break; - } + public static class SynchronizedRunnable implements Runnable { + private final Object lockObject; + private int counter; + private boolean running; + + public SynchronizedRunnable(Object lockObject) { + this.lockObject = lockObject; + this.counter = 0; + this.running = false; } - } - running = false; - } - public String toString() { - return "SynchronizedRunnable[counter=" + counter + ", running=" + running - + "]"; + public void run() { + running = true; + for (;;) { + synchronized (lockObject) { + counter++; + try { + Thread.sleep(10); + } catch (InterruptedException ex) { + break; + } + } + } + running = false; + } + + public String toString() { + return "SynchronizedRunnable[counter=" + counter + ", running=" + running + "]"; + } } - } - public static class LockRunnable implements Runnable { - private final Lock lock; - private int counter; - private boolean running; + public static class LockRunnable implements Runnable { + private final Lock lock; + private int counter; + private boolean running; - public LockRunnable(Lock lock) { - this.lock = lock; - this.counter = 0; - this.running = false; - } + public LockRunnable(Lock lock) { + this.lock = lock; + this.counter = 0; + this.running = false; + } - public void run() { - running = true; - for (;;) { - lock.lock(); - try { - counter++; - Thread.sleep(10); - } catch (InterruptedException ex) { - break; - } finally { - lock.unlock(); + public void run() { + running = true; + for (;;) { + lock.lock(); + try { + counter++; + Thread.sleep(10); + } catch (InterruptedException ex) { + break; + } finally { + lock.unlock(); + } + } + running = false; } - } - running = false; - } - public String toString() { - return "LockRunnable[counter=" + counter + ", running=" + running + "]"; + public String toString() { + return "LockRunnable[counter=" + counter + ", running=" + running + "]"; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/LOGBACK_849/Basic.java b/logback-core/src/test/java/ch/qos/logback/core/issue/LOGBACK_849/Basic.java index 9255f41c875227bb6686afe2ca7908088666d6ce..db2bb088ed11efc58850d84eeac1af185800cdb4 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/LOGBACK_849/Basic.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/LOGBACK_849/Basic.java @@ -23,53 +23,51 @@ import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.util.ExecutorServiceUtil; - public class Basic { - ExecutorService executor = ExecutorServiceUtil.newExecutorService(); - Context context = new ContextBase(); + ExecutorService executor = ExecutorServiceUtil.newExecutorService(); + Context context = new ContextBase(); - @Test(timeout = 100) - public void withNoSubmittedTasksShutdownNowShouldReturnImmediately() throws InterruptedException { - executor.shutdownNow(); - executor.awaitTermination(5000, TimeUnit.MILLISECONDS); - } + @Test(timeout = 100) + public void withNoSubmittedTasksShutdownNowShouldReturnImmediately() throws InterruptedException { + executor.shutdownNow(); + executor.awaitTermination(5000, TimeUnit.MILLISECONDS); + } - @Ignore - @Test - public void withOneSlowTask() throws InterruptedException { - executor.execute(new InterruptIgnoring(1000)); - Thread.sleep(100); - ExecutorServiceUtil.shutdown(executor); - } + @Ignore + @Test + public void withOneSlowTask() throws InterruptedException { + executor.execute(new InterruptIgnoring(1000)); + Thread.sleep(100); + ExecutorServiceUtil.shutdown(executor); + } - // InterruptIgnoring =========================================== - static class InterruptIgnoring implements Runnable { + // InterruptIgnoring =========================================== + static class InterruptIgnoring implements Runnable { - int delay; + int delay; - InterruptIgnoring(int delay) { - this.delay = delay; - } + InterruptIgnoring(int delay) { + this.delay = delay; + } - public void run() { - long runUntil = System.currentTimeMillis() + delay; + public void run() { + long runUntil = System.currentTimeMillis() + delay; - while (true) { - try { - long sleep = runUntil - System.currentTimeMillis(); - System.out.println("will sleep " + sleep); - if (sleep > 0) { - Thread.currentThread().sleep(delay); - } else { - return; - } - } catch (InterruptedException e) { - // ignore the exception + while (true) { + try { + long sleep = runUntil - System.currentTimeMillis(); + System.out.println("will sleep " + sleep); + if (sleep > 0) { + Thread.currentThread().sleep(delay); + } else { + return; + } + } catch (InterruptedException e) { + // ignore the exception + } + } } - } } - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/LockThroughput.java b/logback-core/src/test/java/ch/qos/logback/core/issue/LockThroughput.java index e67ca88faabf69ed5aa47ff2d1b2a57efc9142c0..7fc6287309085add5764625a3f70c8998be82c77 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/LockThroughput.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/LockThroughput.java @@ -24,37 +24,36 @@ import ch.qos.logback.core.issue.SelectiveLockRunnable.LockingModel; */ public class LockThroughput { - static int THREAD_COUNT = 10; - static long OVERALL_DURATION_IN_MILLIS = 5000; + static int THREAD_COUNT = 10; + static long OVERALL_DURATION_IN_MILLIS = 5000; - public static void main(String args[]) throws InterruptedException { + public static void main(String args[]) throws InterruptedException { - ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator( - OVERALL_DURATION_IN_MILLIS); - tp.printEnvironmentInfo("LockThroughput"); + ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator(OVERALL_DURATION_IN_MILLIS); + tp.printEnvironmentInfo("LockThroughput"); - for (int i = 0; i < 2; i++) { - tp.execute(buildArray(LockingModel.SYNC)); - tp.execute(buildArray(LockingModel.UNFAIR)); - tp.execute(buildArray(LockingModel.FAIR)); - } - - tp.execute(buildArray(LockingModel.SYNC)); - tp.printThroughput("Sync: "); + for (int i = 0; i < 2; i++) { + tp.execute(buildArray(LockingModel.SYNC)); + tp.execute(buildArray(LockingModel.UNFAIR)); + tp.execute(buildArray(LockingModel.FAIR)); + } + + tp.execute(buildArray(LockingModel.SYNC)); + tp.printThroughput("Sync: "); - tp.execute(buildArray(LockingModel.UNFAIR)); - tp.printThroughput("Unfair: "); + tp.execute(buildArray(LockingModel.UNFAIR)); + tp.printThroughput("Unfair: "); - tp.execute(buildArray(LockingModel.FAIR)); - tp.printThroughput("Fair: "); - } + tp.execute(buildArray(LockingModel.FAIR)); + tp.printThroughput("Fair: "); + } - static SelectiveLockRunnable[] buildArray(LockingModel model) { - SelectiveLockRunnable[] array = new SelectiveLockRunnable[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - array[i] = new SelectiveLockRunnable(model); + static SelectiveLockRunnable[] buildArray(LockingModel model) { + SelectiveLockRunnable[] array = new SelectiveLockRunnable[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + array[i] = new SelectiveLockRunnable(model); + } + return array; } - return array; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/LockingInJava.java b/logback-core/src/test/java/ch/qos/logback/core/issue/LockingInJava.java index 707c9bd4065629b7b0a8886f10e318a2f56e3e3a..780d48cec17a919300202cffda09b5972fc38604 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/LockingInJava.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/LockingInJava.java @@ -22,73 +22,68 @@ package ch.qos.logback.core.issue; */ public class LockingInJava implements Runnable { - static int THREAD_COUNT = 5; - static Object LOCK = new Object(); - static LockingInJava[] RUNNABLE_ARRAY = new LockingInJava[THREAD_COUNT]; - static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT]; + static int THREAD_COUNT = 5; + static Object LOCK = new Object(); + static LockingInJava[] RUNNABLE_ARRAY = new LockingInJava[THREAD_COUNT]; + static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT]; - private int counter = 0; - private boolean done = false; - - public static void main(String args[]) throws InterruptedException { - printEnvironmentInfo(); - execute(); - printResults(); - } + private int counter = 0; + private boolean done = false; - public static void printEnvironmentInfo() { - System.out.println("java.runtime.version = " - + System.getProperty("java.runtime.version")); - System.out.println("java.vendor = " - + System.getProperty("java.vendor")); - System.out.println("java.version = " - + System.getProperty("java.version")); - System.out.println("os.name = " - + System.getProperty("os.name")); - System.out.println("os.version = " - + System.getProperty("os.version")); - } - - public static void execute() throws InterruptedException { - for (int i = 0; i < THREAD_COUNT; i++) { - RUNNABLE_ARRAY[i] = new LockingInJava(); - THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]); - } - for (Thread t : THREAD_ARRAY) { - t.start(); + public static void main(String args[]) throws InterruptedException { + printEnvironmentInfo(); + execute(); + printResults(); } - // let the threads run for a while - Thread.sleep(10000); - - for (int i = THREAD_COUNT - 1; i <= 0; i--) { - RUNNABLE_ARRAY[i].done = true; + + public static void printEnvironmentInfo() { + System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version")); + System.out.println("java.vendor = " + System.getProperty("java.vendor")); + System.out.println("java.version = " + System.getProperty("java.version")); + System.out.println("os.name = " + System.getProperty("os.name")); + System.out.println("os.version = " + System.getProperty("os.version")); } - - } - public static void printResults() { - for (int i = 0; i < RUNNABLE_ARRAY.length; i++) { - System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]); + public static void execute() throws InterruptedException { + for (int i = 0; i < THREAD_COUNT; i++) { + RUNNABLE_ARRAY[i] = new LockingInJava(); + THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]); + } + for (Thread t : THREAD_ARRAY) { + t.start(); + } + // let the threads run for a while + Thread.sleep(10000); + + for (int i = THREAD_COUNT - 1; i <= 0; i--) { + RUNNABLE_ARRAY[i].done = true; + } + } - } - public void run() { - for (;;) { - synchronized (LOCK) { - counter++; - try { - Thread.sleep(10); - } catch (InterruptedException ex) { + public static void printResults() { + for (int i = 0; i < RUNNABLE_ARRAY.length; i++) { + System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]); } - if(done) { - return; + } + + public void run() { + for (;;) { + synchronized (LOCK) { + counter++; + try { + Thread.sleep(10); + } catch (InterruptedException ex) { + } + if (done) { + return; + } + } } - } } - } - public String toString() { - return "counter=" + counter; - } + public String toString() { + return "counter=" + counter; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockThroughput.java b/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockThroughput.java index 2c70565782d565ed6b71d05d888204487e09ffec..a52a1871911075ab775e13575913ac2e05dc7efa 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockThroughput.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockThroughput.java @@ -24,29 +24,28 @@ import ch.qos.logback.core.issue.SelectiveLockRunnable.LockingModel; */ public class NoLockThroughput { - static int THREAD_COUNT = 3; - static long OVERALL_DURATION_IN_MILLIS = 2000; + static int THREAD_COUNT = 3; + static long OVERALL_DURATION_IN_MILLIS = 2000; - public static void main(String args[]) throws InterruptedException { + public static void main(String args[]) throws InterruptedException { - ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator( - OVERALL_DURATION_IN_MILLIS); - tp.printEnvironmentInfo("NoLockThroughput"); + ThreadedThroughputCalculator tp = new ThreadedThroughputCalculator(OVERALL_DURATION_IN_MILLIS); + tp.printEnvironmentInfo("NoLockThroughput"); - for (int i = 0; i < 2; i++) { - tp.execute(buildArray(LockingModel.NOLOCK)); - } + for (int i = 0; i < 2; i++) { + tp.execute(buildArray(LockingModel.NOLOCK)); + } - tp.execute(buildArray(LockingModel.NOLOCK)); - tp.printThroughput("No lock: ", true); - } + tp.execute(buildArray(LockingModel.NOLOCK)); + tp.printThroughput("No lock: ", true); + } - static SelectiveLockRunnable[] buildArray(LockingModel model) { - SelectiveLockRunnable[] array = new SelectiveLockRunnable[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - array[i] = new SelectiveLockRunnable(model); + static SelectiveLockRunnable[] buildArray(LockingModel model) { + SelectiveLockRunnable[] array = new SelectiveLockRunnable[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + array[i] = new SelectiveLockRunnable(model); + } + return array; } - return array; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockingInJava.java b/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockingInJava.java index d492b7fe9f5eeb7fd6ae1674473926639e88c26a..719361f67006a213b4c9c36c1e5b26a3d9340702 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockingInJava.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/NoLockingInJava.java @@ -21,67 +21,62 @@ package ch.qos.logback.core.issue; */ public class NoLockingInJava implements Runnable { - static int THREAD_COUNT = 5; - static Object LOCK = new Object(); - static NoLockingInJava[] RUNNABLE_ARRAY = new NoLockingInJava[THREAD_COUNT]; - static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT]; + static int THREAD_COUNT = 5; + static Object LOCK = new Object(); + static NoLockingInJava[] RUNNABLE_ARRAY = new NoLockingInJava[THREAD_COUNT]; + static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT]; - private int counter = 0; - private boolean done = false; + private int counter = 0; + private boolean done = false; - public static void main(String args[]) throws InterruptedException { - printEnvironmentInfo(); - execute(); - printResults(); - } - - public static void printEnvironmentInfo() { - System.out.println("java.runtime.version = " - + System.getProperty("java.runtime.version")); - System.out.println("java.vendor = " - + System.getProperty("java.vendor")); - System.out.println("java.version = " - + System.getProperty("java.version")); - System.out.println("os.name = " - + System.getProperty("os.name")); - System.out.println("os.version = " - + System.getProperty("os.version")); - } - - public static void execute() throws InterruptedException { - for (int i = 0; i < THREAD_COUNT; i++) { - RUNNABLE_ARRAY[i] = new NoLockingInJava(); - THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]); + public static void main(String args[]) throws InterruptedException { + printEnvironmentInfo(); + execute(); + printResults(); } - for (Thread t : THREAD_ARRAY) { - t.start(); - } - // let the threads run for a while - Thread.sleep(10000); - for (int i = THREAD_COUNT - 1; i <= 0; i--) { - RUNNABLE_ARRAY[i].done = true; + public static void printEnvironmentInfo() { + System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version")); + System.out.println("java.vendor = " + System.getProperty("java.vendor")); + System.out.println("java.version = " + System.getProperty("java.version")); + System.out.println("os.name = " + System.getProperty("os.name")); + System.out.println("os.version = " + System.getProperty("os.version")); } - } + public static void execute() throws InterruptedException { + for (int i = 0; i < THREAD_COUNT; i++) { + RUNNABLE_ARRAY[i] = new NoLockingInJava(); + THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]); + } + for (Thread t : THREAD_ARRAY) { + t.start(); + } + // let the threads run for a while + Thread.sleep(10000); + + for (int i = THREAD_COUNT - 1; i <= 0; i--) { + RUNNABLE_ARRAY[i].done = true; + } - public static void printResults() { - for (int i = 0; i < RUNNABLE_ARRAY.length; i++) { - System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]); } - } - public void run() { - for (;;) { - counter++; - if (done) { - return; - } + public static void printResults() { + for (int i = 0; i < RUNNABLE_ARRAY.length; i++) { + System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]); + } } - } - public String toString() { - return "counter=" + counter; - } + public void run() { + for (;;) { + counter++; + if (done) { + return; + } + } + } + + public String toString() { + return "counter=" + counter; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/SelectiveLockRunnable.java b/logback-core/src/test/java/ch/qos/logback/core/issue/SelectiveLockRunnable.java index f266aa14978c15e98d2fad659e0ff854ec2de499..b03d47c03605f99e00feefbcea74ad9e7246a583 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/SelectiveLockRunnable.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/SelectiveLockRunnable.java @@ -26,81 +26,81 @@ import ch.qos.logback.core.contention.RunnableWithCounterAndDone; */ public class SelectiveLockRunnable extends RunnableWithCounterAndDone { - enum LockingModel { - NOLOCK, SYNC, FAIR, UNFAIR; - } + enum LockingModel { + NOLOCK, SYNC, FAIR, UNFAIR; + } + + static Object LOCK = new Object(); + static Lock FAIR_LOCK = new ReentrantLock(true); + static Lock UNFAIR_LOCK = new ReentrantLock(false); - static Object LOCK = new Object(); - static Lock FAIR_LOCK = new ReentrantLock(true); - static Lock UNFAIR_LOCK = new ReentrantLock(false); + LockingModel model; - LockingModel model; + SelectiveLockRunnable(LockingModel model) { + this.model = model; + } - SelectiveLockRunnable(LockingModel model) { - this.model = model; - } + public void run() { + switch (model) { + case NOLOCK: + nolockRun(); + break; + case SYNC: + synchronizedRun(); + break; + case FAIR: + fairLockRun(); + break; + case UNFAIR: + unfairLockRun(); + break; + } + } - public void run() { - switch (model) { - case NOLOCK: - nolockRun(); - break; - case SYNC: - synchronizedRun(); - break; - case FAIR: - fairLockRun(); - break; - case UNFAIR: - unfairLockRun(); - break; + void fairLockRun() { + for (;;) { + FAIR_LOCK.lock(); + counter++; + FAIR_LOCK.unlock(); + if (done) { + return; + } + } } - } - void fairLockRun() { - for (;;) { - FAIR_LOCK.lock(); - counter++; - FAIR_LOCK.unlock(); - if (done) { - return; - } + void unfairLockRun() { + for (;;) { + UNFAIR_LOCK.lock(); + counter++; + UNFAIR_LOCK.unlock(); + if (done) { + return; + } + } } - } - void unfairLockRun() { - for (;;) { - UNFAIR_LOCK.lock(); - counter++; - UNFAIR_LOCK.unlock(); - if (done) { - return; - } + void nolockRun() { + for (;;) { + counter++; + if (done) { + return; + } + } } - } - void nolockRun() { - for (;;) { - counter++; - if (done) { - return; - } + void synchronizedRun() { + for (;;) { + synchronized (LOCK) { + counter++; + } + if (done) { + return; + } + } } - } - void synchronizedRun() { - for (;;) { - synchronized (LOCK) { - counter++; - } - if (done) { - return; - } + @Override + public String toString() { + return "SelectiveLockRunnable " + model; } - } - - @Override - public String toString() { - return "SelectiveLockRunnable "+model; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/issue/lbcore258/FileLockSimulator.java b/logback-core/src/test/java/ch/qos/logback/core/issue/lbcore258/FileLockSimulator.java index 2865a9f8f6d5582664c85fe4be53cb527c92626a..5e71ec79ab0325955cded737feb414ec8b268d34 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/issue/lbcore258/FileLockSimulator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/issue/lbcore258/FileLockSimulator.java @@ -18,7 +18,6 @@ import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; - /** * FileLockSimulator is a small application intended to simulate FileAppender in prudent mode. * In this mode, the application obtains an exclusive lock on the file, writes to the file and @@ -43,60 +42,61 @@ import java.nio.channels.FileLock; * lock to the point of appearing deadlocked. * */ -public class FileLockSimulator { +public class FileLockSimulator { - static String LINE_SEPARATOR = System.getProperty("line.separator"); - static final int DOT_FREQ = 128; - static final int DOT_WITH_NEW_LINE_FREQ = DOT_FREQ * 80; + static String LINE_SEPARATOR = System.getProperty("line.separator"); + static final int DOT_FREQ = 128; + static final int DOT_WITH_NEW_LINE_FREQ = DOT_FREQ * 80; - static String instanceName; - static int delay; - static FileOutputStream fos; - static FileChannel fileChannel; + static String instanceName; + static int delay; + static FileOutputStream fos; + static FileChannel fileChannel; - public static void main(String[] args) throws IOException, InterruptedException { + public static void main(String[] args) throws IOException, InterruptedException { - String instanceName = args[0]; - System.out.println("Instance named as [" + instanceName + "]"); + String instanceName = args[0]; + System.out.println("Instance named as [" + instanceName + "]"); - String fileStr = args[1]; - System.out.println("Output target specified as [" + fileStr + "]"); + String fileStr = args[1]; + System.out.println("Output target specified as [" + fileStr + "]"); - int delay = Integer.parseInt(args[2]); - System.out.println("Sleep delay specified as [" + delay + "] milliseconds"); + int delay = Integer.parseInt(args[2]); + System.out.println("Sleep delay specified as [" + delay + "] milliseconds"); - fos = new FileOutputStream(fileStr, true); - fileChannel = fos.getChannel(); + fos = new FileOutputStream(fileStr, true); + fileChannel = fos.getChannel(); - for (int i = 1; ; i++) { - printDotAndSleep(i); - lockAndWrite(i); + for (int i = 1;; i++) { + printDotAndSleep(i); + lockAndWrite(i); + } } - } - static void lockAndWrite(int i) throws InterruptedException, IOException { - FileLock fileLock = null; - try { - fileLock = fileChannel.lock(); - long position = fileChannel.position(); - long size = fileChannel.size(); - if (size != position) { - fileChannel.position(size); - } - String msg = "hello from" + instanceName + " " + i + LINE_SEPARATOR; - fos.write(msg.getBytes()); - } finally { - if (fileLock != null) { - fileLock.release(); - } + static void lockAndWrite(int i) throws InterruptedException, IOException { + FileLock fileLock = null; + try { + fileLock = fileChannel.lock(); + long position = fileChannel.position(); + long size = fileChannel.size(); + if (size != position) { + fileChannel.position(size); + } + String msg = "hello from" + instanceName + " " + i + LINE_SEPARATOR; + fos.write(msg.getBytes()); + } finally { + if (fileLock != null) { + fileLock.release(); + } + } } - } - static void printDotAndSleep(int i) throws InterruptedException { - if (i % DOT_FREQ == 0) { - System.out.print("."); - Thread.sleep(delay); + static void printDotAndSleep(int i) throws InterruptedException { + if (i % DOT_FREQ == 0) { + System.out.print("."); + Thread.sleep(delay); + } + if (i % DOT_WITH_NEW_LINE_FREQ == 0) + System.out.println(""); } - if (i % DOT_WITH_NEW_LINE_FREQ == 0) System.out.println(""); - } } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/PackageTest.java index bc9fb9def772c8ead6b0d6b141d393b53394fb8c..4d8593ef51fc1b019ecf3b3229975031574ecbfc 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/PackageTest.java @@ -18,16 +18,10 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { SkippingInInterpreterTest.class, - TrivialConfiguratorTest.class, - ch.qos.logback.core.joran.action.PackageTest.class, - ch.qos.logback.core.joran.event.PackageTest.class, - ch.qos.logback.core.joran.util.PackageTest.class, - ch.qos.logback.core.joran.spi.PackageTest.class, - ch.qos.logback.core.joran.replay.PackageTest.class, - ch.qos.logback.core.joran.implicitAction.PackageTest.class, - ch.qos.logback.core.joran.conditional.PackageTest.class - }) +@SuiteClasses({ SkippingInInterpreterTest.class, TrivialConfiguratorTest.class, ch.qos.logback.core.joran.action.PackageTest.class, + ch.qos.logback.core.joran.event.PackageTest.class, ch.qos.logback.core.joran.util.PackageTest.class, ch.qos.logback.core.joran.spi.PackageTest.class, + ch.qos.logback.core.joran.replay.PackageTest.class, ch.qos.logback.core.joran.implicitAction.PackageTest.class, + ch.qos.logback.core.joran.conditional.PackageTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/SimpleConfigurator.java b/logback-core/src/test/java/ch/qos/logback/core/joran/SimpleConfigurator.java index 5a2b35c2811108eeba09426cbfd9bcd6e976e983..9edfd42c3f44e8aee16966984509361367ec1a2b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/SimpleConfigurator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/SimpleConfigurator.java @@ -24,33 +24,33 @@ import ch.qos.logback.core.joran.spi.RuleStore; public class SimpleConfigurator extends GenericConfigurator { - HashMap rulesMap; - - public SimpleConfigurator(HashMap rules) { - this.rulesMap = rules; - } - - @Override - protected void addImplicitRules(Interpreter interpreter) { - NestedComplexPropertyIA nestedIA = new NestedComplexPropertyIA(); - nestedIA.setContext(context); - interpreter.addImplicitAction(nestedIA); - - NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); - nestedSimpleIA.setContext(context); - interpreter.addImplicitAction(nestedSimpleIA); - } - - public Interpreter getInterpreter() { - return interpreter; - } - - @Override - protected void addInstanceRules(RuleStore rs) { - for(ElementSelector elementSelector : rulesMap.keySet()) { - Action action = rulesMap.get(elementSelector); - rs.addRule(elementSelector, action); + HashMap rulesMap; + + public SimpleConfigurator(HashMap rules) { + this.rulesMap = rules; + } + + @Override + protected void addImplicitRules(Interpreter interpreter) { + NestedComplexPropertyIA nestedIA = new NestedComplexPropertyIA(); + nestedIA.setContext(context); + interpreter.addImplicitAction(nestedIA); + + NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); + nestedSimpleIA.setContext(context); + interpreter.addImplicitAction(nestedSimpleIA); + } + + public Interpreter getInterpreter() { + return interpreter; + } + + @Override + protected void addInstanceRules(RuleStore rs) { + for (ElementSelector elementSelector : rulesMap.keySet()) { + Action action = rulesMap.get(elementSelector); + rs.addRule(elementSelector, action); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/SkippingInInterpreterTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/SkippingInInterpreterTest.java index 44c2fb8505b3b22e8813b4c3ea3762f1bb252d28..b3d823c38e4c75900f1794b7a07878acb275bd0e 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/SkippingInInterpreterTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/SkippingInInterpreterTest.java @@ -47,69 +47,68 @@ import ch.qos.logback.core.util.CoreTestConstants; */ public class SkippingInInterpreterTest { - HashMap rulesMap = new HashMap(); - Context context = new ContextBase(); - StatusManager sm = context.getStatusManager(); - - SAXParser createParser() throws Exception { - SAXParserFactory spf = SAXParserFactory.newInstance(); - return spf.newSAXParser(); - } - - void doTest(String filename, Integer expectedInt, Class exceptionClass) - throws Exception { - - rulesMap.put(new ElementSelector("test"), new NOPAction()); - rulesMap.put(new ElementSelector("test/badBegin"), new BadBeginAction()); - rulesMap.put(new ElementSelector("test/badBegin/touch"), new TouchAction()); - rulesMap.put(new ElementSelector("test/badEnd"), new BadEndAction()); - rulesMap.put(new ElementSelector("test/badEnd/touch"), new TouchAction()); - rulesMap.put(new ElementSelector("test/hello"), new HelloAction()); - - rulesMap.put(new ElementSelector("test/isolate"), new NOPAction()); - rulesMap.put(new ElementSelector("test/isolate/badEnd"), new BadEndAction()); - rulesMap.put(new ElementSelector("test/isolate/badEnd/touch"), new TouchAction()); - rulesMap.put(new ElementSelector("test/isolate/touch"), new TouchAction()); - rulesMap.put(new ElementSelector("test/hello"), new HelloAction()); - - TrivialConfigurator tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - tc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/skip/" + filename); - - String str = context.getProperty(HelloAction.PROPERTY_KEY); - assertEquals("Hello John Doe.", str); - - Integer i = (Integer) context.getObject(TouchAction.KEY); - if (expectedInt == null) { - assertNull(i); - } else { - assertEquals(expectedInt, i); + HashMap rulesMap = new HashMap(); + Context context = new ContextBase(); + StatusManager sm = context.getStatusManager(); + + SAXParser createParser() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + return spf.newSAXParser(); + } + + void doTest(String filename, Integer expectedInt, Class exceptionClass) throws Exception { + + rulesMap.put(new ElementSelector("test"), new NOPAction()); + rulesMap.put(new ElementSelector("test/badBegin"), new BadBeginAction()); + rulesMap.put(new ElementSelector("test/badBegin/touch"), new TouchAction()); + rulesMap.put(new ElementSelector("test/badEnd"), new BadEndAction()); + rulesMap.put(new ElementSelector("test/badEnd/touch"), new TouchAction()); + rulesMap.put(new ElementSelector("test/hello"), new HelloAction()); + + rulesMap.put(new ElementSelector("test/isolate"), new NOPAction()); + rulesMap.put(new ElementSelector("test/isolate/badEnd"), new BadEndAction()); + rulesMap.put(new ElementSelector("test/isolate/badEnd/touch"), new TouchAction()); + rulesMap.put(new ElementSelector("test/isolate/touch"), new TouchAction()); + rulesMap.put(new ElementSelector("test/hello"), new HelloAction()); + + TrivialConfigurator tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + tc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/skip/" + filename); + + String str = context.getProperty(HelloAction.PROPERTY_KEY); + assertEquals("Hello John Doe.", str); + + Integer i = (Integer) context.getObject(TouchAction.KEY); + if (expectedInt == null) { + assertNull(i); + } else { + assertEquals(expectedInt, i); + } + + // check the existence of an ERROR status + List statusList = sm.getCopyOfStatusList(); + Status s0 = statusList.get(0); + assertEquals(Status.ERROR, s0.getLevel()); + assertTrue(s0.getThrowable().getClass() == exceptionClass); + } + + @Test + public void testSkippingRuntimeExInBadBegin() throws Exception { + doTest("badBegin1.xml", null, IllegalStateException.class); } - // check the existence of an ERROR status - List statusList = sm.getCopyOfStatusList(); - Status s0 = statusList.get(0); - assertEquals(Status.ERROR, s0.getLevel()); - assertTrue(s0.getThrowable().getClass() == exceptionClass); - } - - @Test - public void testSkippingRuntimeExInBadBegin() throws Exception { - doTest("badBegin1.xml", null, IllegalStateException.class); - } - - @Test - public void testSkippingActionExInBadBegin() throws Exception { - doTest("badBegin2.xml", null, ActionException.class); - } - - @Test - public void testSkippingRuntimeExInBadEnd() throws Exception { - doTest("badEnd1.xml", new Integer(2), IllegalStateException.class); - } - - @Test - public void testSkippingActionExInBadEnd() throws Exception { - doTest("badEnd2.xml", new Integer(2), ActionException.class); - } + @Test + public void testSkippingActionExInBadBegin() throws Exception { + doTest("badBegin2.xml", null, ActionException.class); + } + + @Test + public void testSkippingRuntimeExInBadEnd() throws Exception { + doTest("badEnd1.xml", new Integer(2), IllegalStateException.class); + } + + @Test + public void testSkippingActionExInBadEnd() throws Exception { + doTest("badEnd2.xml", new Integer(2), ActionException.class); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfigurator.java b/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfigurator.java index c2e900b7ac8865f557de12d800cbda8fe3526fe2..6278cfc524efc8ed56b025e44fa830394d102848 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfigurator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfigurator.java @@ -22,22 +22,22 @@ import ch.qos.logback.core.joran.spi.RuleStore; public class TrivialConfigurator extends GenericConfigurator { - HashMap rulesMap; - - public TrivialConfigurator(HashMap rules) { - this.rulesMap = rules; - } - - @Override - protected void addImplicitRules(Interpreter interpreter) { - } - - @Override - protected void addInstanceRules(RuleStore rs) { - for(ElementSelector elementSelector : rulesMap.keySet()) { - Action action = rulesMap.get(elementSelector); - rs.addRule(elementSelector, action); + HashMap rulesMap; + + public TrivialConfigurator(HashMap rules) { + this.rulesMap = rules; + } + + @Override + protected void addImplicitRules(Interpreter interpreter) { + } + + @Override + protected void addInstanceRules(RuleStore rs) { + for (ElementSelector elementSelector : rulesMap.keySet()) { + Action action = rulesMap.get(elementSelector); + rs.addRule(elementSelector, action); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfiguratorTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfiguratorTest.java index ce581a7d268a9736435e66c182c87238734a01b6..f298c18cae36ccf570c0b6fd972c50f46ff84f48 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfiguratorTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/TrivialConfiguratorTest.java @@ -43,135 +43,130 @@ import ch.qos.logback.core.util.CoreTestConstants; public class TrivialConfiguratorTest { - Context context = new ContextBase(); - HashMap rulesMap = new HashMap(); - - public void doTest(String filename) throws Exception { - - // rule store is case insensitve - rulesMap.put(new ElementSelector("x/inc"), new IncAction()); - - TrivialConfigurator trivialConfigurator = new TrivialConfigurator(rulesMap); - - trivialConfigurator.setContext(context); - trivialConfigurator.doConfigure(filename); - } - - @Test - public void smoke() throws Exception { - int oldBeginCount = IncAction.beginCount; - int oldEndCount = IncAction.endCount; - int oldErrorCount = IncAction.errorCount; - doTest(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + "inc.xml"); - assertEquals(oldErrorCount, IncAction.errorCount); - assertEquals(oldBeginCount + 1, IncAction.beginCount); - assertEquals(oldEndCount + 1, IncAction.endCount); - } - - @Test - public void inexistentFile() { - TrivialStatusListener tsl = new TrivialStatusListener(); - tsl.start(); - String filename = CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" - + "nothereBLAH.xml"; - context.getStatusManager().add(tsl); - try { - doTest(filename); - } catch (Exception e) { - assertTrue(e.getMessage().startsWith("Could not open [")); + Context context = new ContextBase(); + HashMap rulesMap = new HashMap(); + + public void doTest(String filename) throws Exception { + + // rule store is case insensitve + rulesMap.put(new ElementSelector("x/inc"), new IncAction()); + + TrivialConfigurator trivialConfigurator = new TrivialConfigurator(rulesMap); + + trivialConfigurator.setContext(context); + trivialConfigurator.doConfigure(filename); } - assertTrue(tsl.list.size() + " should be greater than or equal to 1", - tsl.list.size() >= 1); - Status s0 = tsl.list.get(0); - assertTrue(s0.getMessage().startsWith("Could not open [")); - } - - @Test - public void illFormedXML() { - TrivialStatusListener tsl = new TrivialStatusListener(); - tsl.start(); - String filename = CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + "illformed.xml"; - context.getStatusManager().add(tsl); - try { - doTest(filename); - } catch (Exception e) { + + @Test + public void smoke() throws Exception { + int oldBeginCount = IncAction.beginCount; + int oldEndCount = IncAction.endCount; + int oldErrorCount = IncAction.errorCount; + doTest(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + "inc.xml"); + assertEquals(oldErrorCount, IncAction.errorCount); + assertEquals(oldBeginCount + 1, IncAction.beginCount); + assertEquals(oldEndCount + 1, IncAction.endCount); } - assertEquals(1, tsl.list.size()); - Status s0 = tsl.list.get(0); - assertTrue(s0.getMessage().startsWith(CoreConstants.XML_PARSING)); - } - - @Test - public void lbcore105() throws IOException, JoranException { - String jarEntry = "buzz.xml"; - File jarFile = makeRandomJarFile(); - fillInJarFile(jarFile, jarEntry); - URL url = asURL(jarFile, jarEntry); - TrivialConfigurator tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - tc.doConfigure(url); - // deleting an open file fails - assertTrue(jarFile.delete()); - assertFalse(jarFile.exists()); - } - - @Test - public void lbcore127() throws IOException, JoranException { - String jarEntry = "buzz.xml"; - String jarEntry2 = "lightyear.xml"; - - File jarFile = makeRandomJarFile(); - fillInJarFile(jarFile, jarEntry, jarEntry2); - - URL url1 = asURL(jarFile, jarEntry); - URL url2 = asURL(jarFile, jarEntry2); - - URLConnection urlConnection2 = url2.openConnection(); - urlConnection2.setUseCaches(false); - InputStream is = urlConnection2.getInputStream(); - - TrivialConfigurator tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - tc.doConfigure(url1); - - is.read(); - is.close(); - - // deleting an open file fails - assertTrue(jarFile.delete()); - assertFalse(jarFile.exists()); - } - - File makeRandomJarFile() { - File outputDir = new File(CoreTestConstants.OUTPUT_DIR_PREFIX); - outputDir.mkdirs(); - int randomPart = RandomUtil.getPositiveInt(); - return new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "foo-" + randomPart - + ".jar"); - } - - private void fillInJarFile(File jarFile, String jarEntryName) - throws IOException { - fillInJarFile(jarFile, jarEntryName, null); - } - - private void fillInJarFile(File jarFile, String jarEntryName1, - String jarEntryName2) throws IOException { - JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); - jos.putNextEntry(new ZipEntry(jarEntryName1)); - jos.write("".getBytes()); - jos.closeEntry(); - if (jarEntryName2 != null) { - jos.putNextEntry(new ZipEntry(jarEntryName2)); - jos.write("".getBytes()); - jos.closeEntry(); + + @Test + public void inexistentFile() { + TrivialStatusListener tsl = new TrivialStatusListener(); + tsl.start(); + String filename = CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + "nothereBLAH.xml"; + context.getStatusManager().add(tsl); + try { + doTest(filename); + } catch (Exception e) { + assertTrue(e.getMessage().startsWith("Could not open [")); + } + assertTrue(tsl.list.size() + " should be greater than or equal to 1", tsl.list.size() >= 1); + Status s0 = tsl.list.get(0); + assertTrue(s0.getMessage().startsWith("Could not open [")); } - jos.close(); - } - URL asURL(File jarFile, String jarEntryName) throws IOException { - URL innerURL = jarFile.toURI().toURL(); - return new URL("jar:" + innerURL + "!/" + jarEntryName); - } + @Test + public void illFormedXML() { + TrivialStatusListener tsl = new TrivialStatusListener(); + tsl.start(); + String filename = CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + "illformed.xml"; + context.getStatusManager().add(tsl); + try { + doTest(filename); + } catch (Exception e) { + } + assertEquals(1, tsl.list.size()); + Status s0 = tsl.list.get(0); + assertTrue(s0.getMessage().startsWith(CoreConstants.XML_PARSING)); + } + + @Test + public void lbcore105() throws IOException, JoranException { + String jarEntry = "buzz.xml"; + File jarFile = makeRandomJarFile(); + fillInJarFile(jarFile, jarEntry); + URL url = asURL(jarFile, jarEntry); + TrivialConfigurator tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + tc.doConfigure(url); + // deleting an open file fails + assertTrue(jarFile.delete()); + assertFalse(jarFile.exists()); + } + + @Test + public void lbcore127() throws IOException, JoranException { + String jarEntry = "buzz.xml"; + String jarEntry2 = "lightyear.xml"; + + File jarFile = makeRandomJarFile(); + fillInJarFile(jarFile, jarEntry, jarEntry2); + + URL url1 = asURL(jarFile, jarEntry); + URL url2 = asURL(jarFile, jarEntry2); + + URLConnection urlConnection2 = url2.openConnection(); + urlConnection2.setUseCaches(false); + InputStream is = urlConnection2.getInputStream(); + + TrivialConfigurator tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + tc.doConfigure(url1); + + is.read(); + is.close(); + + // deleting an open file fails + assertTrue(jarFile.delete()); + assertFalse(jarFile.exists()); + } + + File makeRandomJarFile() { + File outputDir = new File(CoreTestConstants.OUTPUT_DIR_PREFIX); + outputDir.mkdirs(); + int randomPart = RandomUtil.getPositiveInt(); + return new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "foo-" + randomPart + ".jar"); + } + + private void fillInJarFile(File jarFile, String jarEntryName) throws IOException { + fillInJarFile(jarFile, jarEntryName, null); + } + + private void fillInJarFile(File jarFile, String jarEntryName1, String jarEntryName2) throws IOException { + JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); + jos.putNextEntry(new ZipEntry(jarEntryName1)); + jos.write("".getBytes()); + jos.closeEntry(); + if (jarEntryName2 != null) { + jos.putNextEntry(new ZipEntry(jarEntryName2)); + jos.write("".getBytes()); + jos.closeEntry(); + } + jos.close(); + } + + URL asURL(File jarFile, String jarEntryName) throws IOException { + URL innerURL = jarFile.toURI().toURL(); + return new URL("jar:" + innerURL + "!/" + jarEntryName); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/AsLowerCasePropertyDefiner.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/AsLowerCasePropertyDefiner.java index ba0cf5b4e550dd396d6475f4bbe617d6db4a5fa7..de457545e688b0048e1a67ee69a279159dc863fa 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/AsLowerCasePropertyDefiner.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/AsLowerCasePropertyDefiner.java @@ -17,17 +17,17 @@ import ch.qos.logback.core.PropertyDefinerBase; public class AsLowerCasePropertyDefiner extends PropertyDefinerBase { - String val; + String val; - public String getPropertyValue() { - if (val == null) { - return null; - } else { - return val.toLowerCase(); + public String getPropertyValue() { + if (val == null) { + return null; + } else { + return val.toLowerCase(); + } } - } - public void setValue(String val) { - this.val = val; - } + public void setValue(String val) { + this.val = val; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/DefinePropertyActionTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/DefinePropertyActionTest.java index 141ef815b4b751ad3d64c2cc3493b1611d5ed1b6..66f26cc090df605411da35936ec33c208e7ee980 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/DefinePropertyActionTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/DefinePropertyActionTest.java @@ -40,69 +40,66 @@ import ch.qos.logback.core.util.CoreTestConstants; */ public class DefinePropertyActionTest { - private static final String DEFINE_INPUT_DIR = CoreTestConstants.JORAN_INPUT_PREFIX - + "define/"; - private static final String GOOD_XML = "good.xml"; - private static final String NONAME_XML = "noname.xml"; - private static final String NOCLASS_XML = "noclass.xml"; - private static final String BADCLASS_XML = "badclass.xml"; + private static final String DEFINE_INPUT_DIR = CoreTestConstants.JORAN_INPUT_PREFIX + "define/"; + private static final String GOOD_XML = "good.xml"; + private static final String NONAME_XML = "noname.xml"; + private static final String NOCLASS_XML = "noclass.xml"; + private static final String BADCLASS_XML = "badclass.xml"; - SimpleConfigurator simpleConfigurator; - Context context = new ContextBase(); - DefinePropertyAction definerAction; - InterpretationContext ic; - StatusChecker checker = new StatusChecker(context); + SimpleConfigurator simpleConfigurator; + Context context = new ContextBase(); + DefinePropertyAction definerAction; + InterpretationContext ic; + StatusChecker checker = new StatusChecker(context); - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("define"), new DefinePropertyAction()); - simpleConfigurator = new SimpleConfigurator(rulesMap); - simpleConfigurator.setContext(context); - } + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("define"), new DefinePropertyAction()); + simpleConfigurator = new SimpleConfigurator(rulesMap); + simpleConfigurator.setContext(context); + } - @After - public void tearDown() throws Exception { - //StatusPrinter.printInCaseOfErrorsOrWarnings(context); - } + @After + public void tearDown() throws Exception { + // StatusPrinter.printInCaseOfErrorsOrWarnings(context); + } - @Test - public void good() throws JoranException { - simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + GOOD_XML); - InterpretationContext ic = simpleConfigurator.getInterpreter().getInterpretationContext(); - String inContextFoo = ic.getProperty("foo"); - assertEquals("monster", inContextFoo); - } + @Test + public void good() throws JoranException { + simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + GOOD_XML); + InterpretationContext ic = simpleConfigurator.getInterpreter().getInterpretationContext(); + String inContextFoo = ic.getProperty("foo"); + assertEquals("monster", inContextFoo); + } - @Test - public void noName() throws JoranException { - simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + NONAME_XML); - // get from context - String inContextFoo = context.getProperty("foo"); - assertNull(inContextFoo); - // check context errors - checker.assertContainsMatch(Status.ERROR, - "Missing property name for property definer. Near \\[define\\] line 1"); - } + @Test + public void noName() throws JoranException { + simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + NONAME_XML); + // get from context + String inContextFoo = context.getProperty("foo"); + assertNull(inContextFoo); + // check context errors + checker.assertContainsMatch(Status.ERROR, "Missing property name for property definer. Near \\[define\\] line 1"); + } - @Test - public void noClass() throws JoranException { - simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + NOCLASS_XML); - String inContextFoo = context.getProperty("foo"); - assertNull(inContextFoo); - checker.assertContainsMatch(Status.ERROR, - "Missing class name for property definer. Near \\[define\\] line 1"); - } + @Test + public void noClass() throws JoranException { + simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + NOCLASS_XML); + String inContextFoo = context.getProperty("foo"); + assertNull(inContextFoo); + checker.assertContainsMatch(Status.ERROR, "Missing class name for property definer. Near \\[define\\] line 1"); + } - @Test - public void testBadClass() throws JoranException { - simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + BADCLASS_XML); - // get from context - String inContextFoo = context.getProperty("foo"); - assertNull(inContextFoo); - // check context errors - checker.assertContainsMatch(Status.ERROR, "Could not create an PropertyDefiner of type"); - } + @Test + public void testBadClass() throws JoranException { + simpleConfigurator.doConfigure(DEFINE_INPUT_DIR + BADCLASS_XML); + // get from context + String inContextFoo = context.getProperty("foo"); + assertNull(inContextFoo); + // check context errors + checker.assertContainsMatch(Status.ERROR, "Could not create an PropertyDefiner of type"); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/DummyAttributes.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/DummyAttributes.java index 8ffbb694617ad8e3ea3f49abc3dc6342b1cb9d2f..fb546077ffe5b070fef927b77f7cd06de90a45f1 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/DummyAttributes.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/DummyAttributes.java @@ -19,58 +19,58 @@ import org.xml.sax.Attributes; public class DummyAttributes implements Attributes { - HashMap atts = new HashMap(); + HashMap atts = new HashMap(); - public int getIndex(String qName) { - return 0; - } + public int getIndex(String qName) { + return 0; + } - public int getIndex(String uri, String localName) { - return 0; - } + public int getIndex(String uri, String localName) { + return 0; + } - public int getLength() { - return 0; - } + public int getLength() { + return 0; + } - public String getLocalName(int index) { - return null; - } + public String getLocalName(int index) { + return null; + } - public String getQName(int index) { - return null; - } + public String getQName(int index) { + return null; + } - public String getType(int index) { - return null; - } + public String getType(int index) { + return null; + } - public String getType(String qName) { - return null; - } + public String getType(String qName) { + return null; + } - public String getType(String uri, String localName) { - return null; - } + public String getType(String uri, String localName) { + return null; + } - public String getURI(int index) { - return null; - } + public String getURI(int index) { + return null; + } - public String getValue(int index) { - return null; - } + public String getValue(int index) { + return null; + } - public String getValue(String qName) { - return atts.get(qName); - } + public String getValue(String qName) { + return atts.get(qName); + } - public void setValue(String key, String value) { - atts.put(key, value); - } + public void setValue(String key, String value) { + atts.put(key, value); + } - public String getValue(String uri, String localName) { - return null; - } + public String getValue(String uri, String localName) { + return null; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/IncludeActionTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/IncludeActionTest.java index 4c2b201a8e76215708be7bbfb7457c5bcd1f3860..55a94d911428f8069d39289c828b11818a93228c 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/IncludeActionTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/IncludeActionTest.java @@ -47,182 +47,178 @@ import ch.qos.logback.core.util.StatusPrinter; public class IncludeActionTest { - final static String INCLUDE_KEY = "includeKey"; - final static String SUB_FILE_KEY = "subFileKey"; - final static String SECOND_FILE_KEY = "secondFileKey"; - - Context context = new ContextBase(); - StatusChecker statusChecker = new StatusChecker(context); - TrivialConfigurator tc; - - static final String INCLUSION_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX - + "inclusion/"; - - static final String TOP_BY_FILE = INCLUSION_DIR_PREFIX + "topByFile.xml"; - - static final String TOP_OPTIONAL = INCLUSION_DIR_PREFIX + "topOptional.xml"; - - static final String TOP_OPTIONAL_RESOURCE = INCLUSION_DIR_PREFIX + "topOptionalResource.xml"; - - static final String INTERMEDIARY_FILE = INCLUSION_DIR_PREFIX - + "intermediaryByFile.xml"; - - static final String SUB_FILE = INCLUSION_DIR_PREFIX + "subByFile.xml"; - - static final String MULTI_INCLUDE_BY_FILE = INCLUSION_DIR_PREFIX - + "multiIncludeByFile.xml"; - - static final String SECOND_FILE = INCLUSION_DIR_PREFIX + "second.xml"; - - static final String TOP_BY_URL = INCLUSION_DIR_PREFIX + "topByUrl.xml"; - - static final String INCLUDE_BY_RESOURCE = INCLUSION_DIR_PREFIX - + "topByResource.xml"; - - static final String INCLUDED_FILE = INCLUSION_DIR_PREFIX + "included.xml"; - static final String URL_TO_INCLUDE = "file:./" + INCLUDED_FILE; - - static final String INVALID = INCLUSION_DIR_PREFIX + "invalid.xml"; - - static final String INCLUDED_AS_RESOURCE = "asResource/joran/inclusion/includedAsResource.xml"; - - int diff = RandomUtil.getPositiveInt(); - - StackAction stackAction = new StackAction(); - - @Before - public void setUp() throws Exception { - FileTestUtil.makeTestOutputDir(); - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("x"), new NOPAction()); - rulesMap.put(new ElementSelector("x/include"), new IncludeAction()); - rulesMap.put(new ElementSelector("x/stack"), stackAction); - - tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - } - - @After - public void tearDown() throws Exception { - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - context = null; - System.clearProperty(INCLUDE_KEY); - System.clearProperty(SECOND_FILE_KEY); - System.clearProperty(SUB_FILE_KEY); - //StackAction.reset(); - } - - @Test - public void basicFile() throws JoranException { - System.setProperty(INCLUDE_KEY, INCLUDED_FILE); - tc.doConfigure(TOP_BY_FILE); - verifyConfig(new String[] { "IA", "IB" }); - } - - @Test - public void optionalFile() throws JoranException { - tc.doConfigure(TOP_OPTIONAL); - verifyConfig(new String[] { "IA", "IB" }); - StatusPrinter.print(context); - } - - @Test - public void optionalResource() throws JoranException { - tc.doConfigure(TOP_OPTIONAL_RESOURCE); - verifyConfig(new String[] { "IA", "IB" }); - StatusPrinter.print(context); - assertEquals(Status.INFO, statusChecker.getHighestLevel(0)); - } - - @Test - public void basicResource() throws JoranException { - System.setProperty(INCLUDE_KEY, INCLUDED_AS_RESOURCE); - tc.doConfigure(INCLUDE_BY_RESOURCE); - verifyConfig(new String[] { "AR_A", "AR_B" }); - } - - @Test - public void basicURL() throws JoranException { - System.setProperty(INCLUDE_KEY, URL_TO_INCLUDE); - tc.doConfigure(TOP_BY_URL); - verifyConfig(new String[] { "IA", "IB" }); - } - - @Test - public void noFileFound() throws JoranException { - System.setProperty(INCLUDE_KEY, "toto"); - tc.doConfigure(TOP_BY_FILE); - assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); - } - - @Test - public void withCorruptFile() throws JoranException, IOException { - String tmpOut = copyToTemp(INVALID); - System.setProperty(INCLUDE_KEY, tmpOut); - tc.doConfigure(TOP_BY_FILE); - assertEquals(Status.ERROR, statusChecker.getHighestLevel(0)); - assertTrue(statusChecker.containsException(SAXParseException.class)); - - // we like to erase the temp file in order to see - // if http://jira.qos.ch/browse/LBCORE-122 was fixed - File f = new File(tmpOut); - assertTrue(f.exists()); - assertTrue(f.delete()); - - } - - String copyToTemp(String in) throws IOException { - FileInputStream fis = new FileInputStream(in); - String out = CoreTestConstants.OUTPUT_DIR_PREFIX + "out" + diff; - FileOutputStream fos = new FileOutputStream(out); - int b; - while ((b = fis.read()) != -1) { - fos.write(b); + final static String INCLUDE_KEY = "includeKey"; + final static String SUB_FILE_KEY = "subFileKey"; + final static String SECOND_FILE_KEY = "secondFileKey"; + + Context context = new ContextBase(); + StatusChecker statusChecker = new StatusChecker(context); + TrivialConfigurator tc; + + static final String INCLUSION_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX + "inclusion/"; + + static final String TOP_BY_FILE = INCLUSION_DIR_PREFIX + "topByFile.xml"; + + static final String TOP_OPTIONAL = INCLUSION_DIR_PREFIX + "topOptional.xml"; + + static final String TOP_OPTIONAL_RESOURCE = INCLUSION_DIR_PREFIX + "topOptionalResource.xml"; + + static final String INTERMEDIARY_FILE = INCLUSION_DIR_PREFIX + "intermediaryByFile.xml"; + + static final String SUB_FILE = INCLUSION_DIR_PREFIX + "subByFile.xml"; + + static final String MULTI_INCLUDE_BY_FILE = INCLUSION_DIR_PREFIX + "multiIncludeByFile.xml"; + + static final String SECOND_FILE = INCLUSION_DIR_PREFIX + "second.xml"; + + static final String TOP_BY_URL = INCLUSION_DIR_PREFIX + "topByUrl.xml"; + + static final String INCLUDE_BY_RESOURCE = INCLUSION_DIR_PREFIX + "topByResource.xml"; + + static final String INCLUDED_FILE = INCLUSION_DIR_PREFIX + "included.xml"; + static final String URL_TO_INCLUDE = "file:./" + INCLUDED_FILE; + + static final String INVALID = INCLUSION_DIR_PREFIX + "invalid.xml"; + + static final String INCLUDED_AS_RESOURCE = "asResource/joran/inclusion/includedAsResource.xml"; + + int diff = RandomUtil.getPositiveInt(); + + StackAction stackAction = new StackAction(); + + @Before + public void setUp() throws Exception { + FileTestUtil.makeTestOutputDir(); + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("x"), new NOPAction()); + rulesMap.put(new ElementSelector("x/include"), new IncludeAction()); + rulesMap.put(new ElementSelector("x/stack"), stackAction); + + tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + } + + @After + public void tearDown() throws Exception { + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + context = null; + System.clearProperty(INCLUDE_KEY); + System.clearProperty(SECOND_FILE_KEY); + System.clearProperty(SUB_FILE_KEY); + // StackAction.reset(); + } + + @Test + public void basicFile() throws JoranException { + System.setProperty(INCLUDE_KEY, INCLUDED_FILE); + tc.doConfigure(TOP_BY_FILE); + verifyConfig(new String[] { "IA", "IB" }); + } + + @Test + public void optionalFile() throws JoranException { + tc.doConfigure(TOP_OPTIONAL); + verifyConfig(new String[] { "IA", "IB" }); + StatusPrinter.print(context); + } + + @Test + public void optionalResource() throws JoranException { + tc.doConfigure(TOP_OPTIONAL_RESOURCE); + verifyConfig(new String[] { "IA", "IB" }); + StatusPrinter.print(context); + assertEquals(Status.INFO, statusChecker.getHighestLevel(0)); + } + + @Test + public void basicResource() throws JoranException { + System.setProperty(INCLUDE_KEY, INCLUDED_AS_RESOURCE); + tc.doConfigure(INCLUDE_BY_RESOURCE); + verifyConfig(new String[] { "AR_A", "AR_B" }); + } + + @Test + public void basicURL() throws JoranException { + System.setProperty(INCLUDE_KEY, URL_TO_INCLUDE); + tc.doConfigure(TOP_BY_URL); + verifyConfig(new String[] { "IA", "IB" }); + } + + @Test + public void noFileFound() throws JoranException { + System.setProperty(INCLUDE_KEY, "toto"); + tc.doConfigure(TOP_BY_FILE); + assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); + } + + @Test + public void withCorruptFile() throws JoranException, IOException { + String tmpOut = copyToTemp(INVALID); + System.setProperty(INCLUDE_KEY, tmpOut); + tc.doConfigure(TOP_BY_FILE); + assertEquals(Status.ERROR, statusChecker.getHighestLevel(0)); + assertTrue(statusChecker.containsException(SAXParseException.class)); + + // we like to erase the temp file in order to see + // if http://jira.qos.ch/browse/LBCORE-122 was fixed + File f = new File(tmpOut); + assertTrue(f.exists()); + assertTrue(f.delete()); + + } + + String copyToTemp(String in) throws IOException { + FileInputStream fis = new FileInputStream(in); + String out = CoreTestConstants.OUTPUT_DIR_PREFIX + "out" + diff; + FileOutputStream fos = new FileOutputStream(out); + int b; + while ((b = fis.read()) != -1) { + fos.write(b); + } + fis.close(); + fos.close(); + return out; + } + + @Test + public void malformedURL() throws JoranException { + System.setProperty(INCLUDE_KEY, "htp://logback.qos.ch"); + tc.doConfigure(TOP_BY_URL); + assertEquals(Status.ERROR, statusChecker.getHighestLevel(0)); + assertTrue(statusChecker.containsException(MalformedURLException.class)); + } + + @Test + public void unknownURL() throws JoranException { + System.setProperty(INCLUDE_KEY, "http://logback2345.qos.ch"); + tc.doConfigure(TOP_BY_URL); + assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); + } + + @Test + public void nestedInclude() throws JoranException { + System.setProperty(SUB_FILE_KEY, SUB_FILE); + System.setProperty(INCLUDE_KEY, INTERMEDIARY_FILE); + tc.doConfigure(TOP_BY_FILE); + Stack witness = new Stack(); + witness.push("a"); + witness.push("b"); + witness.push("c"); + assertEquals(witness, stackAction.getStack()); + } + + @Test + public void multiInclude() throws JoranException { + System.setProperty(INCLUDE_KEY, INCLUDED_FILE); + System.setProperty(SECOND_FILE_KEY, SECOND_FILE); + tc.doConfigure(MULTI_INCLUDE_BY_FILE); + verifyConfig(new String[] { "IA", "IB", "SECOND" }); + } + + void verifyConfig(String[] expected) { + Stack witness = new Stack(); + witness.addAll(Arrays.asList(expected)); + assertEquals(witness, stackAction.getStack()); } - fis.close(); - fos.close(); - return out; - } - - @Test - public void malformedURL() throws JoranException { - System.setProperty(INCLUDE_KEY, "htp://logback.qos.ch"); - tc.doConfigure(TOP_BY_URL); - assertEquals(Status.ERROR, statusChecker.getHighestLevel(0)); - assertTrue(statusChecker.containsException(MalformedURLException.class)); - } - - @Test - public void unknownURL() throws JoranException { - System.setProperty(INCLUDE_KEY, "http://logback2345.qos.ch"); - tc.doConfigure(TOP_BY_URL); - assertEquals(Status.WARN, statusChecker.getHighestLevel(0)); - } - - @Test - public void nestedInclude() throws JoranException { - System.setProperty(SUB_FILE_KEY, SUB_FILE); - System.setProperty(INCLUDE_KEY, INTERMEDIARY_FILE); - tc.doConfigure(TOP_BY_FILE); - Stack witness = new Stack(); - witness.push("a"); - witness.push("b"); - witness.push("c"); - assertEquals(witness, stackAction.getStack()); - } - - @Test - public void multiInclude() throws JoranException { - System.setProperty(INCLUDE_KEY, INCLUDED_FILE); - System.setProperty(SECOND_FILE_KEY, SECOND_FILE); - tc.doConfigure(MULTI_INCLUDE_BY_FILE); - verifyConfig(new String[] { "IA", "IB", "SECOND" }); - } - - void verifyConfig(String[] expected) { - Stack witness = new Stack(); - witness.addAll(Arrays.asList(expected)); - assertEquals(witness, stackAction.getStack()); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/PackageTest.java index f9b99924740084468f6cdf8da1f888a233e0de10..591bcee89868d862766e1c21998fa567f7eebd34 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({PropertyActionTest.class, IncludeActionTest.class}) -public class PackageTest { +@SuiteClasses({ PropertyActionTest.class, IncludeActionTest.class }) +public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/PropertyActionTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/PropertyActionTest.java index 5f65698c2f75834eff76acf4c659d0becc519102..1248d366e992d64cc57aaea3d037182142e5e640 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/PropertyActionTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/PropertyActionTest.java @@ -33,129 +33,129 @@ import ch.qos.logback.core.util.StatusPrinter; * Test {@link PropertyAction}. * @author Ceki Gülcü */ -public class PropertyActionTest { - - Context context; - InterpretationContext ec; - PropertyAction propertyAction; - DummyAttributes atts = new DummyAttributes(); - - @Before - public void setUp() throws Exception { - context = new ContextBase(); - ec = new InterpretationContext(context, null); - propertyAction = new PropertyAction(); - propertyAction.setContext(context); - } - - @After - public void tearDown() throws Exception { - context = null; - propertyAction = null; - atts = null; - } - - @Test - public void nameValuePair() { - atts.setValue("name", "v1"); - atts.setValue("value", "work"); - propertyAction.begin(ec, null, atts); - assertEquals("work", ec.getProperty("v1")); - } - - @Test - public void nameValuePairWithPrerequisiteSubsitution() { - context.putProperty("w", "wor"); - atts.setValue("name", "v1"); - atts.setValue("value", "${w}k"); - propertyAction.begin(ec, null, atts); - assertEquals("work", ec.getProperty("v1")); - } - - @Test - public void noValue() { - atts.setValue("name", "v1"); - propertyAction.begin(ec, null, atts); - assertEquals(1, context.getStatusManager().getCount()); - assertTrue(checkError()); - } - - @Test - public void noName() { - atts.setValue("value", "v1"); - propertyAction.begin(ec, null, atts); - assertEquals(1, context.getStatusManager().getCount()); - assertTrue(checkError()); - } - - @Test - public void noAttributes() { - propertyAction.begin(ec, null, atts); - assertEquals(1, context.getStatusManager().getCount()); - assertTrue(checkError()); - StatusPrinter.print(context); - } - - @Test - public void testFileNotLoaded() { - atts.setValue("file", "toto"); - atts.setValue("value", "work"); - propertyAction.begin(ec, null, atts); - assertEquals(1, context.getStatusManager().getCount()); - assertTrue(checkError()); - } - - @Test - public void testLoadFileWithPrerequisiteSubsitution() { - context.putProperty("STEM", CoreTestConstants.TEST_SRC_PREFIX + "input/joran"); - atts.setValue("file", "${STEM}/propertyActionTest.properties"); - propertyAction.begin(ec, null, atts); - assertEquals("tata", ec.getProperty("v1")); - assertEquals("toto", ec.getProperty("v2")); - } - - @Test - public void testLoadFile() { - atts.setValue("file", CoreTestConstants.TEST_SRC_PREFIX + "input/joran/propertyActionTest.properties"); - propertyAction.begin(ec, null, atts); - assertEquals("tata", ec.getProperty("v1")); - assertEquals("toto", ec.getProperty("v2")); - } - - @Test - public void testLoadResource() { - atts.setValue("resource", "asResource/joran/propertyActionTest.properties"); - propertyAction.begin(ec, null, atts); - assertEquals("tata", ec.getProperty("r1")); - assertEquals("toto", ec.getProperty("r2")); - } - - @Test - public void testLoadResourceWithPrerequisiteSubsitution() { - context.putProperty("STEM", "asResource/joran"); - atts.setValue("resource", "${STEM}/propertyActionTest.properties"); - propertyAction.begin(ec, null, atts); - assertEquals("tata", ec.getProperty("r1")); - assertEquals("toto", ec.getProperty("r2")); - } - - @Test - public void testLoadNotPossible() { - atts.setValue("file", "toto"); - propertyAction.begin(ec, null, atts); - assertEquals(1, context.getStatusManager().getCount()); - assertTrue(checkFileErrors()); - } - - private boolean checkError() { - Iterator it = context.getStatusManager().getCopyOfStatusList().iterator(); - ErrorStatus es = (ErrorStatus)it.next(); - return PropertyAction.INVALID_ATTRIBUTES.equals(es.getMessage()); - } - - private boolean checkFileErrors() { - Iterator it = context.getStatusManager().getCopyOfStatusList().iterator(); - ErrorStatus es1 = (ErrorStatus)it.next(); - return "Could not find properties file [toto].".equals(es1.getMessage()); - } +public class PropertyActionTest { + + Context context; + InterpretationContext ec; + PropertyAction propertyAction; + DummyAttributes atts = new DummyAttributes(); + + @Before + public void setUp() throws Exception { + context = new ContextBase(); + ec = new InterpretationContext(context, null); + propertyAction = new PropertyAction(); + propertyAction.setContext(context); + } + + @After + public void tearDown() throws Exception { + context = null; + propertyAction = null; + atts = null; + } + + @Test + public void nameValuePair() { + atts.setValue("name", "v1"); + atts.setValue("value", "work"); + propertyAction.begin(ec, null, atts); + assertEquals("work", ec.getProperty("v1")); + } + + @Test + public void nameValuePairWithPrerequisiteSubsitution() { + context.putProperty("w", "wor"); + atts.setValue("name", "v1"); + atts.setValue("value", "${w}k"); + propertyAction.begin(ec, null, atts); + assertEquals("work", ec.getProperty("v1")); + } + + @Test + public void noValue() { + atts.setValue("name", "v1"); + propertyAction.begin(ec, null, atts); + assertEquals(1, context.getStatusManager().getCount()); + assertTrue(checkError()); + } + + @Test + public void noName() { + atts.setValue("value", "v1"); + propertyAction.begin(ec, null, atts); + assertEquals(1, context.getStatusManager().getCount()); + assertTrue(checkError()); + } + + @Test + public void noAttributes() { + propertyAction.begin(ec, null, atts); + assertEquals(1, context.getStatusManager().getCount()); + assertTrue(checkError()); + StatusPrinter.print(context); + } + + @Test + public void testFileNotLoaded() { + atts.setValue("file", "toto"); + atts.setValue("value", "work"); + propertyAction.begin(ec, null, atts); + assertEquals(1, context.getStatusManager().getCount()); + assertTrue(checkError()); + } + + @Test + public void testLoadFileWithPrerequisiteSubsitution() { + context.putProperty("STEM", CoreTestConstants.TEST_SRC_PREFIX + "input/joran"); + atts.setValue("file", "${STEM}/propertyActionTest.properties"); + propertyAction.begin(ec, null, atts); + assertEquals("tata", ec.getProperty("v1")); + assertEquals("toto", ec.getProperty("v2")); + } + + @Test + public void testLoadFile() { + atts.setValue("file", CoreTestConstants.TEST_SRC_PREFIX + "input/joran/propertyActionTest.properties"); + propertyAction.begin(ec, null, atts); + assertEquals("tata", ec.getProperty("v1")); + assertEquals("toto", ec.getProperty("v2")); + } + + @Test + public void testLoadResource() { + atts.setValue("resource", "asResource/joran/propertyActionTest.properties"); + propertyAction.begin(ec, null, atts); + assertEquals("tata", ec.getProperty("r1")); + assertEquals("toto", ec.getProperty("r2")); + } + + @Test + public void testLoadResourceWithPrerequisiteSubsitution() { + context.putProperty("STEM", "asResource/joran"); + atts.setValue("resource", "${STEM}/propertyActionTest.properties"); + propertyAction.begin(ec, null, atts); + assertEquals("tata", ec.getProperty("r1")); + assertEquals("toto", ec.getProperty("r2")); + } + + @Test + public void testLoadNotPossible() { + atts.setValue("file", "toto"); + propertyAction.begin(ec, null, atts); + assertEquals(1, context.getStatusManager().getCount()); + assertTrue(checkFileErrors()); + } + + private boolean checkError() { + Iterator it = context.getStatusManager().getCopyOfStatusList().iterator(); + ErrorStatus es = (ErrorStatus) it.next(); + return PropertyAction.INVALID_ATTRIBUTES.equals(es.getMessage()); + } + + private boolean checkFileErrors() { + Iterator it = context.getStatusManager().getCopyOfStatusList().iterator(); + ErrorStatus es1 = (ErrorStatus) it.next(); + return "Could not find properties file [toto].".equals(es1.getMessage()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadBeginAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadBeginAction.java index 0ada090147bc4aa07d373f5752acc6744cbb2951..460b836ee4cf7f1eca5718d963b58747954eb240 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadBeginAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadBeginAction.java @@ -19,34 +19,31 @@ import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; +public class BadBeginAction extends Action { + static String EXCEPTION_TYPE = "type"; + static final int RUNTIME_EDXCEPTION = 0; + static final int ACTION_EXCEPTION = 1; -public class BadBeginAction extends Action { + int type; + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + + String exType = attributes.getValue(EXCEPTION_TYPE); + type = RUNTIME_EDXCEPTION; + if ("ActionException".equals(exType)) { + type = ACTION_EXCEPTION; + } + + switch (type) { + case ACTION_EXCEPTION: + throw new ActionException(); + default: + throw new IllegalStateException("bad begin"); + } - static String EXCEPTION_TYPE = "type"; - static final int RUNTIME_EDXCEPTION = 0; - static final int ACTION_EXCEPTION = 1; - - int type; - - public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - - String exType = attributes.getValue(EXCEPTION_TYPE); - type = RUNTIME_EDXCEPTION; - if("ActionException".equals(exType)) { - type = ACTION_EXCEPTION; - } - - switch(type) { - case ACTION_EXCEPTION: - throw new ActionException(); - default: - throw new IllegalStateException("bad begin"); } - - } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadEndAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadEndAction.java index 12adb43015676636bb8e0312b68cda5cb94663b0..a141c5293ae442b9ef6fd7b1498a493363b50782 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadEndAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/BadEndAction.java @@ -13,39 +13,34 @@ */ package ch.qos.logback.core.joran.action.ext; - - import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; +public class BadEndAction extends Action { + static String EXCEPTION_TYPE = "type"; + static final int RUNTIME_EXCEPTION = 0; + static final int ACTION_EXCEPTION = 1; -public class BadEndAction extends Action { + int type; - static String EXCEPTION_TYPE = "type"; - static final int RUNTIME_EXCEPTION = 0; - static final int ACTION_EXCEPTION = 1; - - int type; - - - public void begin(InterpretationContext ec, String name, Attributes attributes) { - String exType = attributes.getValue(EXCEPTION_TYPE); - type = RUNTIME_EXCEPTION; - if("ActionException".equals(exType)) { - type = ACTION_EXCEPTION; + public void begin(InterpretationContext ec, String name, Attributes attributes) { + String exType = attributes.getValue(EXCEPTION_TYPE); + type = RUNTIME_EXCEPTION; + if ("ActionException".equals(exType)) { + type = ACTION_EXCEPTION; + } } - } - public void end(InterpretationContext ec, String name) throws ActionException { - switch(type) { - case ACTION_EXCEPTION: - throw new ActionException(); - default: - throw new IllegalStateException("bad end"); + public void end(InterpretationContext ec, String name) throws ActionException { + switch (type) { + case ACTION_EXCEPTION: + throw new ActionException(); + default: + throw new IllegalStateException("bad end"); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/HelloAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/HelloAction.java index edbb06bbe1a33e77aeb778db841fb200e06b00d5..85e0027c6348cc57dd1edcb80b3005d01a7b4ce3 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/HelloAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/HelloAction.java @@ -18,26 +18,23 @@ import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - - public class HelloAction extends Action { - - static final public String PROPERTY_KEY = "name"; - - /** - * Instantiates an layout of the given class and sets its name. - * - */ - public void begin(InterpretationContext ec, String name, Attributes attributes) { - String str = "Hello "+attributes.getValue("name")+"."; - ec.getContext().putProperty(PROPERTY_KEY, str); - } - - /** - * Once the children elements are also parsed, now is the time to activate - * the appender options. - */ - public void end(InterpretationContext ec, String name) { - } + static final public String PROPERTY_KEY = "name"; + + /** + * Instantiates an layout of the given class and sets its name. + * + */ + public void begin(InterpretationContext ec, String name, Attributes attributes) { + String str = "Hello " + attributes.getValue("name") + "."; + ec.getContext().putProperty(PROPERTY_KEY, str); + } + + /** + * Once the children elements are also parsed, now is the time to activate + * the appender options. + */ + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/IncAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/IncAction.java index ba6e38ab8e31e6f0e93a9441ad6b97df077cf665..ae5f9a7b3eb961cbfaa2e96decaa5076d54e1e0f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/IncAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/IncAction.java @@ -19,38 +19,37 @@ import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.ActionException; import ch.qos.logback.core.joran.spi.InterpretationContext; - - public class IncAction extends Action { - static public int beginCount; - static public int endCount; - static public int errorCount; + static public int beginCount; + static public int endCount; + static public int errorCount; - static public void reset() { - beginCount = 0; - endCount = 0; - errorCount = 0; - } - /** - * Instantiates an layout of the given class and sets its name. - * - */ - public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - //System.out.println("IncAction Begin called"); - beginCount++; - String val = attributes.getValue("increment"); - if(!"1".equals(val)) { - errorCount++; - throw new ActionException(); + static public void reset() { + beginCount = 0; + endCount = 0; + errorCount = 0; } - } - /** - * Once the children elements are also parsed, now is the time to activate - * the appender options. - */ - public void end(InterpretationContext ec, String name) { - endCount++; - } + /** + * Instantiates an layout of the given class and sets its name. + * + */ + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + // System.out.println("IncAction Begin called"); + beginCount++; + String val = attributes.getValue("increment"); + if (!"1".equals(val)) { + errorCount++; + throw new ActionException(); + } + } + + /** + * Once the children elements are also parsed, now is the time to activate + * the appender options. + */ + public void end(InterpretationContext ec, String name) { + endCount++; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/StackAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/StackAction.java index 784637781ac13c4935a13a739481dd158e340e6f..d765a8627bc7083edca19cfd8087dc20ea87ec90 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/StackAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/StackAction.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.joran.action.ext; - import java.util.Stack; import org.xml.sax.Attributes; @@ -21,10 +20,8 @@ import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - public class StackAction extends Action { - Stack stack = new Stack(); public Stack getStack() { @@ -38,7 +35,7 @@ public class StackAction extends Action { public void end(InterpretationContext ec, String name) { } -// static public void reset() { -// stack.clear(); -// } + // static public void reset() { + // stack.clear(); + // } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/TouchAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/TouchAction.java index 77c12b0afede2e3cf99a055001c45a4c36e66980..df029ee42a3163060aad984274eaba498727152b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/TouchAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/action/ext/TouchAction.java @@ -13,35 +13,32 @@ */ package ch.qos.logback.core.joran.action.ext; - import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - - public class TouchAction extends Action { - public static final String KEY = "touched"; - - /** - * Instantiates an layout of the given class and sets its name. - * - */ - public void begin(InterpretationContext ec, String name, Attributes attributes) { - Integer i = (Integer) ec.getContext().getObject(KEY); - if(i == null) { - ec.getContext().putObject(KEY, new Integer(1)); - } else { - ec.getContext().putObject(KEY, new Integer(i.intValue()+1)); + public static final String KEY = "touched"; + + /** + * Instantiates an layout of the given class and sets its name. + * + */ + public void begin(InterpretationContext ec, String name, Attributes attributes) { + Integer i = (Integer) ec.getContext().getObject(KEY); + if (i == null) { + ec.getContext().putObject(KEY, new Integer(1)); + } else { + ec.getContext().putObject(KEY, new Integer(i.intValue() + 1)); + } } - } - /** - * Once the children elements are also parsed, now is the time to activate - * the appender options. - */ - public void end(InterpretationContext ec, String name) { - } + /** + * Once the children elements are also parsed, now is the time to activate + * the appender options. + */ + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseAndIncludeCompositionTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseAndIncludeCompositionTest.java index 920dc2629d04a1b669aed21b92d3dd57e49ffc3c..dd1d65b74b43f888e4c6e7267f68226b238b87ea 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseAndIncludeCompositionTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseAndIncludeCompositionTest.java @@ -38,58 +38,55 @@ import ch.qos.logback.core.util.StatusPrinter; public class IfThenElseAndIncludeCompositionTest { - Context context = new ContextBase(); - TrivialConfigurator tc; - int diff = RandomUtil.getPositiveInt(); - static final String CONDITIONAL_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX - + "conditional/"; + Context context = new ContextBase(); + TrivialConfigurator tc; + int diff = RandomUtil.getPositiveInt(); + static final String CONDITIONAL_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX + "conditional/"; - final static String THEN_FILE_TO_INCLUDE_KEY = "thenFileToInclude"; - final static String ELSE_FILE_TO_INCLUDE_KEY = "elseFileToInclude"; - - static final String NESTED_INCLUDE_FILE = CONDITIONAL_DIR_PREFIX+"nestedInclude.xml"; - static final String THEN_FILE_TO_INCLUDE = CONDITIONAL_DIR_PREFIX+"includedA.xml"; - static final String ELSE_FILE_TO_INCLUDE = CONDITIONAL_DIR_PREFIX+"includedB.xml"; + final static String THEN_FILE_TO_INCLUDE_KEY = "thenFileToInclude"; + final static String ELSE_FILE_TO_INCLUDE_KEY = "elseFileToInclude"; - StackAction stackAction = new StackAction(); + static final String NESTED_INCLUDE_FILE = CONDITIONAL_DIR_PREFIX + "nestedInclude.xml"; + static final String THEN_FILE_TO_INCLUDE = CONDITIONAL_DIR_PREFIX + "includedA.xml"; + static final String ELSE_FILE_TO_INCLUDE = CONDITIONAL_DIR_PREFIX + "includedB.xml"; - - @Before - public void setUp() throws Exception { - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("x"), new NOPAction()); - rulesMap.put(new ElementSelector("x/stack"), stackAction); - rulesMap.put(new ElementSelector("*/if"), new IfAction()); - rulesMap.put(new ElementSelector("*/if/then"), new ThenAction()); - rulesMap.put(new ElementSelector("*/if/then/*"), new NOPAction()); - rulesMap.put(new ElementSelector("*/if/else"), new ElseAction()); - rulesMap.put(new ElementSelector("*/if/else/*"), new NOPAction()); - rulesMap.put(new ElementSelector("x/include"), new IncludeAction()); - - tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - } + StackAction stackAction = new StackAction(); + + @Before + public void setUp() throws Exception { + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("x"), new NOPAction()); + rulesMap.put(new ElementSelector("x/stack"), stackAction); + rulesMap.put(new ElementSelector("*/if"), new IfAction()); + rulesMap.put(new ElementSelector("*/if/then"), new ThenAction()); + rulesMap.put(new ElementSelector("*/if/then/*"), new NOPAction()); + rulesMap.put(new ElementSelector("*/if/else"), new ElseAction()); + rulesMap.put(new ElementSelector("*/if/else/*"), new NOPAction()); + rulesMap.put(new ElementSelector("x/include"), new IncludeAction()); + + tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + } + + @After + public void tearDown() throws Exception { + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + context = null; + // StackAction.reset(); + } + + @Test + public void includeNestedWithinIf() throws JoranException { + context.putProperty(THEN_FILE_TO_INCLUDE_KEY, THEN_FILE_TO_INCLUDE); + context.putProperty(ELSE_FILE_TO_INCLUDE_KEY, ELSE_FILE_TO_INCLUDE); + tc.doConfigure(NESTED_INCLUDE_FILE); + verifyConfig(new String[] { "BEGIN", "e0", "IncludedB0", "e1", "END" }); + } + + void verifyConfig(String[] expected) { + Stack witness = new Stack(); + witness.addAll(Arrays.asList(expected)); + assertEquals(witness, stackAction.getStack()); + } - @After - public void tearDown() throws Exception { - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - context = null; - //StackAction.reset(); - } - - @Test - public void includeNestedWithinIf() throws JoranException { - context.putProperty(THEN_FILE_TO_INCLUDE_KEY, THEN_FILE_TO_INCLUDE); - context.putProperty(ELSE_FILE_TO_INCLUDE_KEY, ELSE_FILE_TO_INCLUDE); - tc.doConfigure(NESTED_INCLUDE_FILE); - verifyConfig(new String[] {"BEGIN", "e0", "IncludedB0", "e1", "END"}); - } - - - void verifyConfig(String[] expected) { - Stack witness = new Stack(); - witness.addAll(Arrays.asList(expected)); - assertEquals(witness, stackAction.getStack()); - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseTest.java index b7caf2930bba7e43aec30800680f53c7c8fa421d..82784ab8eed4379a34174b2598efee04d5e5e007 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/IfThenElseTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.joran.conditional; - import java.util.Arrays; import java.util.HashMap; import java.util.Stack; @@ -40,106 +39,104 @@ import static org.junit.Assert.*; public class IfThenElseTest { - Context context = new ContextBase(); - StatusChecker checker = new StatusChecker(context); - TrivialConfigurator tc; - int diff = RandomUtil.getPositiveInt(); - static final String CONDITIONAL_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX - + "conditional/"; - - String ki1 = "ki1"; - String val1 = "val1"; - String sysKey = "sysKey"; - String dynaKey = "dynaKey"; - - StackAction stackAction = new StackAction(); - - @Before - public void setUp() throws Exception { - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("x"), new NOPAction()); - rulesMap.put(new ElementSelector("x/stack"), stackAction); - rulesMap.put(new ElementSelector("x/property"), new PropertyAction()); - rulesMap.put(new ElementSelector("*/if"), new IfAction()); - rulesMap.put(new ElementSelector("*/if/then"), new ThenAction()); - rulesMap.put(new ElementSelector("*/if/then/*"), new NOPAction()); - rulesMap.put(new ElementSelector("*/if/else"), new ElseAction()); - rulesMap.put(new ElementSelector("*/if/else/*"), new NOPAction()); - - tc = new TrivialConfigurator(rulesMap); - tc.setContext(context); - } - - @After - public void tearDown() throws Exception { - StatusPrinter.printIfErrorsOccured(context); - System.clearProperty(sysKey); - } - - @Test - public void whenContextPropertyIsSet_IfThenBranchIsEvaluated() throws JoranException { - context.putProperty(ki1, val1); - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"if0.xml"); - verifyConfig(new String[] {"BEGIN", "a", "END"}); - } - - @Test - public void whenLocalPropertyIsSet_IfThenBranchIsEvaluated() throws JoranException { - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"if_localProperty.xml"); - verifyConfig(new String[] {"BEGIN", "a", "END"}); - } - - - @Test - public void whenNoPropertyIsDefined_ElseBranchIsEvaluated() throws JoranException { - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"if0.xml"); - verifyConfig(new String[] {"BEGIN", "b", "END"}); - } - - @Test - public void whenContextPropertyIsSet_IfThenBranchIsEvaluated_NO_ELSE_DEFINED() throws JoranException { - context.putProperty(ki1, val1); - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"ifWithoutElse.xml"); - verifyConfig(new String[] {"BEGIN", "a", "END"}); - } - - @Test - public void whenNoPropertyIsDefined_IfThenBranchIsNotEvaluated_NO_ELSE_DEFINED() throws JoranException { - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"ifWithoutElse.xml"); - verifyConfig(new String[] {"BEGIN", "END"}); - assertTrue(checker.isErrorFree(0)); - } - - @Test - public void nestedIf() throws JoranException { - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"nestedIf.xml"); - verifyConfig(new String[] {"BEGIN", "a", "c", "END"}); - assertTrue(checker.isErrorFree(0)); - } - - @Test - public void useNonExistenceOfSystemPropertyToDefineAContextProperty() throws JoranException { - assertNull(System.getProperty(sysKey)); - assertNull(context.getProperty(dynaKey)); - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"ifSystem.xml"); - System.out.println(dynaKey+"="+context.getProperty(dynaKey)); - assertNotNull(context.getProperty(dynaKey)); - } - - @Test - public void noContextPropertyShouldBeDefinedIfSystemPropertyExists() throws JoranException { - System.setProperty(sysKey, "a"); - assertNull(context.getProperty(dynaKey)); - System.out.println("before "+dynaKey+"="+context.getProperty(dynaKey)); - tc.doConfigure(CONDITIONAL_DIR_PREFIX+"ifSystem.xml"); - System.out.println(dynaKey+"="+context.getProperty(dynaKey)); - assertNull(context.getProperty(dynaKey)); - } - - private void verifyConfig(String[] expected) { - Stack witness = new Stack(); - witness.addAll(Arrays.asList(expected)); - assertEquals(witness, stackAction.getStack()); - } + Context context = new ContextBase(); + StatusChecker checker = new StatusChecker(context); + TrivialConfigurator tc; + int diff = RandomUtil.getPositiveInt(); + static final String CONDITIONAL_DIR_PREFIX = CoreTestConstants.JORAN_INPUT_PREFIX + "conditional/"; + + String ki1 = "ki1"; + String val1 = "val1"; + String sysKey = "sysKey"; + String dynaKey = "dynaKey"; + + StackAction stackAction = new StackAction(); + + @Before + public void setUp() throws Exception { + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("x"), new NOPAction()); + rulesMap.put(new ElementSelector("x/stack"), stackAction); + rulesMap.put(new ElementSelector("x/property"), new PropertyAction()); + rulesMap.put(new ElementSelector("*/if"), new IfAction()); + rulesMap.put(new ElementSelector("*/if/then"), new ThenAction()); + rulesMap.put(new ElementSelector("*/if/then/*"), new NOPAction()); + rulesMap.put(new ElementSelector("*/if/else"), new ElseAction()); + rulesMap.put(new ElementSelector("*/if/else/*"), new NOPAction()); + + tc = new TrivialConfigurator(rulesMap); + tc.setContext(context); + } + + @After + public void tearDown() throws Exception { + StatusPrinter.printIfErrorsOccured(context); + System.clearProperty(sysKey); + } + + @Test + public void whenContextPropertyIsSet_IfThenBranchIsEvaluated() throws JoranException { + context.putProperty(ki1, val1); + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "if0.xml"); + verifyConfig(new String[] { "BEGIN", "a", "END" }); + } + + @Test + public void whenLocalPropertyIsSet_IfThenBranchIsEvaluated() throws JoranException { + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "if_localProperty.xml"); + verifyConfig(new String[] { "BEGIN", "a", "END" }); + } + + @Test + public void whenNoPropertyIsDefined_ElseBranchIsEvaluated() throws JoranException { + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "if0.xml"); + verifyConfig(new String[] { "BEGIN", "b", "END" }); + } + + @Test + public void whenContextPropertyIsSet_IfThenBranchIsEvaluated_NO_ELSE_DEFINED() throws JoranException { + context.putProperty(ki1, val1); + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "ifWithoutElse.xml"); + verifyConfig(new String[] { "BEGIN", "a", "END" }); + } + + @Test + public void whenNoPropertyIsDefined_IfThenBranchIsNotEvaluated_NO_ELSE_DEFINED() throws JoranException { + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "ifWithoutElse.xml"); + verifyConfig(new String[] { "BEGIN", "END" }); + assertTrue(checker.isErrorFree(0)); + } + + @Test + public void nestedIf() throws JoranException { + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "nestedIf.xml"); + verifyConfig(new String[] { "BEGIN", "a", "c", "END" }); + assertTrue(checker.isErrorFree(0)); + } + + @Test + public void useNonExistenceOfSystemPropertyToDefineAContextProperty() throws JoranException { + assertNull(System.getProperty(sysKey)); + assertNull(context.getProperty(dynaKey)); + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "ifSystem.xml"); + System.out.println(dynaKey + "=" + context.getProperty(dynaKey)); + assertNotNull(context.getProperty(dynaKey)); + } + + @Test + public void noContextPropertyShouldBeDefinedIfSystemPropertyExists() throws JoranException { + System.setProperty(sysKey, "a"); + assertNull(context.getProperty(dynaKey)); + System.out.println("before " + dynaKey + "=" + context.getProperty(dynaKey)); + tc.doConfigure(CONDITIONAL_DIR_PREFIX + "ifSystem.xml"); + System.out.println(dynaKey + "=" + context.getProperty(dynaKey)); + assertNull(context.getProperty(dynaKey)); + } + + private void verifyConfig(String[] expected) { + Stack witness = new Stack(); + witness.addAll(Arrays.asList(expected)); + assertEquals(witness, stackAction.getStack()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PackageTest.java index fe209ff6ec71e67368267c4e9bb074f8de92668b..a2f99dfa4ec717be380d9221370e668030f9f297 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PackageTest.java @@ -18,8 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { PropertyEvalScriptBuilderTest.class, IfThenElseTest.class, - IfThenElseAndIncludeCompositionTest.class }) +@SuiteClasses({ PropertyEvalScriptBuilderTest.class, IfThenElseTest.class, IfThenElseAndIncludeCompositionTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilderTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilderTest.java index 392247e6dd949b01cba54cc134f51432402fa66f..3b07427b9e9fb490d7b506908fde69cb6269c827 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/conditional/PropertyEvalScriptBuilderTest.java @@ -27,96 +27,95 @@ import ch.qos.logback.core.testUtil.RandomUtil; public class PropertyEvalScriptBuilderTest { - - Context context = new ContextBase(); - InterpretationContext localPropContainer = new InterpretationContext(context, null); - PropertyEvalScriptBuilder pesb = new PropertyEvalScriptBuilder(localPropContainer); - int diff = RandomUtil.getPositiveInt(); - - String k = "ka" + diff; - String v = "va"; - String containsScript = "p(\"" + k + "\").contains(\"" + v + "\")"; - - String isNullScriptStr = "isNull(\"" + k + "\")"; - String isDefiedScriptStr = "isDefined(\"" + k + "\")"; - - @Before - public void setUp() { - context.setName("c" + diff); - pesb.setContext(context); - } - - @After - public void tearDown() { - System.clearProperty(k); - } - - - void buildAndAssertTrue(String scriptStr) throws Exception { - Condition condition = pesb.build(scriptStr); - assertNotNull(condition); - assertTrue(condition.evaluate()); - } - - void buildAndAssertFalse(String scriptStr) throws Exception { - Condition condition = pesb.build(scriptStr); - assertNotNull(condition); - assertFalse(condition.evaluate()); - } - - @Test - public void existingLocalPropertyShouldEvaluateToTrue() throws Exception { - localPropContainer.addSubstitutionProperty(k, v); - buildAndAssertTrue(containsScript); - } - - @Test - public void existingContextPropertyShouldEvaluateToTrue() throws Exception { - context.putProperty(k, v); - buildAndAssertTrue(containsScript); - } - - @Test - public void existingSystemPropertyShouldEvaluateToTrue() throws Exception { - System.setProperty(k, v); - buildAndAssertTrue(containsScript); - } - - @Test - public void isNullForExistingLocalProperty() throws Exception { - localPropContainer.addSubstitutionProperty(k, v); - buildAndAssertFalse(isNullScriptStr); - } - @Test - public void isNullForExistingContextProperty() throws Exception { - context.putProperty(k, v); - buildAndAssertFalse(isNullScriptStr); - } - @Test - public void isNullForExistingSystemProperty() throws Exception { - System.setProperty(k, v); - buildAndAssertFalse(isNullScriptStr); - } - - @Test - public void inexistentPropertyShouldEvaluateToFalse() throws Exception { - buildAndAssertFalse(containsScript); - } - - @Test - public void isNullForInexistentPropertyShouldEvaluateToTrue() throws Exception { - buildAndAssertTrue(isNullScriptStr); - } - - public void isDefinedForIExistimgtPropertyShouldEvaluateToTrue() throws Exception { - localPropContainer.addSubstitutionProperty(k, v); - buildAndAssertTrue(isDefiedScriptStr); - } - - @Test - public void isDefinedForInexistentPropertyShouldEvaluateToTrue() throws Exception { - buildAndAssertFalse(isDefiedScriptStr); - } - + Context context = new ContextBase(); + InterpretationContext localPropContainer = new InterpretationContext(context, null); + PropertyEvalScriptBuilder pesb = new PropertyEvalScriptBuilder(localPropContainer); + int diff = RandomUtil.getPositiveInt(); + + String k = "ka" + diff; + String v = "va"; + String containsScript = "p(\"" + k + "\").contains(\"" + v + "\")"; + + String isNullScriptStr = "isNull(\"" + k + "\")"; + String isDefiedScriptStr = "isDefined(\"" + k + "\")"; + + @Before + public void setUp() { + context.setName("c" + diff); + pesb.setContext(context); + } + + @After + public void tearDown() { + System.clearProperty(k); + } + + void buildAndAssertTrue(String scriptStr) throws Exception { + Condition condition = pesb.build(scriptStr); + assertNotNull(condition); + assertTrue(condition.evaluate()); + } + + void buildAndAssertFalse(String scriptStr) throws Exception { + Condition condition = pesb.build(scriptStr); + assertNotNull(condition); + assertFalse(condition.evaluate()); + } + + @Test + public void existingLocalPropertyShouldEvaluateToTrue() throws Exception { + localPropContainer.addSubstitutionProperty(k, v); + buildAndAssertTrue(containsScript); + } + + @Test + public void existingContextPropertyShouldEvaluateToTrue() throws Exception { + context.putProperty(k, v); + buildAndAssertTrue(containsScript); + } + + @Test + public void existingSystemPropertyShouldEvaluateToTrue() throws Exception { + System.setProperty(k, v); + buildAndAssertTrue(containsScript); + } + + @Test + public void isNullForExistingLocalProperty() throws Exception { + localPropContainer.addSubstitutionProperty(k, v); + buildAndAssertFalse(isNullScriptStr); + } + + @Test + public void isNullForExistingContextProperty() throws Exception { + context.putProperty(k, v); + buildAndAssertFalse(isNullScriptStr); + } + + @Test + public void isNullForExistingSystemProperty() throws Exception { + System.setProperty(k, v); + buildAndAssertFalse(isNullScriptStr); + } + + @Test + public void inexistentPropertyShouldEvaluateToFalse() throws Exception { + buildAndAssertFalse(containsScript); + } + + @Test + public void isNullForInexistentPropertyShouldEvaluateToTrue() throws Exception { + buildAndAssertTrue(isNullScriptStr); + } + + public void isDefinedForIExistimgtPropertyShouldEvaluateToTrue() throws Exception { + localPropContainer.addSubstitutionProperty(k, v); + buildAndAssertTrue(isDefiedScriptStr); + } + + @Test + public void isDefinedForInexistentPropertyShouldEvaluateToTrue() throws Exception { + buildAndAssertFalse(isDefiedScriptStr); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/event/InPlayFireTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/event/InPlayFireTest.java index 0f27905d9207434bc6ef797afc7ae106a533a6e7..e940bf0690b6068b22e9101dcd04ca946133fb24 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/event/InPlayFireTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/event/InPlayFireTest.java @@ -29,51 +29,49 @@ import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.CoreTestConstants; -public class InPlayFireTest { +public class InPlayFireTest { - Context context = new ContextBase(); - HashMap rulesMap = new HashMap(); + Context context = new ContextBase(); + HashMap rulesMap = new HashMap(); - @Test - public void testBasic() throws JoranException { - ListenAction listenAction = new ListenAction(); - - rulesMap.put(new ElementSelector("fire"), listenAction); - TrivialConfigurator gc = new TrivialConfigurator(rulesMap); + @Test + public void testBasic() throws JoranException { + ListenAction listenAction = new ListenAction(); - gc.setContext(context); - gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); - - //for(SaxEvent se: listenAction.getSeList()) { - // System.out.println(se); - //} - assertEquals(5, listenAction.getSeList().size()); - assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); - assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); - assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); - assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); - } + rulesMap.put(new ElementSelector("fire"), listenAction); + TrivialConfigurator gc = new TrivialConfigurator(rulesMap); - @Test - public void testReplay() throws JoranException { - ListenAction listenAction = new ListenAction(); - - rulesMap.put(new ElementSelector("fire"), listenAction); - TrivialConfigurator gc = new TrivialConfigurator(rulesMap); + gc.setContext(context); + gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); + + // for(SaxEvent se: listenAction.getSeList()) { + // System.out.println(se); + // } + assertEquals(5, listenAction.getSeList().size()); + assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); + assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); + assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); + assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); + } + + @Test + public void testReplay() throws JoranException { + ListenAction listenAction = new ListenAction(); + + rulesMap.put(new ElementSelector("fire"), listenAction); + TrivialConfigurator gc = new TrivialConfigurator(rulesMap); + + gc.setContext(context); + gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); + + // for(SaxEvent se: listenAction.getSeList()) { + // System.out.println(se); + // } + assertEquals(5, listenAction.getSeList().size()); + assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); + assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); + assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); + assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); + } - gc.setContext(context); - gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); - -// for(SaxEvent se: listenAction.getSeList()) { -// System.out.println(se); -// } - assertEquals(5, listenAction.getSeList().size()); - assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); - assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); - assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); - assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); - } - - - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/event/ListenAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/event/ListenAction.java index 4076e05a536ffd443d4e8b9389101d849413023a..fce55ca74561e34e8bb65358d2e45faccb81c83e 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/event/ListenAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/event/ListenAction.java @@ -24,26 +24,25 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; public class ListenAction extends Action implements InPlayListener { - List seList = new ArrayList(); + List seList = new ArrayList(); - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - ec.addInPlayListener(this); - } + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + ec.addInPlayListener(this); + } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - ec.removeInPlayListener(this); + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + ec.removeInPlayListener(this); - } + } - public void inPlay(SaxEvent event) { - seList.add(event); - } + public void inPlay(SaxEvent event) { + seList.add(event); + } - public List getSeList() { - return seList; - } + public List getSeList() { + return seList; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/event/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/event/PackageTest.java index 65e89854b5caa822e5c5e18a89595262f579ea36..5408423a4d9760024c6f8fef9520605e93c18d6d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/event/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/event/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({SaxEventRecorderTest.class, InPlayFireTest.class}) +@SuiteClasses({ SaxEventRecorderTest.class, InPlayFireTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/event/SaxEventRecorderTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/event/SaxEventRecorderTest.java index 363d2ea858d259c003319fa1f114db481d77abcc..4998f8efe71f63c99324b4999632c4be4a24e175 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/event/SaxEventRecorderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/event/SaxEventRecorderTest.java @@ -38,72 +38,68 @@ import ch.qos.logback.core.util.CoreTestConstants; */ public class SaxEventRecorderTest { - Context context = new ContextBase(); - StatusChecker statusChecker = new StatusChecker(context); - - SAXParser createParser() throws Exception { - SAXParserFactory spf = SAXParserFactory.newInstance(); - return spf.newSAXParser(); - } - - public List doTest(String filename) throws Exception { - SaxEventRecorder recorder = new SaxEventRecorder(context); - FileInputStream fis = new FileInputStream(CoreTestConstants.TEST_SRC_PREFIX - + "input/joran/"+ filename); - recorder.recordEvents(fis); - return recorder.getSaxEventList(); - - - } - - public void dump(List seList) { - for (SaxEvent se : seList) { - System.out.println(se); + Context context = new ContextBase(); + StatusChecker statusChecker = new StatusChecker(context); + + SAXParser createParser() throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + return spf.newSAXParser(); + } + + public List doTest(String filename) throws Exception { + SaxEventRecorder recorder = new SaxEventRecorder(context); + FileInputStream fis = new FileInputStream(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + filename); + recorder.recordEvents(fis); + return recorder.getSaxEventList(); + + } + + public void dump(List seList) { + for (SaxEvent se : seList) { + System.out.println(se); + } + } + + @Test + public void test1() throws Exception { + List seList = doTest("event1.xml"); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + // dump(seList); + assertEquals(11, seList.size()); + } + + @Test + public void test2() throws Exception { + List seList = doTest("ampEvent.xml"); + StatusManager sm = context.getStatusManager(); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + // dump(seList); + assertEquals(3, seList.size()); + + BodyEvent be = (BodyEvent) seList.get(1); + assertEquals("xxx & yyy", be.getText()); + } + + @Test + public void test3() throws Exception { + List seList = doTest("inc.xml"); + StatusManager sm = context.getStatusManager(); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + // dump(seList); + assertEquals(4, seList.size()); + + StartEvent se = (StartEvent) seList.get(1); + Attributes attr = se.getAttributes(); + assertNotNull(attr); + assertEquals("1", attr.getValue("increment")); + } + + @Test + public void bodyWithSpacesAndQuotes() throws Exception { + List seList = doTest("spacesAndQuotes.xml"); + assertEquals(3, seList.size()); + BodyEvent be = (BodyEvent) seList.get(1); + assertEquals("[x][x] \"xyz\"%n", be.getText()); } - } - - @Test - public void test1() throws Exception { - List seList = doTest("event1.xml"); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - //dump(seList); - assertEquals(11, seList.size()); - } - - @Test - public void test2() throws Exception { - List seList = doTest("ampEvent.xml"); - StatusManager sm = context.getStatusManager(); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - //dump(seList); - assertEquals(3, seList.size()); - - BodyEvent be = (BodyEvent) seList.get(1); - assertEquals("xxx & yyy", be.getText()); - } - - @Test - public void test3() throws Exception { - List seList = doTest("inc.xml"); - StatusManager sm = context.getStatusManager(); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - //dump(seList); - assertEquals(4, seList.size()); - - StartEvent se = (StartEvent) seList.get(1); - Attributes attr = se.getAttributes(); - assertNotNull(attr); - assertEquals("1", attr.getValue("increment")); - } - - @Test - public void bodyWithSpacesAndQuotes() throws Exception { - List seList = doTest("spacesAndQuotes.xml"); - assertEquals(3, seList.size()); - BodyEvent be = (BodyEvent) seList.get(1); - assertEquals("[x][x] \"xyz\"%n", be.getText()); - } - - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorderTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorderTest.java index d602215520681ee74760141d71b08b1b87374d47..c34c84fbd1cf7d1ea2bd2fdf6710699361284615 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/event/stax/StaxEventRecorderTest.java @@ -29,69 +29,64 @@ import static org.junit.Assert.*; public class StaxEventRecorderTest { + Context context = new ContextBase(); + StatusChecker statusChecker = new StatusChecker(context); + + public List doTest(String filename) throws Exception { + StaxEventRecorder recorder = new StaxEventRecorder(context); + FileInputStream fis = new FileInputStream(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/" + filename); + recorder.recordEvents(fis); + return recorder.getEventList(); + } - Context context = new ContextBase(); - StatusChecker statusChecker = new StatusChecker(context); - - - public List doTest(String filename) throws Exception { - StaxEventRecorder recorder = new StaxEventRecorder(context); - FileInputStream fis = new FileInputStream(CoreTestConstants.TEST_SRC_PREFIX - + "input/joran/" + filename); - recorder.recordEvents(fis); - return recorder.getEventList(); - } - - public void dump(List seList) { - for (StaxEvent se : seList) { - System.out.println(se); + public void dump(List seList) { + for (StaxEvent se : seList) { + System.out.println(se); + } } - } - @Test - public void testParsingOfXMLWithAttributesAndBodyText() throws Exception { - List seList = doTest("event1.xml"); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - //dump(seList); - assertEquals(11, seList.size()); - assertEquals("test", seList.get(0).getName()); - assertEquals("badBegin", seList.get(1).getName()); - StartEvent startEvent = (StartEvent) seList.get(7); - assertEquals("John Doe", startEvent.getAttributeByName("name").getValue()); - assertEquals("XXX&", ((BodyEvent) seList.get(8)).getText()); - } + @Test + public void testParsingOfXMLWithAttributesAndBodyText() throws Exception { + List seList = doTest("event1.xml"); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + // dump(seList); + assertEquals(11, seList.size()); + assertEquals("test", seList.get(0).getName()); + assertEquals("badBegin", seList.get(1).getName()); + StartEvent startEvent = (StartEvent) seList.get(7); + assertEquals("John Doe", startEvent.getAttributeByName("name").getValue()); + assertEquals("XXX&", ((BodyEvent) seList.get(8)).getText()); + } - @Test - public void testProcessingOfTextWithEntityCharacters() throws Exception { - List seList = doTest("ampEvent.xml"); - StatusManager sm = context.getStatusManager(); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - //dump(seList); - assertEquals(3, seList.size()); + @Test + public void testProcessingOfTextWithEntityCharacters() throws Exception { + List seList = doTest("ampEvent.xml"); + StatusManager sm = context.getStatusManager(); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + // dump(seList); + assertEquals(3, seList.size()); - BodyEvent be = (BodyEvent) seList.get(1); - assertEquals("xxx & yyy", be.getText()); - } + BodyEvent be = (BodyEvent) seList.get(1); + assertEquals("xxx & yyy", be.getText()); + } - @Test - public void testAttributeProcessing() throws Exception { - List seList = doTest("inc.xml"); - StatusManager sm = context.getStatusManager(); - assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); - assertEquals(4, seList.size()); - StartEvent se = (StartEvent) seList.get(1); - Attribute attr = se.getAttributeByName("increment"); - assertNotNull(attr); - assertEquals("1", attr.getValue()); - } + @Test + public void testAttributeProcessing() throws Exception { + List seList = doTest("inc.xml"); + StatusManager sm = context.getStatusManager(); + assertTrue(statusChecker.getHighestLevel(0) == Status.INFO); + assertEquals(4, seList.size()); + StartEvent se = (StartEvent) seList.get(1); + Attribute attr = se.getAttributeByName("increment"); + assertNotNull(attr); + assertEquals("1", attr.getValue()); + } - @Test - public void bodyWithSpacesAndQuotes() throws Exception { - List seList = doTest("spacesAndQuotes.xml"); - assertEquals(3, seList.size()); - BodyEvent be = (BodyEvent) seList.get(1); - assertEquals("[x][x] \"xyz\"%n", be.getText()); - } + @Test + public void bodyWithSpacesAndQuotes() throws Exception { + List seList = doTest("spacesAndQuotes.xml"); + assertEquals(3, seList.size()); + BodyEvent be = (BodyEvent) seList.get(1); + assertEquals("[x][x] \"xyz\"%n", be.getText()); + } } - - diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Cake.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Cake.java index 50128fdfed1409aa10d92929eb732955dc2f6e07..d8cd7a6f9e1ef685f41b6129cec1908e300ec7aa 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Cake.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Cake.java @@ -15,21 +15,23 @@ package ch.qos.logback.core.joran.implicitAction; public class Cake { - String type; - int code; - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public int getCode() { - return code; - } - public void setCode(int code) { - this.code = code; - } - - + String type; + int code; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Fruit.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Fruit.java index 6f442a2f6dd413f9ff45e2c8c1dac3e17b414e90..7c1a5803e9da7c952f136086ef4a591c57b2693b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Fruit.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/Fruit.java @@ -18,23 +18,23 @@ import java.util.List; public class Fruit { - String name; - List textList = new ArrayList(); - List cakeList = new ArrayList(); - - public void setName(String n) { - this.name = n; - } + String name; + List textList = new ArrayList(); + List cakeList = new ArrayList(); - public String getName() { - return name; - } - - public void addText(String s) { - textList.add(s); - } - - public void addCake(Cake c) { - cakeList.add(c); - } + public void setName(String n) { + this.name = n; + } + + public String getName() { + return name; + } + + public void addText(String s) { + textList.add(s); + } + + public void addCake(Cake c) { + cakeList.add(c); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContext.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContext.java index 9478e8e8cabed13128be008149a6aa99a73d016b..d8b028564fd83e97d99ea60a02a4aff94a5f6398 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContext.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContext.java @@ -20,17 +20,17 @@ import ch.qos.logback.core.ContextBase; public class FruitContext extends ContextBase { - List fruitList = new ArrayList(); - - public void addFruit(Fruit fs) { - fruitList.add(fs); - } + List fruitList = new ArrayList(); - public List getFruitList() { - return fruitList; - } + public void addFruit(Fruit fs) { + fruitList.add(fs); + } - public void setFruitShellList(List fruitList) { - this.fruitList = fruitList; - } + public List getFruitList() { + return fruitList; + } + + public void setFruitShellList(List fruitList) { + this.fruitList = fruitList; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContextAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContextAction.java index 074a2ec883adc22adb0ea5e0f3205c320f52bc71..1b061c8f1d9439d40a6edb2876ddffe51bfa7ad0 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContextAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/FruitContextAction.java @@ -21,44 +21,36 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; public class FruitContextAction extends Action { - private boolean inError = false; + private boolean inError = false; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - inError = false; - - try { - ec.pushObject(context); - } catch (Exception oops) { - inError = true; - addError( - "Could not push context", oops); - throw new ActionException(oops); - } - } + inError = false; - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - if (inError) { - return; + try { + ec.pushObject(context); + } catch (Exception oops) { + inError = true; + addError("Could not push context", oops); + throw new ActionException(oops); + } } - Object o = ec.peekObject(); + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + if (inError) { + return; + } + + Object o = ec.peekObject(); - if (o != context) { - addWarn( - "The object at the of the stack is not the context named [" - + context.getName() + "] pushed earlier."); - } else { - addInfo( - "Popping context named [" + context.getName() - + "] from the object stack"); - ec.popObject(); + if (o != context) { + addWarn("The object at the of the stack is not the context named [" + context.getName() + "] pushed earlier."); + } else { + addInfo("Popping context named [" + context.getName() + "] from the object stack"); + ec.popObject(); + } } - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/ImplicitActionTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/ImplicitActionTest.java index 711243f5a4785278fc8543b5662fdcb5e812c05b..689df1c906ee975a90dae54aea4dc51c843a35bf 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/ImplicitActionTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/ImplicitActionTest.java @@ -30,97 +30,92 @@ import ch.qos.logback.core.util.StatusPrinter; public class ImplicitActionTest { - static final String IMPLCIT_DIR = CoreTestConstants.TEST_SRC_PREFIX - + "input/joran/implicitAction/"; - - FruitContext fruitContext = new FruitContext(); - SimpleConfigurator simpleConfigurator; - - @Before - public void setUp() throws Exception { - fruitContext.setName("fruits"); - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("/context/"), new FruitContextAction()); - simpleConfigurator = new SimpleConfigurator(rulesMap); - simpleConfigurator.setContext(fruitContext); - } - - void verifyFruit() { - List fList = fruitContext.getFruitList(); - assertNotNull(fList); - assertEquals(1, fList.size()); - - Fruit f0 = fList.get(0); - assertEquals("blue", f0.getName()); - assertEquals(2, f0.textList.size()); - assertEquals("hello", f0.textList.get(0)); - assertEquals("world", f0.textList.get(1)); - } - - @Test - public void nestedComplex() throws Exception { - try { - simpleConfigurator.doConfigure(IMPLCIT_DIR + "nestedComplex.xml"); - verifyFruit(); - - } catch (Exception je) { - StatusPrinter.print(fruitContext); - throw je; + static final String IMPLCIT_DIR = CoreTestConstants.TEST_SRC_PREFIX + "input/joran/implicitAction/"; + + FruitContext fruitContext = new FruitContext(); + SimpleConfigurator simpleConfigurator; + + @Before + public void setUp() throws Exception { + fruitContext.setName("fruits"); + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("/context/"), new FruitContextAction()); + simpleConfigurator = new SimpleConfigurator(rulesMap); + simpleConfigurator.setContext(fruitContext); } - } - @Test - public void nestedComplexWithoutClassAtrribute() throws Exception { - try { - simpleConfigurator.doConfigure(IMPLCIT_DIR - + "nestedComplexWithoutClassAtrribute.xml"); + void verifyFruit() { + List fList = fruitContext.getFruitList(); + assertNotNull(fList); + assertEquals(1, fList.size()); - verifyFruit(); + Fruit f0 = fList.get(0); + assertEquals("blue", f0.getName()); + assertEquals(2, f0.textList.size()); + assertEquals("hello", f0.textList.get(0)); + assertEquals("world", f0.textList.get(1)); + } + + @Test + public void nestedComplex() throws Exception { + try { + simpleConfigurator.doConfigure(IMPLCIT_DIR + "nestedComplex.xml"); + verifyFruit(); - } catch (Exception je) { - StatusPrinter.print(fruitContext); - throw je; + } catch (Exception je) { + StatusPrinter.print(fruitContext); + throw je; + } } - } - - - void verifyFruitList() { - List fList = fruitContext.getFruitList(); - assertNotNull(fList); - assertEquals(1, fList.size()); - - Fruit f0 = fList.get(0); - assertEquals(2, f0.cakeList.size()); - - Cake cakeA = f0.cakeList.get(0); - assertEquals("A", cakeA.getType()); - - Cake cakeB = f0.cakeList.get(1); - assertEquals("B", cakeB.getType()); - } - @Test - public void nestedComplexCollection() throws Exception { - try { - simpleConfigurator.doConfigure(IMPLCIT_DIR - + "nestedComplexCollection.xml"); - verifyFruitList(); - } catch (Exception je) { - StatusPrinter.print(fruitContext); - throw je; + + @Test + public void nestedComplexWithoutClassAtrribute() throws Exception { + try { + simpleConfigurator.doConfigure(IMPLCIT_DIR + "nestedComplexWithoutClassAtrribute.xml"); + + verifyFruit(); + + } catch (Exception je) { + StatusPrinter.print(fruitContext); + throw je; + } } - } - - - @Test - public void nestedComplexCollectionWithoutClassAtrribute() throws Exception { - try { - simpleConfigurator.doConfigure(IMPLCIT_DIR - + "nestedComplexCollectionWithoutClassAtrribute.xml"); - verifyFruitList(); - } catch (Exception je) { - StatusPrinter.print(fruitContext); - throw je; + + void verifyFruitList() { + List fList = fruitContext.getFruitList(); + assertNotNull(fList); + assertEquals(1, fList.size()); + + Fruit f0 = fList.get(0); + assertEquals(2, f0.cakeList.size()); + + Cake cakeA = f0.cakeList.get(0); + assertEquals("A", cakeA.getType()); + + Cake cakeB = f0.cakeList.get(1); + assertEquals("B", cakeB.getType()); + } + + @Test + public void nestedComplexCollection() throws Exception { + try { + simpleConfigurator.doConfigure(IMPLCIT_DIR + "nestedComplexCollection.xml"); + verifyFruitList(); + } catch (Exception je) { + StatusPrinter.print(fruitContext); + throw je; + } + } + + @Test + public void nestedComplexCollectionWithoutClassAtrribute() throws Exception { + try { + simpleConfigurator.doConfigure(IMPLCIT_DIR + "nestedComplexCollectionWithoutClassAtrribute.xml"); + verifyFruitList(); + } catch (Exception je) { + StatusPrinter.print(fruitContext); + throw je; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/PackageTest.java index c2ae44273e7bcb6de3a6e4c24374ee84d46cfcc1..ced90551f99d568438385c54b5ec7069c4670fcb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/implicitAction/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ImplicitActionTest.class}) +@SuiteClasses({ ImplicitActionTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/Fruit.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/Fruit.java index cb042fabbd17233d0048cd160265167bd760c64d..ce5130634af87b279f5b30da9244a904f1fdfbf4 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/Fruit.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/Fruit.java @@ -18,29 +18,29 @@ import java.util.List; public class Fruit { - String name; - List textList = new ArrayList(); - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String toString() { - final String TAB = " "; - - StringBuilder retValue = new StringBuilder(); - - retValue.append("xFruit ( ").append("name = ").append(this.name).append(TAB).append(" )"); - - return retValue.toString(); - } - - public void addText(String s) { - textList.add(s); - } - + String name; + List textList = new ArrayList(); + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public String toString() { + final String TAB = " "; + + StringBuilder retValue = new StringBuilder(); + + retValue.append("xFruit ( ").append("name = ").append(this.name).append(TAB).append(" )"); + + return retValue.toString(); + } + + public void addText(String s) { + textList.add(s); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurationTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurationTest.java index 6eac7da134b60c70f05415a02bc8286c8792f866..cdd3908acd2c648d4ccdcf2168451ed30cc2fa45 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurationTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurationTest.java @@ -32,83 +32,80 @@ import ch.qos.logback.core.util.StatusPrinter; /** * The Fruit* code is intended to test Joran's replay capability * */ -public class FruitConfigurationTest { +public class FruitConfigurationTest { - FruitContext fruitContext = new FruitContext(); + FruitContext fruitContext = new FruitContext(); - public List doFirstPart(String filename) throws Exception { + public List doFirstPart(String filename) throws Exception { - try { - HashMap rulesMap = new HashMap(); - rulesMap.put(new ElementSelector("group/fruitShell"), new FruitShellAction()); - rulesMap.put(new ElementSelector("group/fruitShell/fruit"), - new FruitFactoryAction()); - rulesMap.put(new ElementSelector("group/fruitShell/fruit/*"), new NOPAction()); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(rulesMap); + try { + HashMap rulesMap = new HashMap(); + rulesMap.put(new ElementSelector("group/fruitShell"), new FruitShellAction()); + rulesMap.put(new ElementSelector("group/fruitShell/fruit"), new FruitFactoryAction()); + rulesMap.put(new ElementSelector("group/fruitShell/fruit/*"), new NOPAction()); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(rulesMap); - simpleConfigurator.setContext(fruitContext); + simpleConfigurator.setContext(fruitContext); - simpleConfigurator.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/replay/" - + filename); + simpleConfigurator.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/replay/" + filename); - return fruitContext.getFruitShellList(); - } catch (Exception je) { - StatusPrinter.print(fruitContext); - throw je; + return fruitContext.getFruitShellList(); + } catch (Exception je) { + StatusPrinter.print(fruitContext); + throw je; + } + } + + @Test + public void fruit1() throws Exception { + List fsList = doFirstPart("fruit1.xml"); + assertNotNull(fsList); + assertEquals(1, fsList.size()); + + FruitShell fs0 = fsList.get(0); + assertNotNull(fs0); + assertEquals("fs0", fs0.getName()); + Fruit fruit0 = fs0.fruitFactory.buildFruit(); + assertTrue(fruit0 instanceof Fruit); + assertEquals("blue", fruit0.getName()); + } + + @Test + public void fruit2() throws Exception { + List fsList = doFirstPart("fruit2.xml"); + assertNotNull(fsList); + assertEquals(2, fsList.size()); + + FruitShell fs0 = fsList.get(0); + assertNotNull(fs0); + assertEquals("fs0", fs0.getName()); + Fruit fruit0 = fs0.fruitFactory.buildFruit(); + assertTrue(fruit0 instanceof Fruit); + assertEquals("blue", fruit0.getName()); + + FruitShell fs1 = fsList.get(1); + assertNotNull(fs1); + assertEquals("fs1", fs1.getName()); + Fruit fruit1 = fs1.fruitFactory.buildFruit(); + assertTrue(fruit1 instanceof WeightytFruit); + assertEquals("orange", fruit1.getName()); + assertEquals(1.2, ((WeightytFruit) fruit1).getWeight(), 0.01); + } + + @Test + public void withSubst() throws Exception { + List fsList = doFirstPart("fruitWithSubst.xml"); + assertNotNull(fsList); + assertEquals(1, fsList.size()); + + FruitShell fs0 = fsList.get(0); + assertNotNull(fs0); + assertEquals("fs0", fs0.getName()); + int oldCount = FruitFactory.count; + Fruit fruit0 = fs0.fruitFactory.buildFruit(); + assertTrue(fruit0 instanceof WeightytFruit); + assertEquals("orange-" + oldCount, fruit0.getName()); + assertEquals(1.2, ((WeightytFruit) fruit0).getWeight(), 0.01); } - } - - @Test - public void fruit1() throws Exception { - List fsList = doFirstPart("fruit1.xml"); - assertNotNull(fsList); - assertEquals(1, fsList.size()); - - FruitShell fs0 = fsList.get(0); - assertNotNull(fs0); - assertEquals("fs0", fs0.getName()); - Fruit fruit0 = fs0.fruitFactory.buildFruit(); - assertTrue(fruit0 instanceof Fruit); - assertEquals("blue", fruit0.getName()); - } - - - @Test - public void fruit2() throws Exception { - List fsList = doFirstPart("fruit2.xml"); - assertNotNull(fsList); - assertEquals(2, fsList.size()); - - FruitShell fs0 = fsList.get(0); - assertNotNull(fs0); - assertEquals("fs0", fs0.getName()); - Fruit fruit0 = fs0.fruitFactory.buildFruit(); - assertTrue(fruit0 instanceof Fruit); - assertEquals("blue", fruit0.getName()); - - FruitShell fs1 = fsList.get(1); - assertNotNull(fs1); - assertEquals("fs1", fs1.getName()); - Fruit fruit1 = fs1.fruitFactory.buildFruit(); - assertTrue(fruit1 instanceof WeightytFruit); - assertEquals("orange", fruit1.getName()); - assertEquals(1.2, ((WeightytFruit) fruit1).getWeight(), 0.01); - } - - @Test - public void withSubst() throws Exception { - List fsList = doFirstPart("fruitWithSubst.xml"); - assertNotNull(fsList); - assertEquals(1, fsList.size()); - - FruitShell fs0 = fsList.get(0); - assertNotNull(fs0); - assertEquals("fs0", fs0.getName()); - int oldCount = FruitFactory.count; - Fruit fruit0 = fs0.fruitFactory.buildFruit(); - assertTrue(fruit0 instanceof WeightytFruit); - assertEquals("orange-" + oldCount, fruit0.getName()); - assertEquals(1.2, ((WeightytFruit) fruit0).getWeight(), 0.01); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurator.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurator.java index de470bbb8b8e86869abde403ebccea94e6f767c4..5ebc2deffffcadea159f2546e2bf27f2cbeb9ae9 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurator.java @@ -28,35 +28,34 @@ import ch.qos.logback.core.joran.spi.RuleStore; public class FruitConfigurator extends GenericConfigurator { - FruitFactory ff; - public FruitConfigurator(FruitFactory ff) { - this.ff = ff; - } - - @Override - final public void doConfigure(final List eventList) - throws JoranException { - buildInterpreter(); - interpreter.getInterpretationContext().pushObject(ff); - EventPlayer player = new EventPlayer(interpreter); - player.play(eventList); - } - - @Override - protected void addImplicitRules(Interpreter interpreter) { - NestedComplexPropertyIA nestedIA = new NestedComplexPropertyIA(); - nestedIA.setContext(context); - interpreter.addImplicitAction(nestedIA); - - NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); - nestedIA.setContext(context); - interpreter.addImplicitAction(nestedSimpleIA); - } - - - @Override - protected void addInstanceRules(RuleStore rs) { - rs.addRule(new ElementSelector("fruitShell"), new NOPAction()); - } + FruitFactory ff; + + public FruitConfigurator(FruitFactory ff) { + this.ff = ff; + } + + @Override + final public void doConfigure(final List eventList) throws JoranException { + buildInterpreter(); + interpreter.getInterpretationContext().pushObject(ff); + EventPlayer player = new EventPlayer(interpreter); + player.play(eventList); + } + + @Override + protected void addImplicitRules(Interpreter interpreter) { + NestedComplexPropertyIA nestedIA = new NestedComplexPropertyIA(); + nestedIA.setContext(context); + interpreter.addImplicitAction(nestedIA); + + NestedBasicPropertyIA nestedSimpleIA = new NestedBasicPropertyIA(); + nestedIA.setContext(context); + interpreter.addImplicitAction(nestedSimpleIA); + } + + @Override + protected void addInstanceRules(RuleStore rs) { + rs.addRule(new ElementSelector("fruitShell"), new NOPAction()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitContext.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitContext.java index c02c4fc625077ef3f80eb17700346636114d85ec..ba2af6c5a952957bdec274ca48ac4ff4437a86b8 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitContext.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitContext.java @@ -20,17 +20,17 @@ import ch.qos.logback.core.ContextBase; public class FruitContext extends ContextBase { - List fruitShellList = new ArrayList(); - - public void addFruitShell(FruitShell fs) { - fruitShellList.add(fs); - } + List fruitShellList = new ArrayList(); - public List getFruitShellList() { - return fruitShellList; - } + public void addFruitShell(FruitShell fs) { + fruitShellList.add(fs); + } - public void setFruitShellList(List fruitShellList) { - this.fruitShellList = fruitShellList; - } + public List getFruitShellList() { + return fruitShellList; + } + + public void setFruitShellList(List fruitShellList) { + this.fruitShellList = fruitShellList; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactory.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactory.java index f45f5d7f6adc8994008792d74dd27b2baa63a92c..e3ad7e5884bcc2bda90f170244ffe643e15caf32 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactory.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactory.java @@ -22,48 +22,48 @@ import ch.qos.logback.core.joran.spi.JoranException; public class FruitFactory { - static int count = 0; - - private List eventList; - Fruit fruit; - - public void setFruit(Fruit fruit) { - this.fruit = fruit; - } + static int count = 0; - public Fruit buildFruit() { - - Context context = new ContextBase(); - this.fruit = null; - context.putProperty("fruitKey", "orange-"+count); - // for next round - count++; - FruitConfigurator fruitConfigurator = new FruitConfigurator(this); - fruitConfigurator.setContext(context); - try { - fruitConfigurator.doConfigure(eventList); - } catch(JoranException je) { - je.printStackTrace(); - } - return fruit; - } + private List eventList; + Fruit fruit; - public String toString() { - final String TAB = " "; + public void setFruit(Fruit fruit) { + this.fruit = fruit; + } - StringBuilder retValue = new StringBuilder(); + public Fruit buildFruit() { - retValue.append("FruitFactory ( "); - if (eventList != null && eventList.size() > 0) { - retValue.append("event1 = ").append(eventList.get(0)).append(TAB); + Context context = new ContextBase(); + this.fruit = null; + context.putProperty("fruitKey", "orange-" + count); + // for next round + count++; + FruitConfigurator fruitConfigurator = new FruitConfigurator(this); + fruitConfigurator.setContext(context); + try { + fruitConfigurator.doConfigure(eventList); + } catch (JoranException je) { + je.printStackTrace(); + } + return fruit; } - retValue.append(" )"); - return retValue.toString(); - } + public String toString() { + final String TAB = " "; + + StringBuilder retValue = new StringBuilder(); + + retValue.append("FruitFactory ( "); + if (eventList != null && eventList.size() > 0) { + retValue.append("event1 = ").append(eventList.get(0)).append(TAB); + } + retValue.append(" )"); - public void setEventList(List eventList) { - this.eventList = eventList; - } + return retValue.toString(); + } + + public void setEventList(List eventList) { + this.eventList = eventList; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactoryAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactoryAction.java index 40205c983731746ca4348bdc392e5ba2a03763f4..1680aa0f93541c35394b072f2e3316c56faf7e76 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactoryAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitFactoryAction.java @@ -26,33 +26,32 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; public class FruitFactoryAction extends Action implements InPlayListener { - List seList = new ArrayList(); - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - ec.addInPlayListener(this); - } - - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - ec.removeInPlayListener(this); - - Object o = ec.peekObject(); - if(o instanceof FruitShell) { - FruitShell fs = (FruitShell) o; - FruitFactory fruitFactory = new FruitFactory(); - fruitFactory.setEventList(new ArrayList(seList)); - fs.setFruitFactory(fruitFactory); + List seList = new ArrayList(); + + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { + ec.addInPlayListener(this); } - } - public void inPlay(SaxEvent event) { - seList.add(event); - } + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + ec.removeInPlayListener(this); + + Object o = ec.peekObject(); + if (o instanceof FruitShell) { + FruitShell fs = (FruitShell) o; + FruitFactory fruitFactory = new FruitFactory(); + fruitFactory.setEventList(new ArrayList(seList)); + fs.setFruitFactory(fruitFactory); + } + } - public List getSeList() { - return seList; - } + public void inPlay(SaxEvent event) { + seList.add(event); + } + + public List getSeList() { + return seList; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShell.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShell.java index b1710cb4d59c16758984cd6d6250d3b9675b401e..ec2a2dcbc39ee98e45d23b716b84a4af419daed2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShell.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShell.java @@ -17,46 +17,42 @@ import ch.qos.logback.core.spi.ContextAwareBase; public class FruitShell extends ContextAwareBase { - FruitFactory fruitFactory; - String name; - - public void setFruitFactory(FruitFactory fruitFactory) { - this.fruitFactory = fruitFactory; - } - - void testFruit() { - - Fruit fruit = fruitFactory.buildFruit(); - System.out.println(fruit); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - /** - * Constructs a String with all attributes - * in name = value format. - * - * @return a String representation - * of this object. - */ - public String toString() - { - final String TAB = " "; - - String retValue = ""; - - retValue = "FruitShell ( " - + "fruitFactory = " + this.fruitFactory + TAB - + "name = " + this.name + TAB - + " )"; - - return retValue; - } - + FruitFactory fruitFactory; + String name; + + public void setFruitFactory(FruitFactory fruitFactory) { + this.fruitFactory = fruitFactory; + } + + void testFruit() { + + Fruit fruit = fruitFactory.buildFruit(); + System.out.println(fruit); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + /** + * Constructs a String with all attributes + * in name = value format. + * + * @return a String representation + * of this object. + */ + public String toString() { + final String TAB = " "; + + String retValue = ""; + + retValue = "FruitShell ( " + "fruitFactory = " + this.fruitFactory + TAB + "name = " + this.name + TAB + " )"; + + return retValue; + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShellAction.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShellAction.java index 92b8ccd83aad89112e6b23ee37378162e7fdd8da..33d2eed9ec286a9e33a7f3e80dbd4553cfa9c73f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShellAction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitShellAction.java @@ -25,63 +25,53 @@ import ch.qos.logback.core.util.OptionHelper; * */ public class FruitShellAction extends Action { - FruitShell fruitShell; - private boolean inError = false; + FruitShell fruitShell; + private boolean inError = false; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { + @Override + public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - // We are just beginning, reset variables - fruitShell = new FruitShell(); - inError = false; - - try { + // We are just beginning, reset variables + fruitShell = new FruitShell(); + inError = false; + try { - fruitShell.setContext(context); + fruitShell.setContext(context); - String shellName = attributes.getValue(NAME_ATTRIBUTE); + String shellName = attributes.getValue(NAME_ATTRIBUTE); - if (OptionHelper.isEmpty(shellName)) { - addWarn( - "No appender name given for fruitShell]."); - } else { - fruitShell.setName(shellName); - addInfo("FruitShell named as [" + shellName + "]"); - } + if (OptionHelper.isEmpty(shellName)) { + addWarn("No appender name given for fruitShell]."); + } else { + fruitShell.setName(shellName); + addInfo("FruitShell named as [" + shellName + "]"); + } - ec.pushObject(fruitShell); - } catch (Exception oops) { - inError = true; - addError( - "Could not create an FruitShell", oops); - throw new ActionException(oops); + ec.pushObject(fruitShell); + } catch (Exception oops) { + inError = true; + addError("Could not create an FruitShell", oops); + throw new ActionException(oops); + } } - } - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - if (inError) { - return; - } + @Override + public void end(InterpretationContext ec, String name) throws ActionException { + if (inError) { + return; + } - Object o = ec.peekObject(); + Object o = ec.peekObject(); - if (o != fruitShell) { - addWarn( - "The object at the of the stack is not the fruitShell named [" - + fruitShell.getName() + "] pushed earlier."); - } else { - addInfo( - "Popping fruitSHell named [" + fruitShell.getName() - + "] from the object stack"); - ec.popObject(); - FruitContext fruitContext = (FruitContext) ec.getContext(); - fruitContext.addFruitShell(fruitShell); + if (o != fruitShell) { + addWarn("The object at the of the stack is not the fruitShell named [" + fruitShell.getName() + "] pushed earlier."); + } else { + addInfo("Popping fruitSHell named [" + fruitShell.getName() + "] from the object stack"); + ec.popObject(); + FruitContext fruitContext = (FruitContext) ec.getContext(); + fruitContext.addFruitShell(fruitShell); + } } - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/PackageTest.java index d6f94bd5a73525c743ca76c2e69ef154fc87421d..a9def49e09f6306f94fabe85294ef665182e1050 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/PackageTest.java @@ -18,7 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({FruitConfigurationTest.class}) +@SuiteClasses({ FruitConfigurationTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/WeightytFruit.java b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/WeightytFruit.java index e4be59675ef071d1a35f76e09ed335237ac2c829..da5a967773410a892c37fc0777eddc7c384c7ebd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/replay/WeightytFruit.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/replay/WeightytFruit.java @@ -15,15 +15,14 @@ package ch.qos.logback.core.joran.replay; public class WeightytFruit extends Fruit { - double weight; + double weight; - public double getWeight() { - return weight; - } + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } - public void setWeight(double weight) { - this.weight = weight; - } - - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinator.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinator.java index e9829049773e4f3dfbb3282ffeecdbd9c737e7c8..f3c1687ae6d54821d3163a6ec2f387d5c8ede146 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinator.java @@ -18,84 +18,83 @@ import java.util.List; public class CaseCombinator { + List combinations(String in) { + int length = in.length(); + List permutationsList = new ArrayList(); - List combinations(String in) { - int length = in.length(); - List permutationsList = new ArrayList(); + int totalCombinations = computeTotalNumerOfCombinations(in, length); - int totalCombinations = computeTotalNumerOfCombinations(in, length); - - for (int j = 0; j < totalCombinations; j++) { - StringBuilder newCombination = new StringBuilder(); - int pos = 0; - for (int i = 0; i < length; i++) { - char c = in.charAt(i); - if (isEnglishLetter(c)) { - c = permute(c, j, pos); - pos++; + for (int j = 0; j < totalCombinations; j++) { + StringBuilder newCombination = new StringBuilder(); + int pos = 0; + for (int i = 0; i < length; i++) { + char c = in.charAt(i); + if (isEnglishLetter(c)) { + c = permute(c, j, pos); + pos++; + } + newCombination.append(c); + } + permutationsList.add(newCombination.toString()); } - newCombination.append(c); - } - permutationsList.add(newCombination.toString()); - } - return permutationsList; - - } - - private char permute(char c, int permutation, int position) { - int mask = 1 << position; - boolean shouldBeInUpperCase = (permutation & mask) != 0; - boolean isEffectivelyUpperCase = isUpperCase(c); - if (shouldBeInUpperCase && !isEffectivelyUpperCase) - return toUpperCase(c); - if (!shouldBeInUpperCase && isEffectivelyUpperCase) - return toLowerCase(c); - return c; - } + return permutationsList; - private int computeTotalNumerOfCombinations(String in, int length) { - int count = 0; - for (int i = 0; i < length; i++) { - char c = in.charAt(i); - if (isEnglishLetter(c)) - count++; } - // return 2^count (2 to the power of count) - return (1 << count); - } - private char toUpperCase(char c) { - if ('A' <= c && c <= 'Z') { - return c; + private char permute(char c, int permutation, int position) { + int mask = 1 << position; + boolean shouldBeInUpperCase = (permutation & mask) != 0; + boolean isEffectivelyUpperCase = isUpperCase(c); + if (shouldBeInUpperCase && !isEffectivelyUpperCase) + return toUpperCase(c); + if (!shouldBeInUpperCase && isEffectivelyUpperCase) + return toLowerCase(c); + return c; } - if ('a' <= c && c <= 'z') { - return (char) ((int) c + 'A' - 'a'); + + private int computeTotalNumerOfCombinations(String in, int length) { + int count = 0; + for (int i = 0; i < length; i++) { + char c = in.charAt(i); + if (isEnglishLetter(c)) + count++; + } + // return 2^count (2 to the power of count) + return (1 << count); } - // code should never reach this point - return c; - } - private char toLowerCase(char c) { - if ('a' <= c && c <= 'z') { - return c; + private char toUpperCase(char c) { + if ('A' <= c && c <= 'Z') { + return c; + } + if ('a' <= c && c <= 'z') { + return (char) ((int) c + 'A' - 'a'); + } + // code should never reach this point + return c; } - if ('A' <= c && c <= 'Z') { - return (char) ((int) c + 'a' - 'A'); + + private char toLowerCase(char c) { + if ('a' <= c && c <= 'z') { + return c; + } + if ('A' <= c && c <= 'Z') { + return (char) ((int) c + 'a' - 'A'); + } + // code should never reach this point + return c; } - // code should never reach this point - return c; - } - private boolean isEnglishLetter(char c) { - if ('a' <= c && c <= 'z') - return true; + private boolean isEnglishLetter(char c) { + if ('a' <= c && c <= 'z') + return true; - if ('A' <= c && c <= 'Z') - return true; - return false; - } + if ('A' <= c && c <= 'Z') + return true; + return false; + } - private boolean isUpperCase(char c) { - return ('A' <= c && c <= 'Z'); - } + private boolean isUpperCase(char c) { + return ('A' <= c && c <= 'Z'); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinatorTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinatorTest.java index 7671e40447b8827e450334f399ed6615aee448ad..b548d902ea8df904c7f5e2622aac671c53219ef7 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinatorTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/CaseCombinatorTest.java @@ -22,32 +22,30 @@ import java.util.Set; import org.junit.Test; - public class CaseCombinatorTest { - CaseCombinator p = new CaseCombinator(); - - - @Test - public void smoke() { CaseCombinator p = new CaseCombinator(); - - List result = p.combinations("a-B="); - - List witness = new ArrayList(); - witness.add("a-b="); - witness.add("A-b="); - witness.add("a-B="); - witness.add("A-B="); - assertEquals(witness, result); - } - - @Test - public void other() { - List result = p.combinations("aBCd"); - assertEquals(16, result.size()); - Set witness = new HashSet(result); - // check that there are no duplicates - assertEquals(16, witness.size()); - } + + @Test + public void smoke() { + CaseCombinator p = new CaseCombinator(); + + List result = p.combinations("a-B="); + + List witness = new ArrayList(); + witness.add("a-b="); + witness.add("A-b="); + witness.add("a-B="); + witness.add("A-B="); + assertEquals(witness, result); + } + + @Test + public void other() { + List result = p.combinations("aBCd"); + assertEquals(16, result.size()); + Set witness = new HashSet(result); + // check that there are no duplicates + assertEquals(16, witness.size()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ConfigurationWatchListTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ConfigurationWatchListTest.java index d5400e47249d8924ec33abe466490b48f9671b40..2e95d3257296047551383190241d1e3524ff81b2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ConfigurationWatchListTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ConfigurationWatchListTest.java @@ -26,13 +26,13 @@ import static org.junit.Assert.assertEquals; */ public class ConfigurationWatchListTest { - @Test - // See http://jira.qos.ch/browse/LBCORE-119 - public void fileToURLAndBack() throws MalformedURLException { - File file = new File("a b.xml"); - URL url = file.toURI().toURL(); - ConfigurationWatchList cwl = new ConfigurationWatchList(); - File back = cwl.convertToFile(url); - assertEquals(file.getName(), back.getName()); - } + @Test + // See http://jira.qos.ch/browse/LBCORE-119 + public void fileToURLAndBack() throws MalformedURLException { + File file = new File("a b.xml"); + URL url = file.toURI().toURL(); + ConfigurationWatchList cwl = new ConfigurationWatchList(); + File back = cwl.convertToFile(url); + assertEquals(file.getName(), back.getName()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistryTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistryTest.java index a5f590da02e92a3827245a5242c4aec1854c0621..3dc115fe760ea0b6a5d610f3ddb0e07d848879bc 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistryTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DefaultNestedComponentRegistryTest.java @@ -26,29 +26,29 @@ import ch.qos.logback.core.joran.util.House; public class DefaultNestedComponentRegistryTest { - DefaultNestedComponentRegistry registry = new DefaultNestedComponentRegistry(); - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void smoke() { - String propertyName = "window"; - registry.add(House.class, propertyName, Window.class); - Class result = registry.findDefaultComponentType(House.class, propertyName); - assertEquals(Window.class, result); - } - - @Test - public void absent() { - registry.add(House.class, "a", Window.class); - Class result = registry.findDefaultComponentType(House.class, "other"); - assertNull(result); - } + DefaultNestedComponentRegistry registry = new DefaultNestedComponentRegistry(); + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void smoke() { + String propertyName = "window"; + registry.add(House.class, propertyName, Window.class); + Class result = registry.findDefaultComponentType(House.class, propertyName); + assertEquals(Window.class, result); + } + + @Test + public void absent() { + registry.add(House.class, "a", Window.class); + Class result = registry.findDefaultComponentType(House.class, "other"); + assertNull(result); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DoNotAutoStart.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DoNotAutoStart.java index 879e09610a0364b8c508731bb83840b881c4cd42..b0bf6812677ad201965dbbdba6ba3eb843b8d487 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DoNotAutoStart.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/DoNotAutoStart.java @@ -18,17 +18,18 @@ import ch.qos.logback.core.spi.LifeCycle; @NoAutoStart public class DoNotAutoStart implements LifeCycle { - boolean started = false; - public boolean isStarted() { - return started; - } + boolean started = false; - public void start() { - started = true; - } + public boolean isStarted() { + return started; + } - public void stop() { - started = false; - } + public void start() { + started = true; + } + + public void stop() { + started = false; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ElementSelectorTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ElementSelectorTest.java index c06b9ca9f792f15d0e426893a799561f40668437..1004dff92419e98e0b4bd01517c700c9813172f9 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ElementSelectorTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/ElementSelectorTest.java @@ -24,156 +24,154 @@ import org.junit.Test; */ public class ElementSelectorTest { - @Test - public void test1() { - ElementSelector p = new ElementSelector("a"); - assertEquals(1, p.size()); - assertEquals("a", p.peekLast()); - assertEquals("a", p.get(0)); - } - - @Test - public void testSuffix() { - ElementSelector p = new ElementSelector("a/"); - assertEquals(1, p.size()); - assertEquals("a", p.peekLast()); - assertEquals("a", p.get(0)); - } - - @Test - public void test2() { - ElementSelector p = new ElementSelector("a/b"); - assertEquals(2, p.size()); - assertEquals("b", p.peekLast()); - assertEquals("a", p.get(0)); - assertEquals("b", p.get(1)); - } - - @Test - public void test3() { - ElementSelector p = new ElementSelector("a123/b1234/cvvsdf"); - assertEquals(3, p.size()); - assertEquals("a123", p.get(0)); - assertEquals("b1234", p.get(1)); - assertEquals("cvvsdf", p.get(2)); - } - - @Test - public void test4() { - ElementSelector p = new ElementSelector("/a123/b1234/cvvsdf"); - assertEquals(3, p.size()); - assertEquals("a123", p.get(0)); - assertEquals("b1234", p.get(1)); - assertEquals("cvvsdf", p.get(2)); - } - - @Test - public void test5() { - ElementSelector p = new ElementSelector("//a"); - assertEquals(1, p.size()); - assertEquals("a", p.get(0)); - } - - @Test - public void test6() { - ElementSelector p = new ElementSelector("//a//b"); - assertEquals(2, p.size()); - assertEquals("a", p.get(0)); - assertEquals("b", p.get(1)); - } - - - // test tail matching - @Test - public void testTailMatch() { - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("*"); - assertEquals(0, ruleElementSelector.getTailMatchLength(p)); + @Test + public void test1() { + ElementSelector p = new ElementSelector("a"); + assertEquals(1, p.size()); + assertEquals("a", p.peekLast()); + assertEquals("a", p.get(0)); } - { - ElementPath p = new ElementPath("/a"); - ElementSelector ruleElementSelector = new ElementSelector("*/a"); - assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + @Test + public void testSuffix() { + ElementSelector p = new ElementSelector("a/"); + assertEquals(1, p.size()); + assertEquals("a", p.peekLast()); + assertEquals("a", p.get(0)); } - { - ElementPath p = new ElementPath("/A"); - ElementSelector ruleElementSelector = new ElementSelector("*/a"); - assertEquals(1, ruleElementSelector.getTailMatchLength(p)); - } - - { - ElementPath p = new ElementPath("/a"); - ElementSelector ruleElementSelector = new ElementSelector("*/A"); - assertEquals(1, ruleElementSelector.getTailMatchLength(p)); - } - - - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("*/b"); - assertEquals(1, ruleElementSelector.getTailMatchLength(p)); - } - - { - ElementPath p = new ElementPath("/a/B"); - ElementSelector ruleElementSelector = new ElementSelector("*/b"); - assertEquals(1, ruleElementSelector.getTailMatchLength(p)); - } - - { - ElementPath p = new ElementPath("/a/b/c"); - ElementSelector ruleElementSelector = new ElementSelector("*/b/c"); - assertEquals(2, ruleElementSelector.getTailMatchLength(p)); - } - } - - // test prefix matching - @Test - public void testPrefixMatch() { - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("/x/*"); - assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + @Test + public void test2() { + ElementSelector p = new ElementSelector("a/b"); + assertEquals(2, p.size()); + assertEquals("b", p.peekLast()); + assertEquals("a", p.get(0)); + assertEquals("b", p.get(1)); } - { - ElementPath p = new ElementPath("/a"); - ElementSelector ruleElementSelector = new ElementSelector("/x/*"); - assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + @Test + public void test3() { + ElementSelector p = new ElementSelector("a123/b1234/cvvsdf"); + assertEquals(3, p.size()); + assertEquals("a123", p.get(0)); + assertEquals("b1234", p.get(1)); + assertEquals("cvvsdf", p.get(2)); } - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("/a/*"); - assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + @Test + public void test4() { + ElementSelector p = new ElementSelector("/a123/b1234/cvvsdf"); + assertEquals(3, p.size()); + assertEquals("a123", p.get(0)); + assertEquals("b1234", p.get(1)); + assertEquals("cvvsdf", p.get(2)); } - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("/A/*"); - assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + @Test + public void test5() { + ElementSelector p = new ElementSelector("//a"); + assertEquals(1, p.size()); + assertEquals("a", p.get(0)); } - - { - ElementPath p = new ElementPath("/A/b"); - ElementSelector ruleElementSelector = new ElementSelector("/a/*"); - assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + + @Test + public void test6() { + ElementSelector p = new ElementSelector("//a//b"); + assertEquals(2, p.size()); + assertEquals("a", p.get(0)); + assertEquals("b", p.get(1)); } - - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("/a/b/*"); - assertEquals(2, ruleElementSelector.getPrefixMatchLength(p)); + + // test tail matching + @Test + public void testTailMatch() { + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("*"); + assertEquals(0, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a"); + ElementSelector ruleElementSelector = new ElementSelector("*/a"); + assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/A"); + ElementSelector ruleElementSelector = new ElementSelector("*/a"); + assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a"); + ElementSelector ruleElementSelector = new ElementSelector("*/A"); + assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("*/b"); + assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/B"); + ElementSelector ruleElementSelector = new ElementSelector("*/b"); + assertEquals(1, ruleElementSelector.getTailMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b/c"); + ElementSelector ruleElementSelector = new ElementSelector("*/b/c"); + assertEquals(2, ruleElementSelector.getTailMatchLength(p)); + } } - - { - ElementPath p = new ElementPath("/a/b"); - ElementSelector ruleElementSelector = new ElementSelector("/*"); - assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + + // test prefix matching + @Test + public void testPrefixMatch() { + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("/x/*"); + assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a"); + ElementSelector ruleElementSelector = new ElementSelector("/x/*"); + assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("/a/*"); + assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("/A/*"); + assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/A/b"); + ElementSelector ruleElementSelector = new ElementSelector("/a/*"); + assertEquals(1, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("/a/b/*"); + assertEquals(2, ruleElementSelector.getPrefixMatchLength(p)); + } + + { + ElementPath p = new ElementPath("/a/b"); + ElementSelector ruleElementSelector = new ElementSelector("/*"); + assertEquals(0, ruleElementSelector.getPrefixMatchLength(p)); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/NoAutoStartUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/NoAutoStartUtilTest.java index ffdbb65a67584960efe7e8a60b4477db82452317..72dbeb362a779a38a6bebd1135d60eff04c52d5b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/NoAutoStartUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/NoAutoStartUtilTest.java @@ -18,19 +18,17 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; - public class NoAutoStartUtilTest { - - @Test - public void commonObject() { - Object o = new Object(); - assertTrue(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); - } - - @Test - public void markedWithNoAutoStart() { - DoNotAutoStart o = new DoNotAutoStart(); - assertFalse(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); - } + @Test + public void commonObject() { + Object o = new Object(); + assertTrue(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); + } + + @Test + public void markedWithNoAutoStart() { + DoNotAutoStart o = new DoNotAutoStart(); + assertFalse(NoAutoStartUtil.notMarkedWithNoAutoStart(o)); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/PackageTest.java index a7d24bf587444cd05a60e7d8f4f44dde860c589a..6815e6d288290a9123b6d8c19d599c70ab89bcdd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/PackageTest.java @@ -18,8 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { ElementSelectorTest.class, SimpleRuleStoreTest.class, - NoAutoStartUtilTest.class, ConfigurationWatchListTest.class, - DefaultNestedComponentRegistryTest.class, CaseCombinatorTest.class }) +@SuiteClasses({ ElementSelectorTest.class, SimpleRuleStoreTest.class, NoAutoStartUtilTest.class, ConfigurationWatchListTest.class, + DefaultNestedComponentRegistryTest.class, CaseCombinatorTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/SimpleRuleStoreTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/SimpleRuleStoreTest.java index 96193656c43172cb93684666c80036c711476172..ab834d091a12a737cd2e5bfb026d649160c21099 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/spi/SimpleRuleStoreTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/spi/SimpleRuleStoreTest.java @@ -36,231 +36,228 @@ import ch.qos.logback.core.joran.action.Action; */ public class SimpleRuleStoreTest { - SimpleRuleStore srs = new SimpleRuleStore(new ContextBase()); - CaseCombinator cc = new CaseCombinator(); - - @Test - public void smoke() throws Exception { - srs.addRule(new ElementSelector("a/b"), new XAction()); - - // test for all possible case combinations of "a/b" - for (String s : cc.combinations("a/b")) { - System.out.println("s="+s); - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(1, r.size()); - - if (!(r.get(0) instanceof XAction)) { - fail("Wrong type"); - } + SimpleRuleStore srs = new SimpleRuleStore(new ContextBase()); + CaseCombinator cc = new CaseCombinator(); + + @Test + public void smoke() throws Exception { + srs.addRule(new ElementSelector("a/b"), new XAction()); + + // test for all possible case combinations of "a/b" + for (String s : cc.combinations("a/b")) { + System.out.println("s=" + s); + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(1, r.size()); + + if (!(r.get(0) instanceof XAction)) { + fail("Wrong type"); + } + } } - } - @Test - public void smokeII() throws Exception { - srs.addRule(new ElementSelector("a/b"), new XAction()); - srs.addRule(new ElementSelector("a/b"), new YAction()); + @Test + public void smokeII() throws Exception { + srs.addRule(new ElementSelector("a/b"), new XAction()); + srs.addRule(new ElementSelector("a/b"), new YAction()); - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(2, r.size()); + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(2, r.size()); - if (!(r.get(0) instanceof XAction)) { - fail("Wrong type"); - } + if (!(r.get(0) instanceof XAction)) { + fail("Wrong type"); + } - if (!(r.get(1) instanceof YAction)) { - fail("Wrong type"); - } + if (!(r.get(1) instanceof YAction)) { + fail("Wrong type"); + } + } } - } - @Test - public void testSlashSuffix() throws Exception { - ElementSelector pa = new ElementSelector("a/"); - srs.addRule(pa, new XAction()); + @Test + public void testSlashSuffix() throws Exception { + ElementSelector pa = new ElementSelector("a/"); + srs.addRule(pa, new XAction()); - for (String s : cc.combinations("a")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(1, r.size()); + for (String s : cc.combinations("a")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(1, r.size()); - if (!(r.get(0) instanceof XAction)) { - fail("Wrong type"); - } - } + if (!(r.get(0) instanceof XAction)) { + fail("Wrong type"); + } + } - } + } - @Test - public void testTail1() throws Exception { - srs.addRule(new ElementSelector("*/b"), new XAction()); + @Test + public void testTail1() throws Exception { + srs.addRule(new ElementSelector("*/b"), new XAction()); - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); - assertEquals(1, r.size()); + assertEquals(1, r.size()); - if (!(r.get(0) instanceof XAction)) { - fail("Wrong type"); - } + if (!(r.get(0) instanceof XAction)) { + fail("Wrong type"); + } + } } - } - @Test - public void testTail2() throws Exception { - SimpleRuleStore srs = new SimpleRuleStore(new ContextBase()); - srs.addRule(new ElementSelector("*/c"), new XAction()); + @Test + public void testTail2() throws Exception { + SimpleRuleStore srs = new SimpleRuleStore(new ContextBase()); + srs.addRule(new ElementSelector("*/c"), new XAction()); - for (String s : cc.combinations("a/b/c")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); + for (String s : cc.combinations("a/b/c")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); - assertEquals(1, r.size()); + assertEquals(1, r.size()); - if (!(r.get(0) instanceof XAction)) { - fail("Wrong type"); - } + if (!(r.get(0) instanceof XAction)) { + fail("Wrong type"); + } + } } - } - @Test - public void testTail3() throws Exception { - srs.addRule(new ElementSelector("*/b"), new XAction()); - srs.addRule(new ElementSelector("*/a/b"), new YAction()); + @Test + public void testTail3() throws Exception { + srs.addRule(new ElementSelector("*/b"), new XAction()); + srs.addRule(new ElementSelector("*/a/b"), new YAction()); - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(1, r.size()); + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(1, r.size()); - if (!(r.get(0) instanceof YAction)) { - fail("Wrong type"); - } + if (!(r.get(0) instanceof YAction)) { + fail("Wrong type"); + } + } } - } - - @Test - public void testTail4() throws Exception { - srs.addRule(new ElementSelector("*/b"), new XAction()); - srs.addRule(new ElementSelector("*/a/b"), new YAction()); - srs.addRule(new ElementSelector("a/b"), new ZAction()); - - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(1, r.size()); - - if (!(r.get(0) instanceof ZAction)) { - fail("Wrong type"); - } + + @Test + public void testTail4() throws Exception { + srs.addRule(new ElementSelector("*/b"), new XAction()); + srs.addRule(new ElementSelector("*/a/b"), new YAction()); + srs.addRule(new ElementSelector("a/b"), new ZAction()); + + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(1, r.size()); + + if (!(r.get(0) instanceof ZAction)) { + fail("Wrong type"); + } + } } - } - - @Test - public void testSuffix() throws Exception { - srs.addRule(new ElementSelector("a"), new XAction()); - srs.addRule(new ElementSelector("a/*"), new YAction()); - - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); - assertEquals(1, r.size()); - assertTrue(r.get(0) instanceof YAction); + + @Test + public void testSuffix() throws Exception { + srs.addRule(new ElementSelector("a"), new XAction()); + srs.addRule(new ElementSelector("a/*"), new YAction()); + + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); + assertEquals(1, r.size()); + assertTrue(r.get(0) instanceof YAction); + } } - } - @Test - public void testDeepSuffix() throws Exception { - srs.addRule(new ElementSelector("a"), new XAction(1)); - srs.addRule(new ElementSelector("a/b/*"), new XAction(2)); + @Test + public void testDeepSuffix() throws Exception { + srs.addRule(new ElementSelector("a"), new XAction(1)); + srs.addRule(new ElementSelector("a/b/*"), new XAction(2)); - for (String s : cc.combinations("a/other")) { - List r = srs.matchActions(new ElementPath(s)); - assertNull(r); + for (String s : cc.combinations("a/other")) { + List r = srs.matchActions(new ElementPath(s)); + assertNull(r); + } } - } - @Test - public void testPrefixSuffixInteraction1() throws Exception { - srs.addRule(new ElementSelector("a"), new ZAction()); - srs.addRule(new ElementSelector("a/*"), new YAction()); - srs.addRule(new ElementSelector("*/a/b"), new XAction(3)); + @Test + public void testPrefixSuffixInteraction1() throws Exception { + srs.addRule(new ElementSelector("a"), new ZAction()); + srs.addRule(new ElementSelector("a/*"), new YAction()); + srs.addRule(new ElementSelector("*/a/b"), new XAction(3)); - for (String s : cc.combinations("a/b")) { - List r = srs.matchActions(new ElementPath(s)); - assertNotNull(r); + for (String s : cc.combinations("a/b")) { + List r = srs.matchActions(new ElementPath(s)); + assertNotNull(r); - assertEquals(1, r.size()); + assertEquals(1, r.size()); - assertTrue(r.get(0) instanceof XAction); - XAction xaction = (XAction) r.get(0); - assertEquals(3, xaction.id); + assertTrue(r.get(0) instanceof XAction); + XAction xaction = (XAction) r.get(0); + assertEquals(3, xaction.id); + } } - } - - @Test - public void testPrefixSuffixInteraction2() throws Exception { - srs.addRule(new ElementSelector("tG"), new XAction()); - srs.addRule(new ElementSelector("tG/tS"), new YAction()); - srs.addRule(new ElementSelector("tG/tS/test"), new ZAction()); - srs.addRule(new ElementSelector("tG/tS/test/*"), new XAction(9)); - - for (String s : cc.combinations("tG/tS/toto")) { - List r = srs.matchActions(new ElementPath(s)); - assertNull(r); + + @Test + public void testPrefixSuffixInteraction2() throws Exception { + srs.addRule(new ElementSelector("tG"), new XAction()); + srs.addRule(new ElementSelector("tG/tS"), new YAction()); + srs.addRule(new ElementSelector("tG/tS/test"), new ZAction()); + srs.addRule(new ElementSelector("tG/tS/test/*"), new XAction(9)); + + for (String s : cc.combinations("tG/tS/toto")) { + List r = srs.matchActions(new ElementPath(s)); + assertNull(r); + } } - } - class XAction extends Action { - int id = 0; + class XAction extends Action { + int id = 0; - XAction() { - } + XAction() { + } - XAction(int id) { - this.id = id; - } + XAction(int id) { + this.id = id; + } - public void begin(InterpretationContext ec, String name, - Attributes attributes) { - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } - public void finish(InterpretationContext ec) { - } + public void finish(InterpretationContext ec) { + } - public String toString() { - return "XAction(" + id + ")"; + public String toString() { + return "XAction(" + id + ")"; + } } - } - class YAction extends Action { - public void begin(InterpretationContext ec, String name, - Attributes attributes) { - } + class YAction extends Action { + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } - public void finish(InterpretationContext ec) { + public void finish(InterpretationContext ec) { + } } - } - class ZAction extends Action { - public void begin(InterpretationContext ec, String name, - Attributes attributes) { - } + class ZAction extends Action { + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } - public void finish(InterpretationContext ec) { + public void finish(InterpretationContext ec) { + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/util/House.java b/logback-core/src/test/java/ch/qos/logback/core/joran/util/House.java index 7cc04d26f99d40ac2a0ad99936c490449d03c676..e0117c6671d807a9328ed364827ba0fb8f45e155 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/util/House.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/util/House.java @@ -23,160 +23,158 @@ import ch.qos.logback.core.util.Duration; import ch.qos.logback.core.util.FileSize; public class House { - Door mainDoor; - int count; - Double temperature; - boolean open; - String name; - String camelCase; - SwimmingPool pool; - Duration duration; - FileSize fs; - HouseColor houseColor; - FilterReply reply; - - - Charset charset; - - List adjectiveList = new ArrayList(); - List windowList = new ArrayList(); - List largePoolList = new ArrayList(); - - public String getCamelCase() { - return camelCase; - } - - public void setCamelCase(String camelCase) { - this.camelCase = camelCase; - } - - public int getCount() { - return count; - } - - public void setCount(int c) { - this.count = c; - } - - - public Double getTemperature() { - return temperature; - } - - public void setTemperature(Double temperature) { - this.temperature = temperature; - } - - public Door getDoor() { - return mainDoor; - } - - public void setDoor(Door door) { - this.mainDoor = door; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isOpen() { - return open; - } - - public void setOpen(boolean open) { - this.open = open; - } - - @DefaultClass(LargeSwimmingPoolImpl.class) - public void addLargeSwimmingPool(SwimmingPool pool) { - this.pool = pool; - } - - @DefaultClass(SwimmingPoolImpl.class) - public void setSwimmingPool(SwimmingPool pool) { - this.pool = pool; - } - - public SwimmingPool getSwimmingPool() { - return pool; - } - - public void addWindow(Window w) { - windowList.add(w); - } - - public void addAdjective(String s) { - adjectiveList.add(s); - } - - public Duration getDuration() { - return duration; - } - - public void setDuration(Duration duration) { - this.duration = duration; - } - - public FileSize getFs() { - return fs; - } - - public void setFs(FileSize fs) { - this.fs = fs; - } - - public void setHouseColor(HouseColor color) { - this.houseColor = color; - } - - public HouseColor getHouseColor() { - return houseColor; - } - - public void setFilterReply(FilterReply reply) { - this.reply = reply; - } - - public FilterReply getFilterReply() { - return reply; - } - - public Charset getCharset() { - return charset; - } - - public void setCharset(Charset charset) { - this.charset = charset; - } + Door mainDoor; + int count; + Double temperature; + boolean open; + String name; + String camelCase; + SwimmingPool pool; + Duration duration; + FileSize fs; + HouseColor houseColor; + FilterReply reply; + + Charset charset; + + List adjectiveList = new ArrayList(); + List windowList = new ArrayList(); + List largePoolList = new ArrayList(); + + public String getCamelCase() { + return camelCase; + } + + public void setCamelCase(String camelCase) { + this.camelCase = camelCase; + } + + public int getCount() { + return count; + } + + public void setCount(int c) { + this.count = c; + } + + public Double getTemperature() { + return temperature; + } + + public void setTemperature(Double temperature) { + this.temperature = temperature; + } + + public Door getDoor() { + return mainDoor; + } + + public void setDoor(Door door) { + this.mainDoor = door; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isOpen() { + return open; + } + + public void setOpen(boolean open) { + this.open = open; + } + + @DefaultClass(LargeSwimmingPoolImpl.class) + public void addLargeSwimmingPool(SwimmingPool pool) { + this.pool = pool; + } + + @DefaultClass(SwimmingPoolImpl.class) + public void setSwimmingPool(SwimmingPool pool) { + this.pool = pool; + } + + public SwimmingPool getSwimmingPool() { + return pool; + } + + public void addWindow(Window w) { + windowList.add(w); + } + + public void addAdjective(String s) { + adjectiveList.add(s); + } + + public Duration getDuration() { + return duration; + } + + public void setDuration(Duration duration) { + this.duration = duration; + } + + public FileSize getFs() { + return fs; + } + + public void setFs(FileSize fs) { + this.fs = fs; + } + + public void setHouseColor(HouseColor color) { + this.houseColor = color; + } + + public HouseColor getHouseColor() { + return houseColor; + } + + public void setFilterReply(FilterReply reply) { + this.reply = reply; + } + + public FilterReply getFilterReply() { + return reply; + } + + public Charset getCharset() { + return charset; + } + + public void setCharset(Charset charset) { + this.charset = charset; + } } class Door { - int handle; + int handle; } class Window { - int handle; + int handle; } interface SwimmingPool { } class SwimmingPoolImpl implements SwimmingPool { - int length; - int width; - int depth; + int length; + int width; + int depth; } class LargeSwimmingPoolImpl implements SwimmingPool { - int length; - int width; - int depth; + int length; + int width; + int depth; } enum HouseColor { - WHITE, BLUE + WHITE, BLUE } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/util/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/util/PackageTest.java index 8b14eaccd881e687dcb9ad22c26ef730f84df014..9fc78577e3515cdd9020948aa0793536981dc09b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/util/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/util/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses( { PropertySetterTest.class }) +@SuiteClasses({ PropertySetterTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/joran/util/PropertySetterTest.java b/logback-core/src/test/java/ch/qos/logback/core/joran/util/PropertySetterTest.java index 4730e364185cbb50b0ef3ad799dbd03bdd785c95..17ad13a9a653e670ee35e15ca0d19ac1e8c60652 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/joran/util/PropertySetterTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/joran/util/PropertySetterTest.java @@ -34,214 +34,189 @@ import ch.qos.logback.core.util.AggregationType; public class PropertySetterTest { - DefaultNestedComponentRegistry defaultComponentRegistry = new DefaultNestedComponentRegistry(); - - Context context = new ContextBase(); - House house = new House(); - PropertySetter setter = new PropertySetter(house); - - - @Before - public void setUp() { - setter.setContext(context); - } - - @Test - public void testCanAggregateComponent() { - assertEquals(AggregationType.AS_COMPLEX_PROPERTY, setter - .computeAggregationType("door")); - - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("count")); - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("Count")); - - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("name")); - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("Name")); - - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("Duration")); - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("fs")); - - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("open")); - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("Open")); - - assertEquals(AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, setter - .computeAggregationType("Window")); - assertEquals(AggregationType.AS_BASIC_PROPERTY_COLLECTION, setter - .computeAggregationType("adjective")); - - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("filterReply")); - assertEquals(AggregationType.AS_BASIC_PROPERTY, setter - .computeAggregationType("houseColor")); - - System.out.println(); - } - - @Test - public void testSetProperty() { - { - House house = new House(); - PropertySetter setter = new PropertySetter(house); - setter.setProperty("count", "10"); - setter.setProperty("temperature", "33.1"); - - setter.setProperty("name", "jack"); - setter.setProperty("open", "true"); - - assertEquals(10, house.getCount()); - assertEquals(33.1d, (double) house.getTemperature(), 0.01); - assertEquals("jack", house.getName()); - assertTrue(house.isOpen()); - } - - { - House house = new House(); - PropertySetter setter = new PropertySetter(house); - setter.setProperty("Count", "10"); - setter.setProperty("Name", "jack"); - setter.setProperty("Open", "true"); - - assertEquals(10, house.getCount()); - assertEquals("jack", house.getName()); - assertTrue(house.isOpen()); - } - } - - @Test - public void testSetCamelProperty() { - setter.setProperty("camelCase", "trot"); - assertEquals("trot", house.getCamelCase()); - - setter.setProperty("camelCase", "gh"); - assertEquals("gh", house.getCamelCase()); - } - - @Test - public void testSetComplexProperty() { - Door door = new Door(); - setter.setComplexProperty("door", door); - assertEquals(door, house.getDoor()); - } - - @Test - public void testgetClassNameViaImplicitRules() { - Class compClass = setter.getClassNameViaImplicitRules("door", - AggregationType.AS_COMPLEX_PROPERTY, defaultComponentRegistry); - assertEquals(Door.class, compClass); - } - - @Test - public void testgetComplexPropertyColleClassNameViaImplicitRules() { - Class compClass = setter.getClassNameViaImplicitRules("window", - AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, - defaultComponentRegistry); - assertEquals(Window.class, compClass); - } - - @Test - public void testPropertyCollection() { - setter.addBasicProperty("adjective", "nice"); - setter.addBasicProperty("adjective", "big"); - - assertEquals(2, house.adjectiveList.size()); - assertEquals("nice", house.adjectiveList.get(0)); - assertEquals("big", house.adjectiveList.get(1)); - } - - @Test - public void testComplexCollection() { - Window w1 = new Window(); - w1.handle = 10; - Window w2 = new Window(); - w2.handle = 20; - - setter.addComplexProperty("window", w1); - setter.addComplexProperty("window", w2); - assertEquals(2, house.windowList.size()); - assertEquals(10, house.windowList.get(0).handle); - assertEquals(20, house.windowList.get(1).handle); - } - - @Test - public void testSetComplexWithCamelCaseName() { - SwimmingPool pool = new SwimmingPoolImpl(); - setter.setComplexProperty("swimmingPool", pool); - assertEquals(pool, house.getSwimmingPool()); - } - - @Test - public void testDuration() { - setter.setProperty("duration", "1.4 seconds"); - assertEquals(1400, house.getDuration().getMilliseconds()); - } - - @Test - public void testFileSize() { - setter.setProperty("fs", "2 kb"); - assertEquals(2 * 1024, house.getFs().getSize()); - } - - @Test - public void testFilterReply() { - // test case reproducing bug #52 - setter.setProperty("filterReply", "ACCEPT"); - assertEquals(FilterReply.ACCEPT, house.getFilterReply()); - } - - @Test - public void testEnum() { - setter.setProperty("houseColor", "BLUE"); - assertEquals(HouseColor.BLUE, house.getHouseColor()); - } - - @Test - public void testDefaultClassAnnonation() { - Method relevantMethod = setter.getRelevantMethod("SwimmingPool", - AggregationType.AS_COMPLEX_PROPERTY); - assertNotNull(relevantMethod); - Class spClass = setter.getDefaultClassNameByAnnonation("SwimmingPool", - relevantMethod); - assertEquals(SwimmingPoolImpl.class, spClass); - - Class classViaImplicitRules = setter.getClassNameViaImplicitRules( - "SwimmingPool", AggregationType.AS_COMPLEX_PROPERTY, - defaultComponentRegistry); - assertEquals(SwimmingPoolImpl.class, classViaImplicitRules); - } - - @Test - public void testDefaultClassAnnotationForLists() { - Method relevantMethod = setter.getRelevantMethod("LargeSwimmingPool", - AggregationType.AS_COMPLEX_PROPERTY_COLLECTION); - assertNotNull(relevantMethod); - Class spClass = setter.getDefaultClassNameByAnnonation("LargeSwimmingPool", - relevantMethod); - assertEquals(LargeSwimmingPoolImpl.class, spClass); - - Class classViaImplicitRules = setter.getClassNameViaImplicitRules( - "LargeSwimmingPool", AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, - defaultComponentRegistry); - assertEquals(LargeSwimmingPoolImpl.class, classViaImplicitRules); - } - - @Test - public void charset() { - setter.setProperty("charset", "UTF-8"); - assertEquals(Charset.forName("UTF-8"), house.getCharset()); - - house.setCharset(null); - setter.setProperty("charset", "UTF"); - assertNull(house.getCharset()); - - StatusChecker checker = new StatusChecker(context); - checker.containsException(UnsupportedCharsetException.class); - } -} + DefaultNestedComponentRegistry defaultComponentRegistry = new DefaultNestedComponentRegistry(); + + Context context = new ContextBase(); + House house = new House(); + PropertySetter setter = new PropertySetter(house); + + @Before + public void setUp() { + setter.setContext(context); + } + + @Test + public void testCanAggregateComponent() { + assertEquals(AggregationType.AS_COMPLEX_PROPERTY, setter.computeAggregationType("door")); + + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("count")); + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Count")); + + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("name")); + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Name")); + + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Duration")); + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("fs")); + + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("open")); + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("Open")); + + assertEquals(AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, setter.computeAggregationType("Window")); + assertEquals(AggregationType.AS_BASIC_PROPERTY_COLLECTION, setter.computeAggregationType("adjective")); + + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("filterReply")); + assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("houseColor")); + + System.out.println(); + } + + @Test + public void testSetProperty() { + { + House house = new House(); + PropertySetter setter = new PropertySetter(house); + setter.setProperty("count", "10"); + setter.setProperty("temperature", "33.1"); + + setter.setProperty("name", "jack"); + setter.setProperty("open", "true"); + + assertEquals(10, house.getCount()); + assertEquals(33.1d, (double) house.getTemperature(), 0.01); + assertEquals("jack", house.getName()); + assertTrue(house.isOpen()); + } + + { + House house = new House(); + PropertySetter setter = new PropertySetter(house); + setter.setProperty("Count", "10"); + setter.setProperty("Name", "jack"); + setter.setProperty("Open", "true"); + + assertEquals(10, house.getCount()); + assertEquals("jack", house.getName()); + assertTrue(house.isOpen()); + } + } + + @Test + public void testSetCamelProperty() { + setter.setProperty("camelCase", "trot"); + assertEquals("trot", house.getCamelCase()); + + setter.setProperty("camelCase", "gh"); + assertEquals("gh", house.getCamelCase()); + } + + @Test + public void testSetComplexProperty() { + Door door = new Door(); + setter.setComplexProperty("door", door); + assertEquals(door, house.getDoor()); + } + + @Test + public void testgetClassNameViaImplicitRules() { + Class compClass = setter.getClassNameViaImplicitRules("door", AggregationType.AS_COMPLEX_PROPERTY, defaultComponentRegistry); + assertEquals(Door.class, compClass); + } + + @Test + public void testgetComplexPropertyColleClassNameViaImplicitRules() { + Class compClass = setter.getClassNameViaImplicitRules("window", AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, defaultComponentRegistry); + assertEquals(Window.class, compClass); + } + + @Test + public void testPropertyCollection() { + setter.addBasicProperty("adjective", "nice"); + setter.addBasicProperty("adjective", "big"); + assertEquals(2, house.adjectiveList.size()); + assertEquals("nice", house.adjectiveList.get(0)); + assertEquals("big", house.adjectiveList.get(1)); + } + + @Test + public void testComplexCollection() { + Window w1 = new Window(); + w1.handle = 10; + Window w2 = new Window(); + w2.handle = 20; + + setter.addComplexProperty("window", w1); + setter.addComplexProperty("window", w2); + assertEquals(2, house.windowList.size()); + assertEquals(10, house.windowList.get(0).handle); + assertEquals(20, house.windowList.get(1).handle); + } + + @Test + public void testSetComplexWithCamelCaseName() { + SwimmingPool pool = new SwimmingPoolImpl(); + setter.setComplexProperty("swimmingPool", pool); + assertEquals(pool, house.getSwimmingPool()); + } + + @Test + public void testDuration() { + setter.setProperty("duration", "1.4 seconds"); + assertEquals(1400, house.getDuration().getMilliseconds()); + } + + @Test + public void testFileSize() { + setter.setProperty("fs", "2 kb"); + assertEquals(2 * 1024, house.getFs().getSize()); + } + + @Test + public void testFilterReply() { + // test case reproducing bug #52 + setter.setProperty("filterReply", "ACCEPT"); + assertEquals(FilterReply.ACCEPT, house.getFilterReply()); + } + + @Test + public void testEnum() { + setter.setProperty("houseColor", "BLUE"); + assertEquals(HouseColor.BLUE, house.getHouseColor()); + } + + @Test + public void testDefaultClassAnnonation() { + Method relevantMethod = setter.getRelevantMethod("SwimmingPool", AggregationType.AS_COMPLEX_PROPERTY); + assertNotNull(relevantMethod); + Class spClass = setter.getDefaultClassNameByAnnonation("SwimmingPool", relevantMethod); + assertEquals(SwimmingPoolImpl.class, spClass); + + Class classViaImplicitRules = setter.getClassNameViaImplicitRules("SwimmingPool", AggregationType.AS_COMPLEX_PROPERTY, defaultComponentRegistry); + assertEquals(SwimmingPoolImpl.class, classViaImplicitRules); + } + + @Test + public void testDefaultClassAnnotationForLists() { + Method relevantMethod = setter.getRelevantMethod("LargeSwimmingPool", AggregationType.AS_COMPLEX_PROPERTY_COLLECTION); + assertNotNull(relevantMethod); + Class spClass = setter.getDefaultClassNameByAnnonation("LargeSwimmingPool", relevantMethod); + assertEquals(LargeSwimmingPoolImpl.class, spClass); + + Class classViaImplicitRules = setter.getClassNameViaImplicitRules("LargeSwimmingPool", AggregationType.AS_COMPLEX_PROPERTY_COLLECTION, + defaultComponentRegistry); + assertEquals(LargeSwimmingPoolImpl.class, classViaImplicitRules); + } + + @Test + public void charset() { + setter.setProperty("charset", "UTF-8"); + assertEquals(Charset.forName("UTF-8"), house.getCharset()); + + house.setCharset(null); + setter.setProperty("charset", "UTF"); + assertNull(house.getCharset()); + + StatusChecker checker = new StatusChecker(context); + checker.containsException(UnsupportedCharsetException.class); + } +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/layout/DummyLayout.java b/logback-core/src/test/java/ch/qos/logback/core/layout/DummyLayout.java index 77fdb2ae7787ffaf1009bed0343be31a9c6e3edb..08040830e9c81a91651e3802f3364884c41ec038 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/layout/DummyLayout.java +++ b/logback-core/src/test/java/ch/qos/logback/core/layout/DummyLayout.java @@ -18,19 +18,18 @@ import ch.qos.logback.core.LayoutBase; public class DummyLayout extends LayoutBase { - public static final String DUMMY = "dummy"+CoreConstants.LINE_SEPARATOR; - String val = DUMMY; - - public DummyLayout() { - } - - public DummyLayout(String val) { - this.val = val; - } - - public String doLayout(E event) { - return val; - } + public static final String DUMMY = "dummy" + CoreConstants.LINE_SEPARATOR; + String val = DUMMY; + + public DummyLayout() { + } + + public DummyLayout(String val) { + this.val = val; + } + + public String doLayout(E event) { + return val; + } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/layout/NopLayout.java b/logback-core/src/test/java/ch/qos/logback/core/layout/NopLayout.java index ece290523e98206420556ef511bb7cdfaed2b349..261a75be6dca4c3224fae2add58772061fb278fc 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/layout/NopLayout.java +++ b/logback-core/src/test/java/ch/qos/logback/core/layout/NopLayout.java @@ -16,8 +16,8 @@ package ch.qos.logback.core.layout; import ch.qos.logback.core.LayoutBase; public class NopLayout extends LayoutBase { - - public String doLayout(E event) { - return ""; - } + + public String doLayout(E event) { + return ""; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSSLSocketAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSSLSocketAppenderTest.java index 414f3ae73f7dadcc6f645451fbcc6e6aba253d49..e82585607cfe33b030278e9f10b4b02ea7769a8d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSSLSocketAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSSLSocketAppenderTest.java @@ -27,38 +27,36 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * @author Carl Harris */ public class AbstractSSLSocketAppenderTest { - - private MockContext context = new MockContext(); - private InstrumentedSSLSocketAppenderBase appender = - new InstrumentedSSLSocketAppenderBase(); - - @Before - public void setUp() throws Exception { - appender.setContext(context); - } - - @Test - public void testUsingDefaultConfig() throws Exception { - // should be able to start and stop successfully with no SSL - // configuration at all - appender.start(); - assertNotNull(appender.getSocketFactory()); - appender.stop(); - } - - private static class InstrumentedSSLSocketAppenderBase - extends AbstractSSLSocketAppender { + private MockContext context = new MockContext(); - @Override - protected void postProcessEvent(Object event) { - throw new UnsupportedOperationException(); + private InstrumentedSSLSocketAppenderBase appender = new InstrumentedSSLSocketAppenderBase(); + + @Before + public void setUp() throws Exception { + appender.setContext(context); + } + + @Test + public void testUsingDefaultConfig() throws Exception { + // should be able to start and stop successfully with no SSL + // configuration at all + appender.start(); + assertNotNull(appender.getSocketFactory()); + appender.stop(); } - @Override - protected PreSerializationTransformer getPST() { - throw new UnsupportedOperationException(); + private static class InstrumentedSSLSocketAppenderBase extends AbstractSSLSocketAppender { + + @Override + protected void postProcessEvent(Object event) { + throw new UnsupportedOperationException(); + } + + @Override + protected PreSerializationTransformer getPST() { + throw new UnsupportedOperationException(); + } + } - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java index dfea435f5982f268a6940e528329539738dda136..26ab212ea0536618ebb55f1d30e3ea46e73c9e5e 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java @@ -48,81 +48,81 @@ import static org.mockito.Mockito.when; */ public class AbstractSocketAppenderIntegrationTest { - private static final int TIMEOUT = 2000; - - private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool(); - private MockContext mockContext = new MockContext(executorService); - private AutoFlushingObjectWriter objectWriter; - private ObjectWriterFactory objectWriterFactory = new SpyProducingObjectWriterFactory(); - private LinkedBlockingDeque deque = spy(new LinkedBlockingDeque(1)); - private QueueFactory queueFactory = mock(QueueFactory.class); - private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender(queueFactory, objectWriterFactory); - - @Before - public void setUp() throws Exception { - when(queueFactory.newLinkedBlockingDeque(anyInt())).thenReturn(deque); - instrumentedAppender.setContext(mockContext); - } - - @After - public void tearDown() throws Exception { - instrumentedAppender.stop(); - assertFalse(instrumentedAppender.isStarted()); - executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); - } - - @Test - public void dispatchesEvents() throws Exception { - - // given - ServerSocket serverSocket = ServerSocketUtil.createServerSocket(); - instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress()); - instrumentedAppender.setPort(serverSocket.getLocalPort()); - instrumentedAppender.start(); - - Socket appenderSocket = serverSocket.accept(); - serverSocket.close(); - - // when - instrumentedAppender.append("some event"); - - // wait for event to be taken from deque and being written into the stream - verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst(); - verify(objectWriter, timeout(TIMEOUT)).write("some event"); - - // then - ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream()); - assertEquals("some event", ois.readObject()); - appenderSocket.close(); - } - - private static class InstrumentedSocketAppender extends AbstractSocketAppender { - - public InstrumentedSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { - super(queueFactory, objectWriterFactory); + private static final int TIMEOUT = 2000; + + private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + private MockContext mockContext = new MockContext(executorService); + private AutoFlushingObjectWriter objectWriter; + private ObjectWriterFactory objectWriterFactory = new SpyProducingObjectWriterFactory(); + private LinkedBlockingDeque deque = spy(new LinkedBlockingDeque(1)); + private QueueFactory queueFactory = mock(QueueFactory.class); + private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender(queueFactory, objectWriterFactory); + + @Before + public void setUp() throws Exception { + when(queueFactory. newLinkedBlockingDeque(anyInt())).thenReturn(deque); + instrumentedAppender.setContext(mockContext); } - @Override - protected void postProcessEvent(String event) { + @After + public void tearDown() throws Exception { + instrumentedAppender.stop(); + assertFalse(instrumentedAppender.isStarted()); + executorService.shutdownNow(); + assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); } - @Override - protected PreSerializationTransformer getPST() { - return new PreSerializationTransformer() { - public Serializable transform(String event) { - return event; + @Test + public void dispatchesEvents() throws Exception { + + // given + ServerSocket serverSocket = ServerSocketUtil.createServerSocket(); + instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress()); + instrumentedAppender.setPort(serverSocket.getLocalPort()); + instrumentedAppender.start(); + + Socket appenderSocket = serverSocket.accept(); + serverSocket.close(); + + // when + instrumentedAppender.append("some event"); + + // wait for event to be taken from deque and being written into the stream + verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst(); + verify(objectWriter, timeout(TIMEOUT)).write("some event"); + + // then + ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream()); + assertEquals("some event", ois.readObject()); + appenderSocket.close(); + } + + private static class InstrumentedSocketAppender extends AbstractSocketAppender { + + public InstrumentedSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { + super(queueFactory, objectWriterFactory); + } + + @Override + protected void postProcessEvent(String event) { + } + + @Override + protected PreSerializationTransformer getPST() { + return new PreSerializationTransformer() { + public Serializable transform(String event) { + return event; + } + }; } - }; } - } - private class SpyProducingObjectWriterFactory extends ObjectWriterFactory { + private class SpyProducingObjectWriterFactory extends ObjectWriterFactory { - @Override - public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { - objectWriter = spy(super.newAutoFlushingObjectWriter(outputStream)); - return objectWriter; + @Override + public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { + objectWriter = spy(super.newAutoFlushingObjectWriter(outputStream)); + return objectWriter; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java index eb041254306847a6fe1b3b15875409addbe1afbc..50172105f2e6ead46f3fc6f0230977e879d4224a 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java @@ -58,469 +58,468 @@ import static org.mockito.Mockito.when; */ public class AbstractSocketAppenderTest { - /** - * Timeout used for all blocking operations in multi-threading contexts. - */ - private static final int TIMEOUT = 1000; - - private ThreadPoolExecutor executorService = spy((ThreadPoolExecutor) Executors.newCachedThreadPool()); - private MockContext mockContext = new MockContext(executorService); - private PreSerializationTransformer preSerializationTransformer = spy(new StringPreSerializationTransformer()); - private Socket socket = mock(Socket.class); - private SocketConnector socketConnector = mock(SocketConnector.class); - private AutoFlushingObjectWriter objectWriter = mock(AutoFlushingObjectWriter.class); - private ObjectWriterFactory objectWriterFactory = mock(ObjectWriterFactory.class); - private LinkedBlockingDeque deque = spy(new LinkedBlockingDeque(1)); - private QueueFactory queueFactory = mock(QueueFactory.class); - private InstrumentedSocketAppender appender = spy(new InstrumentedSocketAppender(preSerializationTransformer, queueFactory, objectWriterFactory, socketConnector)); - - @Before - public void setupValidAppenderWithMockDependencies() throws Exception { - - doReturn(objectWriter).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); - doReturn(deque).when(queueFactory).newLinkedBlockingDeque(anyInt()); - - appender.setContext(mockContext); - appender.setRemoteHost("localhost"); - } + /** + * Timeout used for all blocking operations in multi-threading contexts. + */ + private static final int TIMEOUT = 1000; + + private ThreadPoolExecutor executorService = spy((ThreadPoolExecutor) Executors.newCachedThreadPool()); + private MockContext mockContext = new MockContext(executorService); + private PreSerializationTransformer preSerializationTransformer = spy(new StringPreSerializationTransformer()); + private Socket socket = mock(Socket.class); + private SocketConnector socketConnector = mock(SocketConnector.class); + private AutoFlushingObjectWriter objectWriter = mock(AutoFlushingObjectWriter.class); + private ObjectWriterFactory objectWriterFactory = mock(ObjectWriterFactory.class); + private LinkedBlockingDeque deque = spy(new LinkedBlockingDeque(1)); + private QueueFactory queueFactory = mock(QueueFactory.class); + private InstrumentedSocketAppender appender = spy(new InstrumentedSocketAppender(preSerializationTransformer, queueFactory, objectWriterFactory, + socketConnector)); + + @Before + public void setupValidAppenderWithMockDependencies() throws Exception { + + doReturn(objectWriter).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + doReturn(deque).when(queueFactory). newLinkedBlockingDeque(anyInt()); + + appender.setContext(mockContext); + appender.setRemoteHost("localhost"); + } - @After - public void tearDown() throws Exception { - appender.stop(); - assertFalse(appender.isStarted()); + @After + public void tearDown() throws Exception { + appender.stop(); + assertFalse(appender.isStarted()); - executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); - } + executorService.shutdownNow(); + assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); + } - @Test - public void failsToStartWithoutValidPort() throws Exception { + @Test + public void failsToStartWithoutValidPort() throws Exception { - // given - appender.setPort(-1); + // given + appender.setPort(-1); - // when - appender.start(); + // when + appender.start(); - // then - assertFalse(appender.isStarted()); - verify(appender).addError(contains("port")); - } + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("port")); + } - @Test - public void failsToStartWithoutValidRemoteHost() throws Exception { + @Test + public void failsToStartWithoutValidRemoteHost() throws Exception { - // given - appender.setRemoteHost(null); + // given + appender.setRemoteHost(null); - // when - appender.start(); + // when + appender.start(); - // then - assertFalse(appender.isStarted()); - verify(appender).addError(contains("remote host")); - } + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("remote host")); + } - @Test - public void failsToStartWithNegativeQueueSize() throws Exception { + @Test + public void failsToStartWithNegativeQueueSize() throws Exception { - // given - appender.setQueueSize(-1); + // given + appender.setQueueSize(-1); - // when - appender.start(); + // when + appender.start(); - // then - assertFalse(appender.isStarted()); - verify(appender).addError(contains("Queue size must be greater than zero")); - } + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("Queue size must be greater than zero")); + } - @Test - public void failsToStartWithUnresolvableRemoteHost() throws Exception { + @Test + public void failsToStartWithUnresolvableRemoteHost() throws Exception { - // given - appender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME"); + // given + appender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME"); - // when - appender.start(); + // when + appender.start(); - // then - assertFalse(appender.isStarted()); - verify(appender).addError(contains("unknown host")); - } + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("unknown host")); + } - @Test - public void startsButOutputsWarningWhenQueueSizeIsZero() throws Exception { + @Test + public void startsButOutputsWarningWhenQueueSizeIsZero() throws Exception { - // given - appender.setQueueSize(0); + // given + appender.setQueueSize(0); - // when - appender.start(); + // when + appender.start(); - // then - assertTrue(appender.isStarted()); - verify(appender).addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); - } + // then + assertTrue(appender.isStarted()); + verify(appender).addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); + } - @Test - public void startsWithValidParameters() throws Exception { + @Test + public void startsWithValidParameters() throws Exception { - // when - appender.start(); + // when + appender.start(); - // then - assertTrue(appender.isStarted()); - } + // then + assertTrue(appender.isStarted()); + } - @Test - public void createsSocketConnectorWithConfiguredParameters() throws Exception { + @Test + public void createsSocketConnectorWithConfiguredParameters() throws Exception { - // given - appender.setReconnectionDelay(new Duration(42)); - appender.setRemoteHost("localhost"); - appender.setPort(21); + // given + appender.setReconnectionDelay(new Duration(42)); + appender.setRemoteHost("localhost"); + appender.setPort(21); - // when - appender.start(); + // when + appender.start(); - // then - verify(appender, timeout(TIMEOUT)).newConnector(InetAddress.getByName("localhost"), 21, 0, 42); - } + // then + verify(appender, timeout(TIMEOUT)).newConnector(InetAddress.getByName("localhost"), 21, 0, 42); + } - @Test - public void addsInfoMessageWhenSocketConnectionWasEstablished() throws Exception { + @Test + public void addsInfoMessageWhenSocketConnectionWasEstablished() throws Exception { - // when - mockOneSuccessfulSocketConnection(); - appender.start(); + // when + mockOneSuccessfulSocketConnection(); + appender.start(); - // then - verify(appender, timeout(TIMEOUT)).addInfo(contains("connection established")); - } + // then + verify(appender, timeout(TIMEOUT)).addInfo(contains("connection established")); + } - @Test - public void addsInfoMessageWhenSocketConnectionFailed() throws Exception { + @Test + public void addsInfoMessageWhenSocketConnectionFailed() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); - appender.start(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection failed")); - } + // then + verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection failed")); + } - @Test - public void closesSocketOnException() throws Exception { + @Test + public void closesSocketOnException() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); - appender.start(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(socket, timeout(TIMEOUT).atLeastOnce()).close(); - } + // then + verify(socket, timeout(TIMEOUT).atLeastOnce()).close(); + } - @Test - public void addsInfoMessageWhenSocketConnectionClosed() throws Exception { + @Test + public void addsInfoMessageWhenSocketConnectionClosed() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); - appender.start(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection closed")); - } + // then + verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection closed")); + } - @Test - public void shutsDownOnInterruptWhileWaitingForEvent() throws Exception { + @Test + public void shutsDownOnInterruptWhileWaitingForEvent() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new InterruptedException()).when(deque).takeFirst(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new InterruptedException()).when(deque).takeFirst(); - // when - appender.start(); + // when + appender.start(); - // then - verify(deque, timeout(TIMEOUT)).takeFirst(); - } + // then + verify(deque, timeout(TIMEOUT)).takeFirst(); + } - @Test - public void shutsDownOnInterruptWhileWaitingForSocketConnection() throws Exception { + @Test + public void shutsDownOnInterruptWhileWaitingForSocketConnection() throws Exception { - // given - doThrow(new InterruptedException()).when(socketConnector).call(); + // given + doThrow(new InterruptedException()).when(socketConnector).call(); - // when - appender.start(); + // when + appender.start(); - // then - verify(socketConnector, timeout(TIMEOUT)).call(); - } + // then + verify(socketConnector, timeout(TIMEOUT)).call(); + } - @Test - public void addsInfoMessageWhenShuttingDownDueToInterrupt() throws Exception { + @Test + public void addsInfoMessageWhenShuttingDownDueToInterrupt() throws Exception { - // given - doThrow(new InterruptedException()).when(socketConnector).call(); + // given + doThrow(new InterruptedException()).when(socketConnector).call(); - // when - appender.start(); + // when + appender.start(); - // then - verify(appender, timeout(TIMEOUT)).addInfo(contains("shutting down")); - } + // then + verify(appender, timeout(TIMEOUT)).addInfo(contains("shutting down")); + } - @Test - public void offersEventsToTheEndOfTheDeque() throws Exception { + @Test + public void offersEventsToTheEndOfTheDeque() throws Exception { - // given - appender.start(); + // given + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); - } + // then + verify(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); + } - @Test - public void doesNotQueueAnyEventsWhenStopped() throws Exception { + @Test + public void doesNotQueueAnyEventsWhenStopped() throws Exception { - // given - appender.start(); - appender.stop(); + // given + appender.start(); + appender.stop(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verifyZeroInteractions(deque); - } + // then + verifyZeroInteractions(deque); + } - @Test - public void addsInfoMessageWhenEventCouldNotBeQueuedInConfiguredTimeoutDueToQueueSizeLimitation() throws Exception { + @Test + public void addsInfoMessageWhenEventCouldNotBeQueuedInConfiguredTimeoutDueToQueueSizeLimitation() throws Exception { - // given - long eventDelayLimit = 42; - doReturn(false).when(deque).offer("some event", eventDelayLimit, TimeUnit.MILLISECONDS); - appender.setEventDelayLimit(new Duration(eventDelayLimit)); - appender.start(); + // given + long eventDelayLimit = 42; + doReturn(false).when(deque).offer("some event", eventDelayLimit, TimeUnit.MILLISECONDS); + appender.setEventDelayLimit(new Duration(eventDelayLimit)); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(appender).addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + " milliseconds] being exceeded"); - } + // then + verify(appender).addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + " milliseconds] being exceeded"); + } - @Test - public void takesEventsFromTheFrontOfTheDeque() throws Exception { + @Test + public void takesEventsFromTheFrontOfTheDeque() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - appender.start(); - awaitStartOfEventDispatching(); + // given + mockOneSuccessfulSocketConnection(); + appender.start(); + awaitStartOfEventDispatching(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst(); - } + // then + verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst(); + } - @Test - public void reAddsEventAtTheFrontOfTheDequeWhenTransmissionFails() throws Exception { + @Test + public void reAddsEventAtTheFrontOfTheDequeWhenTransmissionFails() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(objectWriter).write(anyObject()); - appender.start(); - awaitStartOfEventDispatching(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(objectWriter).write(anyObject()); + appender.start(); + awaitStartOfEventDispatching(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(deque, timeout(TIMEOUT).atLeastOnce()).offerFirst("some event"); - } + // then + verify(deque, timeout(TIMEOUT).atLeastOnce()).offerFirst("some event"); + } - @Test - public void addsErrorMessageWhenAppendingIsInterruptedWhileWaitingForTheQueueToAcceptTheEvent() throws Exception { + @Test + public void addsErrorMessageWhenAppendingIsInterruptedWhileWaitingForTheQueueToAcceptTheEvent() throws Exception { - // given - final InterruptedException interruptedException = new InterruptedException(); - doThrow(interruptedException).when(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); - appender.start(); + // given + final InterruptedException interruptedException = new InterruptedException(); + doThrow(interruptedException).when(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(appender).addError("Interrupted while appending event to SocketAppender", interruptedException); - } + // then + verify(appender).addError("Interrupted while appending event to SocketAppender", interruptedException); + } - @Test - public void postProcessesEventsBeforeTransformingItToASerializable() throws Exception { + @Test + public void postProcessesEventsBeforeTransformingItToASerializable() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - appender.start(); - awaitStartOfEventDispatching(); + // given + mockOneSuccessfulSocketConnection(); + appender.start(); + awaitStartOfEventDispatching(); - // when - appender.append("some event"); - awaitAtLeastOneEventToBeDispatched(); + // when + appender.append("some event"); + awaitAtLeastOneEventToBeDispatched(); - // then - InOrder inOrder = inOrder(appender, preSerializationTransformer); - inOrder.verify(appender).postProcessEvent("some event"); - inOrder.verify(preSerializationTransformer).transform("some event"); - } + // then + InOrder inOrder = inOrder(appender, preSerializationTransformer); + inOrder.verify(appender).postProcessEvent("some event"); + inOrder.verify(preSerializationTransformer).transform("some event"); + } - @Test - public void writesSerializedEventToStream() throws Exception { + @Test + public void writesSerializedEventToStream() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - when(preSerializationTransformer.transform("some event")).thenReturn("some serialized event"); - appender.start(); - awaitStartOfEventDispatching(); + // given + mockOneSuccessfulSocketConnection(); + when(preSerializationTransformer.transform("some event")).thenReturn("some serialized event"); + appender.start(); + awaitStartOfEventDispatching(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(objectWriter, timeout(TIMEOUT)).write("some serialized event"); - } + // then + verify(objectWriter, timeout(TIMEOUT)).write("some serialized event"); + } - @Test - public void addsInfoMessageWhenEventIsBeingDroppedBecauseOfConnectionProblemAndDequeCapacityLimitReached() throws Exception { + @Test + public void addsInfoMessageWhenEventIsBeingDroppedBecauseOfConnectionProblemAndDequeCapacityLimitReached() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(objectWriter).write(anyObject()); - doReturn(false).when(deque).offerFirst("some event"); - appender.start(); - awaitStartOfEventDispatching(); - reset(appender); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(objectWriter).write(anyObject()); + doReturn(false).when(deque).offerFirst("some event"); + appender.start(); + awaitStartOfEventDispatching(); + reset(appender); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(appender, timeout(TIMEOUT)).addInfo("Dropping event due to socket connection error and maxed out deque capacity"); - } + // then + verify(appender, timeout(TIMEOUT)).addInfo("Dropping event due to socket connection error and maxed out deque capacity"); + } - @Test - public void reEstablishesSocketConnectionOnConnectionDropWhenWritingEvent() throws Exception { + @Test + public void reEstablishesSocketConnectionOnConnectionDropWhenWritingEvent() throws Exception { - // given - mockTwoSuccessfulSocketConnections(); - doThrow(new IOException()).when(objectWriter).write(anyObject()); - appender.start(); - awaitStartOfEventDispatching(); + // given + mockTwoSuccessfulSocketConnections(); + doThrow(new IOException()).when(objectWriter).write(anyObject()); + appender.start(); + awaitStartOfEventDispatching(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(objectWriterFactory, timeout(TIMEOUT).atLeast(2)).newAutoFlushingObjectWriter(any(OutputStream.class)); - } + // then + verify(objectWriterFactory, timeout(TIMEOUT).atLeast(2)).newAutoFlushingObjectWriter(any(OutputStream.class)); + } - @Test - public void triesToReEstablishSocketConnectionIfItFailed() throws Exception { + @Test + public void triesToReEstablishSocketConnectionIfItFailed() throws Exception { - // given - mockOneSuccessfulSocketConnection(); - doThrow(new IOException()).when(socket).getOutputStream(); - appender.start(); + // given + mockOneSuccessfulSocketConnection(); + doThrow(new IOException()).when(socket).getOutputStream(); + appender.start(); - // when - appender.append("some event"); + // when + appender.append("some event"); - // then - verify(socketConnector, timeout(TIMEOUT).atLeast(2)).call(); - } + // then + verify(socketConnector, timeout(TIMEOUT).atLeast(2)).call(); + } - @Test - public void usesConfiguredAcceptConnectionTimeoutAndResetsSocketTimeoutAfterSuccessfulConnection() throws Exception { + @Test + public void usesConfiguredAcceptConnectionTimeoutAndResetsSocketTimeoutAfterSuccessfulConnection() throws Exception { - // when - mockOneSuccessfulSocketConnection(); - appender.setAcceptConnectionTimeout(42); - appender.start(); - awaitStartOfEventDispatching(); + // when + mockOneSuccessfulSocketConnection(); + appender.setAcceptConnectionTimeout(42); + appender.start(); + awaitStartOfEventDispatching(); - // then - InOrder inOrder = inOrder(socket); - inOrder.verify(socket).setSoTimeout(42); - inOrder.verify(socket).setSoTimeout(0); - } + // then + InOrder inOrder = inOrder(socket); + inOrder.verify(socket).setSoTimeout(42); + inOrder.verify(socket).setSoTimeout(0); + } - private void awaitAtLeastOneEventToBeDispatched() throws IOException { - verify(objectWriter, timeout(TIMEOUT)).write(anyString()); - } + private void awaitAtLeastOneEventToBeDispatched() throws IOException { + verify(objectWriter, timeout(TIMEOUT)).write(anyString()); + } - private void awaitStartOfEventDispatching() throws InterruptedException { - verify(deque, timeout(TIMEOUT)).takeFirst(); - } + private void awaitStartOfEventDispatching() throws InterruptedException { + verify(deque, timeout(TIMEOUT)).takeFirst(); + } - private void mockOneSuccessfulSocketConnection() throws InterruptedException { - doReturn(socket).doReturn(null).when(socketConnector).call(); - } + private void mockOneSuccessfulSocketConnection() throws InterruptedException { + doReturn(socket).doReturn(null).when(socketConnector).call(); + } - private void mockTwoSuccessfulSocketConnections() throws InterruptedException { - doReturn(socket).doReturn(socket).doReturn(null).when(socketConnector).call(); - } + private void mockTwoSuccessfulSocketConnections() throws InterruptedException { + doReturn(socket).doReturn(socket).doReturn(null).when(socketConnector).call(); + } - private static class InstrumentedSocketAppender extends AbstractSocketAppender { + private static class InstrumentedSocketAppender extends AbstractSocketAppender { - private PreSerializationTransformer preSerializationTransformer; - private SocketConnector socketConnector; + private PreSerializationTransformer preSerializationTransformer; + private SocketConnector socketConnector; - public InstrumentedSocketAppender(PreSerializationTransformer preSerializationTransformer, - QueueFactory queueFactory, - ObjectWriterFactory objectWriterFactory, - SocketConnector socketConnector) { - super(queueFactory, objectWriterFactory); - this.preSerializationTransformer = preSerializationTransformer; - this.socketConnector = socketConnector; - } + public InstrumentedSocketAppender(PreSerializationTransformer preSerializationTransformer, QueueFactory queueFactory, + ObjectWriterFactory objectWriterFactory, SocketConnector socketConnector) { + super(queueFactory, objectWriterFactory); + this.preSerializationTransformer = preSerializationTransformer; + this.socketConnector = socketConnector; + } - @Override - protected void postProcessEvent(String event) { - } + @Override + protected void postProcessEvent(String event) { + } - @Override - protected PreSerializationTransformer getPST() { - return preSerializationTransformer; - } + @Override + protected PreSerializationTransformer getPST() { + return preSerializationTransformer; + } - @Override - protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) { - return socketConnector; + @Override + protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) { + return socketConnector; + } } - } - private static class StringPreSerializationTransformer implements PreSerializationTransformer { + private static class StringPreSerializationTransformer implements PreSerializationTransformer { - @Override - public Serializable transform(String event) { - return event; + @Override + public Serializable transform(String event) { + return event; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java index dd1140bc6d39d20877d0c1c631bd69d46256d83d..010ce42454ebdf4676e04448666e8bcb8b221355 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java @@ -30,84 +30,84 @@ import static org.mockito.Mockito.verify; */ public class AutoFlushingObjectWriterTest { - private InstrumentedObjectOutputStream objectOutputStream; + private InstrumentedObjectOutputStream objectOutputStream; - @Before - public void beforeEachTest() throws IOException { - objectOutputStream = spy(new InstrumentedObjectOutputStream()); - } - - @Test - public void writesToUnderlyingObjectOutputStream() throws IOException { - - // given - ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); - String object = "foo"; - - // when - objectWriter.write(object); + @Before + public void beforeEachTest() throws IOException { + objectOutputStream = spy(new InstrumentedObjectOutputStream()); + } - // then - verify(objectOutputStream).writeObjectOverride(object); - } + @Test + public void writesToUnderlyingObjectOutputStream() throws IOException { - @Test - public void flushesAfterWrite() throws IOException { + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; - // given - ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); - String object = "foo"; + // when + objectWriter.write(object); - // when - objectWriter.write(object); + // then + verify(objectOutputStream).writeObjectOverride(object); + } - // then - InOrder inOrder = inOrder(objectOutputStream); - inOrder.verify(objectOutputStream).writeObjectOverride(object); - inOrder.verify(objectOutputStream).flush(); - } + @Test + public void flushesAfterWrite() throws IOException { - @Test - public void resetsObjectOutputStreamAccordingToGivenResetFrequency() throws IOException { + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; - // given - ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); - String object = "foo"; + // when + objectWriter.write(object); - // when - objectWriter.write(object); - objectWriter.write(object); - objectWriter.write(object); - objectWriter.write(object); + // then + InOrder inOrder = inOrder(objectOutputStream); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).flush(); + } - // then - InOrder inOrder = inOrder(objectOutputStream); - inOrder.verify(objectOutputStream).writeObjectOverride(object); - inOrder.verify(objectOutputStream).writeObjectOverride(object); - inOrder.verify(objectOutputStream).reset(); - inOrder.verify(objectOutputStream).writeObjectOverride(object); - inOrder.verify(objectOutputStream).writeObjectOverride(object); - inOrder.verify(objectOutputStream).reset(); - } + @Test + public void resetsObjectOutputStreamAccordingToGivenResetFrequency() throws IOException { + + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; + + // when + objectWriter.write(object); + objectWriter.write(object); + objectWriter.write(object); + objectWriter.write(object); + + // then + InOrder inOrder = inOrder(objectOutputStream); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).reset(); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).reset(); + } - private static class InstrumentedObjectOutputStream extends ObjectOutputStream { + private static class InstrumentedObjectOutputStream extends ObjectOutputStream { - protected InstrumentedObjectOutputStream() throws IOException, SecurityException { - } + protected InstrumentedObjectOutputStream() throws IOException, SecurityException { + } - @Override - protected void writeObjectOverride(final Object obj) throws IOException { - // nop - } + @Override + protected void writeObjectOverride(final Object obj) throws IOException { + // nop + } - @Override - public void flush() throws IOException { - // nop - } + @Override + public void flush() throws IOException { + // nop + } - @Override - public void reset() throws IOException { - // nop + @Override + public void reset() throws IOException { + // nop + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/DefaultSocketConnectorTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/DefaultSocketConnectorTest.java index 41a9af1f9dba87dda5628002aaa4a4470ff42636..ecea0a5529dca41c57a97a01e6252f821a938046 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/DefaultSocketConnectorTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/DefaultSocketConnectorTest.java @@ -39,7 +39,6 @@ import static org.junit.Assert.fail; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - /** * Unit tests for {@link DefaultSocketConnector}. * @@ -47,126 +46,123 @@ import static org.junit.Assert.assertTrue; */ public class DefaultSocketConnectorTest { - private static final int DELAY = 1000; - private static final int SHORT_DELAY = 10; - private static final int RETRY_DELAY = 10; - - private MockExceptionHandler exceptionHandler = new MockExceptionHandler(); - - private ServerSocket serverSocket; - private DefaultSocketConnector connector; - - ExecutorService executor = Executors.newSingleThreadExecutor(); - - @Before - public void setUp() throws Exception { - serverSocket = ServerSocketUtil.createServerSocket(); - connector = new DefaultSocketConnector(serverSocket.getInetAddress(), - serverSocket.getLocalPort(), 0, RETRY_DELAY); - connector.setExceptionHandler(exceptionHandler); - } - - @After - public void tearDown() throws Exception { - if (serverSocket != null) { - serverSocket.close(); + private static final int DELAY = 1000; + private static final int SHORT_DELAY = 10; + private static final int RETRY_DELAY = 10; + + private MockExceptionHandler exceptionHandler = new MockExceptionHandler(); + + private ServerSocket serverSocket; + private DefaultSocketConnector connector; + + ExecutorService executor = Executors.newSingleThreadExecutor(); + + @Before + public void setUp() throws Exception { + serverSocket = ServerSocketUtil.createServerSocket(); + connector = new DefaultSocketConnector(serverSocket.getInetAddress(), serverSocket.getLocalPort(), 0, RETRY_DELAY); + connector.setExceptionHandler(exceptionHandler); } - } - - @Test - public void testConnect() throws Exception { - Future connectorTask = executor.submit(connector); - - Socket socket = connectorTask.get(2 * DELAY, TimeUnit.MILLISECONDS); - assertNotNull(socket); - connectorTask.cancel(true); - - assertTrue(connectorTask.isDone()); - socket.close(); - } - - @Test - public void testConnectionFails() throws Exception { - serverSocket.close(); - Future connectorTask = executor.submit(connector); - - // this connection attempt will always timeout - try { - connectorTask.get(SHORT_DELAY, TimeUnit.MILLISECONDS); - fail(); - } catch(TimeoutException e) { + + @After + public void tearDown() throws Exception { + if (serverSocket != null) { + serverSocket.close(); + } } - Exception lastException = exceptionHandler.awaitConnectionFailed(DELAY); - assertTrue(lastException instanceof ConnectException); - assertFalse(connectorTask.isDone()); - connectorTask.cancel(true); - - //thread.join(4 * DELAY); - assertTrue(connectorTask.isCancelled()); - } - - @Test(timeout = 5000) - public void testConnectEventually() throws Exception { - serverSocket.close(); - - Future connectorTask = executor.submit(connector); - // this connection attempt will always timeout - try { - connectorTask.get(SHORT_DELAY, TimeUnit.MILLISECONDS); - fail(); - } catch(TimeoutException e) { + + @Test + public void testConnect() throws Exception { + Future connectorTask = executor.submit(connector); + + Socket socket = connectorTask.get(2 * DELAY, TimeUnit.MILLISECONDS); + assertNotNull(socket); + connectorTask.cancel(true); + + assertTrue(connectorTask.isDone()); + socket.close(); } + @Test + public void testConnectionFails() throws Exception { + serverSocket.close(); + Future connectorTask = executor.submit(connector); - // on Ceki's machine (Windows 7) this always takes 1second regardless of the value of DELAY - Exception lastException = exceptionHandler.awaitConnectionFailed(DELAY); - assertNotNull(lastException); - assertTrue(lastException instanceof ConnectException); + // this connection attempt will always timeout + try { + connectorTask.get(SHORT_DELAY, TimeUnit.MILLISECONDS); + fail(); + } catch (TimeoutException e) { + } + Exception lastException = exceptionHandler.awaitConnectionFailed(DELAY); + assertTrue(lastException instanceof ConnectException); + assertFalse(connectorTask.isDone()); + connectorTask.cancel(true); - // now rebind to the same local address - SocketAddress address = serverSocket.getLocalSocketAddress(); - serverSocket = new ServerSocket(); - serverSocket.setReuseAddress(true); - serverSocket.bind(address); + // thread.join(4 * DELAY); + assertTrue(connectorTask.isCancelled()); + } - // now we should be able to connect - Socket socket = connectorTask.get(2 * DELAY, TimeUnit.MILLISECONDS); + @Test(timeout = 5000) + public void testConnectEventually() throws Exception { + serverSocket.close(); - assertNotNull(socket); + Future connectorTask = executor.submit(connector); + // this connection attempt will always timeout + try { + connectorTask.get(SHORT_DELAY, TimeUnit.MILLISECONDS); + fail(); + } catch (TimeoutException e) { + } + + // on Ceki's machine (Windows 7) this always takes 1second regardless of the value of DELAY + Exception lastException = exceptionHandler.awaitConnectionFailed(DELAY); + assertNotNull(lastException); + assertTrue(lastException instanceof ConnectException); + + // now rebind to the same local address + SocketAddress address = serverSocket.getLocalSocketAddress(); + serverSocket = new ServerSocket(); + serverSocket.setReuseAddress(true); + serverSocket.bind(address); - assertFalse(connectorTask.isCancelled()); - socket.close(); - } - - private static class MockExceptionHandler implements ExceptionHandler { + // now we should be able to connect + Socket socket = connectorTask.get(2 * DELAY, TimeUnit.MILLISECONDS); - private final Lock lock = new ReentrantLock(); - private final Condition failedCondition = lock.newCondition(); - - private Exception lastException; - - public void connectionFailed(SocketConnector connector, Exception ex) { - lastException = ex; + assertNotNull(socket); + + assertFalse(connectorTask.isCancelled()); + socket.close(); } - - public Exception awaitConnectionFailed(long delay) - throws InterruptedException { - lock.lock(); - try { - long increment = 10; - while (lastException == null && delay > 0) { - boolean success = failedCondition.await(increment, TimeUnit.MILLISECONDS); - delay -= increment; - if(success) break; + private static class MockExceptionHandler implements ExceptionHandler { + + private final Lock lock = new ReentrantLock(); + private final Condition failedCondition = lock.newCondition(); + + private Exception lastException; + + public void connectionFailed(SocketConnector connector, Exception ex) { + lastException = ex; + } + + public Exception awaitConnectionFailed(long delay) throws InterruptedException { + lock.lock(); + try { + long increment = 10; + while (lastException == null && delay > 0) { + boolean success = failedCondition.await(increment, TimeUnit.MILLISECONDS); + delay -= increment; + if (success) + break; + + } + return lastException; + } finally { + lock.unlock(); + } } - return lastException; - } - finally { - lock.unlock(); - } + } - - } - + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/PackageTest.java index 7be4a3167746b0f1658084ef7de04904c86a5378..45a8d7cd6c10cedbbf586be631d19cadb2aa2318 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/PackageTest.java @@ -16,12 +16,8 @@ package ch.qos.logback.core.net; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({AbstractSocketAppenderTest.class, - DefaultSocketConnectorTest.class, - AbstractSSLSocketAppenderTest.class, - ch.qos.logback.core.net.server.PackageTest.class, - ch.qos.logback.core.net.ssl.PackageTest.class}) +@Suite.SuiteClasses({ AbstractSocketAppenderTest.class, DefaultSocketConnectorTest.class, AbstractSSLSocketAppenderTest.class, + ch.qos.logback.core.net.server.PackageTest.class, ch.qos.logback.core.net.ssl.PackageTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/SyslogAppenderBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/SyslogAppenderBaseTest.java index 982c1af4dcc5564e2a41afb01b78127e2e317156..4aee9d8271b72ac347063fa662f81b46d87840b7 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/SyslogAppenderBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/SyslogAppenderBaseTest.java @@ -17,34 +17,32 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class SyslogAppenderBaseTest -{ - @Test - public void testFacilityStringToint() throws InterruptedException - { - assertEquals(SyslogConstants.LOG_KERN, SyslogAppenderBase.facilityStringToint("KERN")); - assertEquals(SyslogConstants.LOG_USER, SyslogAppenderBase.facilityStringToint("USER")); - assertEquals(SyslogConstants.LOG_MAIL, SyslogAppenderBase.facilityStringToint("MAIL")); - assertEquals(SyslogConstants.LOG_DAEMON, SyslogAppenderBase.facilityStringToint("DAEMON")); - assertEquals(SyslogConstants.LOG_AUTH, SyslogAppenderBase.facilityStringToint("AUTH")); - assertEquals(SyslogConstants.LOG_SYSLOG, SyslogAppenderBase.facilityStringToint("SYSLOG")); - assertEquals(SyslogConstants.LOG_LPR, SyslogAppenderBase.facilityStringToint("LPR")); - assertEquals(SyslogConstants.LOG_NEWS, SyslogAppenderBase.facilityStringToint("NEWS")); - assertEquals(SyslogConstants.LOG_UUCP, SyslogAppenderBase.facilityStringToint("UUCP")); - assertEquals(SyslogConstants.LOG_CRON, SyslogAppenderBase.facilityStringToint("CRON")); - assertEquals(SyslogConstants.LOG_AUTHPRIV, SyslogAppenderBase.facilityStringToint("AUTHPRIV")); - assertEquals(SyslogConstants.LOG_FTP, SyslogAppenderBase.facilityStringToint("FTP")); - assertEquals(SyslogConstants.LOG_NTP, SyslogAppenderBase.facilityStringToint("NTP")); - assertEquals(SyslogConstants.LOG_AUDIT, SyslogAppenderBase.facilityStringToint("AUDIT")); - assertEquals(SyslogConstants.LOG_ALERT, SyslogAppenderBase.facilityStringToint("ALERT")); - assertEquals(SyslogConstants.LOG_CLOCK, SyslogAppenderBase.facilityStringToint("CLOCK")); - assertEquals(SyslogConstants.LOG_LOCAL0, SyslogAppenderBase.facilityStringToint("LOCAL0")); - assertEquals(SyslogConstants.LOG_LOCAL1, SyslogAppenderBase.facilityStringToint("LOCAL1")); - assertEquals(SyslogConstants.LOG_LOCAL2, SyslogAppenderBase.facilityStringToint("LOCAL2")); - assertEquals(SyslogConstants.LOG_LOCAL3, SyslogAppenderBase.facilityStringToint("LOCAL3")); - assertEquals(SyslogConstants.LOG_LOCAL4, SyslogAppenderBase.facilityStringToint("LOCAL4")); - assertEquals(SyslogConstants.LOG_LOCAL5, SyslogAppenderBase.facilityStringToint("LOCAL5")); - assertEquals(SyslogConstants.LOG_LOCAL6, SyslogAppenderBase.facilityStringToint("LOCAL6")); - assertEquals(SyslogConstants.LOG_LOCAL7, SyslogAppenderBase.facilityStringToint("LOCAL7")); - } +public class SyslogAppenderBaseTest { + @Test + public void testFacilityStringToint() throws InterruptedException { + assertEquals(SyslogConstants.LOG_KERN, SyslogAppenderBase.facilityStringToint("KERN")); + assertEquals(SyslogConstants.LOG_USER, SyslogAppenderBase.facilityStringToint("USER")); + assertEquals(SyslogConstants.LOG_MAIL, SyslogAppenderBase.facilityStringToint("MAIL")); + assertEquals(SyslogConstants.LOG_DAEMON, SyslogAppenderBase.facilityStringToint("DAEMON")); + assertEquals(SyslogConstants.LOG_AUTH, SyslogAppenderBase.facilityStringToint("AUTH")); + assertEquals(SyslogConstants.LOG_SYSLOG, SyslogAppenderBase.facilityStringToint("SYSLOG")); + assertEquals(SyslogConstants.LOG_LPR, SyslogAppenderBase.facilityStringToint("LPR")); + assertEquals(SyslogConstants.LOG_NEWS, SyslogAppenderBase.facilityStringToint("NEWS")); + assertEquals(SyslogConstants.LOG_UUCP, SyslogAppenderBase.facilityStringToint("UUCP")); + assertEquals(SyslogConstants.LOG_CRON, SyslogAppenderBase.facilityStringToint("CRON")); + assertEquals(SyslogConstants.LOG_AUTHPRIV, SyslogAppenderBase.facilityStringToint("AUTHPRIV")); + assertEquals(SyslogConstants.LOG_FTP, SyslogAppenderBase.facilityStringToint("FTP")); + assertEquals(SyslogConstants.LOG_NTP, SyslogAppenderBase.facilityStringToint("NTP")); + assertEquals(SyslogConstants.LOG_AUDIT, SyslogAppenderBase.facilityStringToint("AUDIT")); + assertEquals(SyslogConstants.LOG_ALERT, SyslogAppenderBase.facilityStringToint("ALERT")); + assertEquals(SyslogConstants.LOG_CLOCK, SyslogAppenderBase.facilityStringToint("CLOCK")); + assertEquals(SyslogConstants.LOG_LOCAL0, SyslogAppenderBase.facilityStringToint("LOCAL0")); + assertEquals(SyslogConstants.LOG_LOCAL1, SyslogAppenderBase.facilityStringToint("LOCAL1")); + assertEquals(SyslogConstants.LOG_LOCAL2, SyslogAppenderBase.facilityStringToint("LOCAL2")); + assertEquals(SyslogConstants.LOG_LOCAL3, SyslogAppenderBase.facilityStringToint("LOCAL3")); + assertEquals(SyslogConstants.LOG_LOCAL4, SyslogAppenderBase.facilityStringToint("LOCAL4")); + assertEquals(SyslogConstants.LOG_LOCAL5, SyslogAppenderBase.facilityStringToint("LOCAL5")); + assertEquals(SyslogConstants.LOG_LOCAL6, SyslogAppenderBase.facilityStringToint("LOCAL6")); + assertEquals(SyslogConstants.LOG_LOCAL7, SyslogAppenderBase.facilityStringToint("LOCAL7")); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockContext.java b/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockContext.java index 51e642363c8e512a1f2402cea0c0f3f76957553b..197848bbfc403efc56fd3b68860477d8d8cf297c 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockContext.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockContext.java @@ -29,62 +29,62 @@ import ch.qos.logback.core.status.StatusManager; */ public class MockContext extends ContextBase { - private final ExecutorService executorService; - - private Status lastStatus; - - public MockContext() { - this(new MockExecutorService()); - } - - public MockContext(ExecutorService executorService) { - this.setStatusManager(new MockStatusManager()); - this.executorService = executorService; - } - - @Override - public ExecutorService getExecutorService() { - return executorService; - } - - public Status getLastStatus() { - return lastStatus; - } - - public void setLastStatus(Status lastStatus) { - this.lastStatus = lastStatus; - } - - private class MockStatusManager implements StatusManager { - - public void add(Status status) { - lastStatus = status; - } + private final ExecutorService executorService; + + private Status lastStatus; - public List getCopyOfStatusList() { - throw new UnsupportedOperationException(); + public MockContext() { + this(new MockExecutorService()); } - public int getCount() { - throw new UnsupportedOperationException(); + public MockContext(ExecutorService executorService) { + this.setStatusManager(new MockStatusManager()); + this.executorService = executorService; } - public boolean add(StatusListener listener) { - throw new UnsupportedOperationException(); + @Override + public ExecutorService getExecutorService() { + return executorService; } - public void remove(StatusListener listener) { - throw new UnsupportedOperationException(); + public Status getLastStatus() { + return lastStatus; } - public void clear() { - throw new UnsupportedOperationException(); + public void setLastStatus(Status lastStatus) { + this.lastStatus = lastStatus; } - public List getCopyOfStatusListenerList() { - throw new UnsupportedOperationException(); + private class MockStatusManager implements StatusManager { + + public void add(Status status) { + lastStatus = status; + } + + public List getCopyOfStatusList() { + throw new UnsupportedOperationException(); + } + + public int getCount() { + throw new UnsupportedOperationException(); + } + + public boolean add(StatusListener listener) { + throw new UnsupportedOperationException(); + } + + public void remove(StatusListener listener) { + throw new UnsupportedOperationException(); + } + + public void clear() { + throw new UnsupportedOperationException(); + } + + public List getCopyOfStatusListenerList() { + throw new UnsupportedOperationException(); + } + } - - } - + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockExecutorService.java b/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockExecutorService.java index 465b015a27c7946fdbd5551cbb65d08a07b426ad..60d95be6b7622177a0afb8606de0a78ea471f762 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockExecutorService.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/mock/MockExecutorService.java @@ -27,35 +27,34 @@ import java.util.concurrent.TimeUnit; */ public class MockExecutorService extends AbstractExecutorService { - private Runnable lastCommand; - - public Runnable getLastCommand() { - return lastCommand; - } - - public void shutdown() { - } - - public List shutdownNow() { - return Collections.emptyList(); - } - - public boolean isShutdown() { - return true; - } - - public boolean isTerminated() { - return true; - } - - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException { - return true; - } - - public void execute(Runnable command) { - command.run(); - lastCommand = command; - } - + private Runnable lastCommand; + + public Runnable getLastCommand() { + return lastCommand; + } + + public void shutdown() { + } + + public List shutdownNow() { + return Collections.emptyList(); + } + + public boolean isShutdown() { + return true; + } + + public boolean isTerminated() { + return true; + } + + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return true; + } + + public void execute(Runnable command) { + command.run(); + lastCommand = command; + } + } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/AbstractServerSocketAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/AbstractServerSocketAppenderTest.java index 9d67a7c4d53a2168250c39ed3e79c1e36da9cd5c..9b065d4710d2f0bc44a9184c35bb9835403a99eb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/AbstractServerSocketAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/AbstractServerSocketAppenderTest.java @@ -37,67 +37,64 @@ import ch.qos.logback.core.status.Status; */ public class AbstractServerSocketAppenderTest { + private MockContext context = new MockContext(); - private MockContext context = new MockContext(); - - private MockServerRunner runner = - new MockServerRunner(); - - private MockServerListener listener = - new MockServerListener(); - - private ServerSocket serverSocket; - private InstrumentedServerSocketAppenderBase appender; - - @Before - public void setUp() throws Exception { - serverSocket = ServerSocketUtil.createServerSocket(); - appender = new InstrumentedServerSocketAppenderBase(serverSocket, listener, runner); - appender.setContext(context); - } - - @After - public void tearDown() throws Exception { - serverSocket.close(); - } - - @Test - public void testStartStop() throws Exception { - appender.start(); - assertTrue(runner.isContextInjected()); - assertTrue(runner.isRunning()); - assertSame(listener, appender.getLastListener()); - - appender.stop(); - assertFalse(runner.isRunning()); - } - - @Test - public void testStartWhenAlreadyStarted() throws Exception { - appender.start(); - appender.start(); - assertEquals(1, runner.getStartCount()); - } - - @Test - public void testStopThrowsException() throws Exception { - appender.start(); - assertTrue(appender.isStarted()); - IOException ex = new IOException("test exception"); - runner.setStopException(ex); - appender.stop(); - - Status status = context.getLastStatus(); - assertNotNull(status); - assertTrue(status instanceof ErrorStatus); - assertTrue(status.getMessage().contains(ex.getMessage())); - assertSame(ex, status.getThrowable()); - } - - @Test - public void testStopWhenNotStarted() throws Exception { - appender.stop(); - assertEquals(0, runner.getStartCount()); - } + private MockServerRunner runner = new MockServerRunner(); + + private MockServerListener listener = new MockServerListener(); + + private ServerSocket serverSocket; + private InstrumentedServerSocketAppenderBase appender; + + @Before + public void setUp() throws Exception { + serverSocket = ServerSocketUtil.createServerSocket(); + appender = new InstrumentedServerSocketAppenderBase(serverSocket, listener, runner); + appender.setContext(context); + } + + @After + public void tearDown() throws Exception { + serverSocket.close(); + } + + @Test + public void testStartStop() throws Exception { + appender.start(); + assertTrue(runner.isContextInjected()); + assertTrue(runner.isRunning()); + assertSame(listener, appender.getLastListener()); + + appender.stop(); + assertFalse(runner.isRunning()); + } + + @Test + public void testStartWhenAlreadyStarted() throws Exception { + appender.start(); + appender.start(); + assertEquals(1, runner.getStartCount()); + } + + @Test + public void testStopThrowsException() throws Exception { + appender.start(); + assertTrue(appender.isStarted()); + IOException ex = new IOException("test exception"); + runner.setStopException(ex); + appender.stop(); + + Status status = context.getLastStatus(); + assertNotNull(status); + assertTrue(status instanceof ErrorStatus); + assertTrue(status.getMessage().contains(ex.getMessage())); + assertSame(ex, status.getThrowable()); + } + + @Test + public void testStopWhenNotStarted() throws Exception { + appender.stop(); + assertEquals(0, runner.getStartCount()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/ConcurrentServerRunnerTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/ConcurrentServerRunnerTest.java index 72a11294a2cb9c170710600b44acdfdd4d7ffca0..8431a926c14e0ed780d93bd57058a4df43d61239 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/ConcurrentServerRunnerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/ConcurrentServerRunnerTest.java @@ -32,142 +32,133 @@ import org.junit.Test; import ch.qos.logback.core.net.mock.MockContext; - public class ConcurrentServerRunnerTest { - private static final int DELAY = 10000; - private static final int SHORT_DELAY = 10; - - private MockContext context = new MockContext(); - private MockServerListener listener = - new MockServerListener(); - - private ExecutorService executor = Executors.newCachedThreadPool(); - private InstrumentedConcurrentServerRunner runner = - new InstrumentedConcurrentServerRunner(listener, executor); - - @Before - public void setUp() throws Exception { - runner.setContext(context); - } - - @After - public void tearDown() throws Exception { - executor.shutdownNow(); - assertTrue(executor.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); - } - - @Test - public void testStartStop() throws Exception { - assertFalse(runner.isRunning()); - executor.execute(runner); - assertTrue(runner.awaitRunState(true, DELAY)); - int retries = DELAY / SHORT_DELAY; - synchronized (listener) { - while (retries-- > 0 && listener.getWaiter() == null) { - listener.wait(SHORT_DELAY); - } + private static final int DELAY = 10000; + private static final int SHORT_DELAY = 10; + + private MockContext context = new MockContext(); + private MockServerListener listener = new MockServerListener(); + + private ExecutorService executor = Executors.newCachedThreadPool(); + private InstrumentedConcurrentServerRunner runner = new InstrumentedConcurrentServerRunner(listener, executor); + + @Before + public void setUp() throws Exception { + runner.setContext(context); } - assertNotNull(listener.getWaiter()); - runner.stop(); - assertTrue(listener.isClosed()); - assertFalse(runner.awaitRunState(false, DELAY)); - } - - @Test - public void testRunOneClient() throws Exception { - executor.execute(runner); - MockClient client = new MockClient(); - listener.addClient(client); - int retries = DELAY / SHORT_DELAY; - synchronized (client) { - while (retries-- > 0 && !client.isRunning()) { - client.wait(SHORT_DELAY); - } + + @After + public void tearDown() throws Exception { + executor.shutdownNow(); + assertTrue(executor.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); } - assertTrue(runner.awaitRunState(true, DELAY)); - client.close(); - runner.stop(); - } - - @Test - public void testRunManyClients() throws Exception { - executor.execute(runner); - int count = 10; - while (count-- > 0) { - MockClient client = new MockClient(); - listener.addClient(client); - int retries = DELAY / SHORT_DELAY; - synchronized (client) { - while (retries-- > 0 && !client.isRunning()) { - client.wait(SHORT_DELAY); + + @Test + public void testStartStop() throws Exception { + assertFalse(runner.isRunning()); + executor.execute(runner); + assertTrue(runner.awaitRunState(true, DELAY)); + int retries = DELAY / SHORT_DELAY; + synchronized (listener) { + while (retries-- > 0 && listener.getWaiter() == null) { + listener.wait(SHORT_DELAY); + } } - } - assertTrue(runner.awaitRunState(true, DELAY)); - } - runner.stop(); - } - - @Test - public void testRunClientAndVisit() throws Exception { - executor.execute(runner); - MockClient client = new MockClient(); - listener.addClient(client); - int retries = DELAY / SHORT_DELAY; - synchronized (client) { - while (retries-- > 0 && !client.isRunning()) { - client.wait(SHORT_DELAY); - } + assertNotNull(listener.getWaiter()); + runner.stop(); + assertTrue(listener.isClosed()); + assertFalse(runner.awaitRunState(false, DELAY)); } - assertTrue(runner.awaitRunState(true, DELAY)); - MockClientVisitor visitor = new MockClientVisitor(); - runner.accept(visitor); - assertSame(client, visitor.getLastVisited()); - runner.stop(); - } - - - static class InstrumentedConcurrentServerRunner - extends ConcurrentServerRunner { - - private final Lock lock = new ReentrantLock(); - private final Condition runningCondition = lock.newCondition(); - - public InstrumentedConcurrentServerRunner( - ServerListener listener, Executor executor) { - super(listener, executor); + + @Test + public void testRunOneClient() throws Exception { + executor.execute(runner); + MockClient client = new MockClient(); + listener.addClient(client); + int retries = DELAY / SHORT_DELAY; + synchronized (client) { + while (retries-- > 0 && !client.isRunning()) { + client.wait(SHORT_DELAY); + } + } + assertTrue(runner.awaitRunState(true, DELAY)); + client.close(); + runner.stop(); } - @Override - protected boolean configureClient(MockClient client) { - return true; + @Test + public void testRunManyClients() throws Exception { + executor.execute(runner); + int count = 10; + while (count-- > 0) { + MockClient client = new MockClient(); + listener.addClient(client); + int retries = DELAY / SHORT_DELAY; + synchronized (client) { + while (retries-- > 0 && !client.isRunning()) { + client.wait(SHORT_DELAY); + } + } + assertTrue(runner.awaitRunState(true, DELAY)); + } + runner.stop(); } - @Override - protected void setRunning(boolean running) { - lock.lock(); - try { - super.setRunning(running); - runningCondition.signalAll(); - } - finally { - lock.unlock(); - } + @Test + public void testRunClientAndVisit() throws Exception { + executor.execute(runner); + MockClient client = new MockClient(); + listener.addClient(client); + int retries = DELAY / SHORT_DELAY; + synchronized (client) { + while (retries-- > 0 && !client.isRunning()) { + client.wait(SHORT_DELAY); + } + } + assertTrue(runner.awaitRunState(true, DELAY)); + MockClientVisitor visitor = new MockClientVisitor(); + runner.accept(visitor); + assertSame(client, visitor.getLastVisited()); + runner.stop(); } - public boolean awaitRunState(boolean state, - long delay) throws InterruptedException { - lock.lock(); - try { - while (isRunning() != state) { - runningCondition.await(delay, TimeUnit.MILLISECONDS); + static class InstrumentedConcurrentServerRunner extends ConcurrentServerRunner { + + private final Lock lock = new ReentrantLock(); + private final Condition runningCondition = lock.newCondition(); + + public InstrumentedConcurrentServerRunner(ServerListener listener, Executor executor) { + super(listener, executor); + } + + @Override + protected boolean configureClient(MockClient client) { + return true; + } + + @Override + protected void setRunning(boolean running) { + lock.lock(); + try { + super.setRunning(running); + runningCondition.signalAll(); + } finally { + lock.unlock(); + } + } + + public boolean awaitRunState(boolean state, long delay) throws InterruptedException { + lock.lock(); + try { + while (isRunning() != state) { + runningCondition.await(delay, TimeUnit.MILLISECONDS); + } + return isRunning(); + } finally { + lock.unlock(); + } } - return isRunning(); - } - finally { - lock.unlock(); - } } - } - + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/InstrumentedServerSocketAppenderBase.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/InstrumentedServerSocketAppenderBase.java index 5828b530825edd712cea32b5a48a662b9c0b73f4..df6dc1d4c144b0feb1f0c542c360baa00e5a12dd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/InstrumentedServerSocketAppenderBase.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/InstrumentedServerSocketAppenderBase.java @@ -28,78 +28,72 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; * * @author Carl Harris */ -public class InstrumentedServerSocketAppenderBase - extends AbstractServerSocketAppender { - - private final ServerSocket serverSocket; - private final ServerListener listener; - private final ServerRunner runner; - - private ServerListener lastListener; - - public InstrumentedServerSocketAppenderBase(ServerSocket serverSocket) { - this(serverSocket, new RemoteReceiverServerListener(serverSocket), null); - } - - public InstrumentedServerSocketAppenderBase(ServerSocket serverSocket, - ServerListener listener, - ServerRunner runner) { - this.serverSocket = serverSocket; - this.listener = listener; - this.runner = runner; - } - - @Override - protected void postProcessEvent(Serializable event) { - } - - @Override - protected PreSerializationTransformer getPST() { - return new PreSerializationTransformer() { - public Serializable transform(Serializable event) { - return event; - } - }; - } - - @Override - protected ServerSocketFactory getServerSocketFactory() throws Exception { - return new ServerSocketFactory() { - - @Override - public ServerSocket createServerSocket(int port) throws IOException { - return serverSocket; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog) - throws IOException { - return serverSocket; - } - - @Override - public ServerSocket createServerSocket(int port, int backlog, - InetAddress ifAddress) throws IOException { - return serverSocket; - } - }; - } - - @Override - protected ServerRunner createServerRunner( - ServerListener listener, Executor executor) { - lastListener = listener; - return runner != null ? runner : super.createServerRunner(listener, executor); - } - - @Override - protected ServerListener createServerListener( - ServerSocket socket) { - return listener; - } - - public ServerListener getLastListener() { - return lastListener; - } +public class InstrumentedServerSocketAppenderBase extends AbstractServerSocketAppender { + + private final ServerSocket serverSocket; + private final ServerListener listener; + private final ServerRunner runner; + + private ServerListener lastListener; + + public InstrumentedServerSocketAppenderBase(ServerSocket serverSocket) { + this(serverSocket, new RemoteReceiverServerListener(serverSocket), null); + } + + public InstrumentedServerSocketAppenderBase(ServerSocket serverSocket, ServerListener listener, + ServerRunner runner) { + this.serverSocket = serverSocket; + this.listener = listener; + this.runner = runner; + } + + @Override + protected void postProcessEvent(Serializable event) { + } + + @Override + protected PreSerializationTransformer getPST() { + return new PreSerializationTransformer() { + public Serializable transform(Serializable event) { + return event; + } + }; + } + + @Override + protected ServerSocketFactory getServerSocketFactory() throws Exception { + return new ServerSocketFactory() { + + @Override + public ServerSocket createServerSocket(int port) throws IOException { + return serverSocket; + } + + @Override + public ServerSocket createServerSocket(int port, int backlog) throws IOException { + return serverSocket; + } + + @Override + public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { + return serverSocket; + } + }; + } + + @Override + protected ServerRunner createServerRunner(ServerListener listener, Executor executor) { + lastListener = listener; + return runner != null ? runner : super.createServerRunner(listener, executor); + } + + @Override + protected ServerListener createServerListener(ServerSocket socket) { + return listener; + } + + public ServerListener getLastListener() { + return lastListener; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClient.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClient.java index a9abe6b3d7a78beb8858972db630f20ea49a12a2..8e4c4fd5fc835486ab5961a933ceb00b005020b2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClient.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClient.java @@ -15,8 +15,6 @@ package ch.qos.logback.core.net.server; import ch.qos.logback.core.net.server.Client; - - /** * * A mock {@link Client} that notifies waiting thread when it has started, @@ -26,38 +24,37 @@ import ch.qos.logback.core.net.server.Client; */ class MockClient implements Client { - private boolean running; - private boolean closed; - - public void run() { - synchronized (this) { - running = true; - notifyAll(); - while (running && !Thread.currentThread().isInterrupted()) { - try { - wait(); - } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); + private boolean running; + private boolean closed; + + public void run() { + synchronized (this) { + running = true; + notifyAll(); + while (running && !Thread.currentThread().isInterrupted()) { + try { + wait(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } } - } } - } - public void close() { - synchronized (this) { - running = false; - closed = true; - notifyAll(); + public void close() { + synchronized (this) { + running = false; + closed = true; + notifyAll(); + } } - } - public synchronized boolean isRunning() { - return running; - } + public synchronized boolean isRunning() { + return running; + } - public synchronized boolean isClosed() { - return closed; - } + public synchronized boolean isClosed() { + return closed; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClientVisitor.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClientVisitor.java index 858a4aeee7df075d7855be5f3a01eca2c2eea3ae..04ad208f173fa25ea1b6e12ff259a594216e83fd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClientVisitor.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockClientVisitor.java @@ -20,17 +20,17 @@ package ch.qos.logback.core.net.server; */ public class MockClientVisitor implements ClientVisitor { - private MockClient lastVisited; - - /** - * {@inheritDoc} - */ - public void visit(MockClient client) { - lastVisited = client; - } + private MockClient lastVisited; - public MockClient getLastVisited() { - return lastVisited; - } + /** + * {@inheritDoc} + */ + public void visit(MockClient client) { + lastVisited = client; + } + + public MockClient getLastVisited() { + return lastVisited; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockEventQueue.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockEventQueue.java index 39afb1b2c32114e88054a7932422708965b91047..eaa832140b428a15cd3a0465447fb0ed7ff60b42 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockEventQueue.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockEventQueue.java @@ -23,14 +23,14 @@ import java.util.concurrent.LinkedBlockingQueue; */ class MockEventQueue extends LinkedBlockingQueue { - private static final long serialVersionUID = 1L; - - @Override - public Serializable take() throws InterruptedException { - if (isEmpty()) { - Thread.currentThread().interrupt(); + private static final long serialVersionUID = 1L; + + @Override + public Serializable take() throws InterruptedException { + if (isEmpty()) { + Thread.currentThread().interrupt(); + } + return super.take(); } - return super.take(); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerListener.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerListener.java index d4e88b8fbc9a2a800641484ee2b7b13b6c3a4e16..ae7ecf794d4dc8de07237411b948d4711eceebfc 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerListener.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerListener.java @@ -20,7 +20,6 @@ import java.util.concurrent.LinkedBlockingQueue; import ch.qos.logback.core.net.server.Client; import ch.qos.logback.core.net.server.ServerListener; - /** * A mock {@link ServerListener} that has a blocking queue to pass a client * to a {@link #acceptClient()} caller. If the {@link #close()} method is @@ -31,51 +30,49 @@ import ch.qos.logback.core.net.server.ServerListener; */ public class MockServerListener implements ServerListener { - private final BlockingQueue queue = - new LinkedBlockingQueue(); - - private boolean closed; - private Thread waiter; - - public synchronized Thread getWaiter() { - return waiter; - } - - public synchronized void setWaiter(Thread waiter) { - this.waiter = waiter; - } - - public synchronized boolean isClosed() { - return closed; - } + private final BlockingQueue queue = new LinkedBlockingQueue(); + + private boolean closed; + private Thread waiter; + + public synchronized Thread getWaiter() { + return waiter; + } + + public synchronized void setWaiter(Thread waiter) { + this.waiter = waiter; + } - public synchronized void setClosed(boolean closed) { - this.closed = closed; - } + public synchronized boolean isClosed() { + return closed; + } - public T acceptClient() throws IOException, InterruptedException { - if (isClosed()) { - throw new IOException("closed"); + public synchronized void setClosed(boolean closed) { + this.closed = closed; } - setWaiter(Thread.currentThread()); - try { - return queue.take(); + + public T acceptClient() throws IOException, InterruptedException { + if (isClosed()) { + throw new IOException("closed"); + } + setWaiter(Thread.currentThread()); + try { + return queue.take(); + } finally { + setWaiter(null); + } } - finally { - setWaiter(null); + + public void addClient(T client) { + queue.offer(client); } - } - public void addClient(T client) { - queue.offer(client); - } - - public synchronized void close() { - setClosed(true); - Thread waiter = getWaiter(); - if (waiter != null) { - waiter.interrupt(); - } - } + public synchronized void close() { + setClosed(true); + Thread waiter = getWaiter(); + if (waiter != null) { + waiter.interrupt(); + } + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerRunner.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerRunner.java index 4d12e95da17c5e2b18304076918a39397efb3207..946cfafc63ce0dcb54a8cf67a3bf7e671485ce41 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerRunner.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/MockServerRunner.java @@ -23,48 +23,47 @@ import ch.qos.logback.core.spi.ContextAwareBase; * * @author Carl Harris */ -public class MockServerRunner extends ContextAwareBase - implements ServerRunner { +public class MockServerRunner extends ContextAwareBase implements ServerRunner { - private IOException stopException; - private int startCount; - private boolean contextInjected; - - @Override - public void setContext(Context context) { - contextInjected = true; - super.setContext(context); - } + private IOException stopException; + private int startCount; + private boolean contextInjected; - public void run() { - startCount++; - } + @Override + public void setContext(Context context) { + contextInjected = true; + super.setContext(context); + } + + public void run() { + startCount++; + } + + public void stop() throws IOException { + if (stopException != null) { + throw stopException; + } + startCount--; + } - public void stop() throws IOException { - if (stopException != null) { - throw stopException; + public boolean isRunning() { + return startCount > 0; } - startCount--; - } - public boolean isRunning() { - return startCount > 0; - } - - public void accept(ClientVisitor visitor) { - throw new UnsupportedOperationException(); - } + public void accept(ClientVisitor visitor) { + throw new UnsupportedOperationException(); + } - public int getStartCount() { - return startCount; - } + public int getStartCount() { + return startCount; + } - public boolean isContextInjected() { - return contextInjected; - } + public boolean isContextInjected() { + return contextInjected; + } + + public void setStopException(IOException stopException) { + this.stopException = stopException; + } - public void setStopException(IOException stopException) { - this.stopException = stopException; - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/PackageTest.java index 6d4001eebb032599897d16e4f8256b852a96e3ba..ae87f35013c9796547c0135e35d7c5cb9c8eb082 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/PackageTest.java @@ -16,12 +16,8 @@ package ch.qos.logback.core.net.server; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({ConcurrentServerRunnerTest.class, - RemoteReceiverStreamClientTest.class, - ServerSocketAppenderBaseFunctionalTest.class, - AbstractServerSocketAppenderTest.class, - SSLServerSocketAppenderBaseTest.class}) +@Suite.SuiteClasses({ ConcurrentServerRunnerTest.class, RemoteReceiverStreamClientTest.class, ServerSocketAppenderBaseFunctionalTest.class, + AbstractServerSocketAppenderTest.class, SSLServerSocketAppenderBaseTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClientTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClientTest.java index 7932486f650c0b194efcf6fe2a50c20353a2c5e0..12a3b66ea5bdb3049fa76eced49328ee0a2efe3c 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClientTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/RemoteReceiverStreamClientTest.java @@ -25,7 +25,6 @@ import org.junit.Test; import ch.qos.logback.core.net.mock.MockContext; - /** * Unit tests for {@link RemoteReceiverStreamClient}. * @@ -33,56 +32,52 @@ import ch.qos.logback.core.net.mock.MockContext; */ public class RemoteReceiverStreamClientTest { - private static final String TEST_EVENT = "test event"; - - private MockContext context = new MockContext(); - - private MockEventQueue queue = new MockEventQueue(); - - private ByteArrayOutputStream outputStream = - new ByteArrayOutputStream(); - - private RemoteReceiverStreamClient client = - new RemoteReceiverStreamClient("someId", outputStream); - - @Before - public void setUp() throws Exception { - client.setContext(context); - client.setQueue(queue); - } - - @Test - public void testOfferEventAndRun() throws Exception { - client.offer(TEST_EVENT); - - Thread thread = new Thread(client); - thread.start(); - - // MockEventQueue will interrupt the thread when the queue is drained - thread.join(1000); - assertFalse(thread.isAlive()); - - ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(outputStream.toByteArray())); - assertEquals(TEST_EVENT, ois.readObject()); - } - - @Test - public void testOfferEventSequenceAndRun() throws Exception { - for (int i = 0; i < 10; i++) { - client.offer(TEST_EVENT + i); + private static final String TEST_EVENT = "test event"; + + private MockContext context = new MockContext(); + + private MockEventQueue queue = new MockEventQueue(); + + private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + private RemoteReceiverStreamClient client = new RemoteReceiverStreamClient("someId", outputStream); + + @Before + public void setUp() throws Exception { + client.setContext(context); + client.setQueue(queue); } - Thread thread = new Thread(client); - thread.start(); - thread.join(1000); - assertFalse(thread.isAlive()); - - ObjectInputStream ois = new ObjectInputStream( - new ByteArrayInputStream(outputStream.toByteArray())); - for (int i = 0; i < 10; i++) { - assertEquals(TEST_EVENT + i, ois.readObject()); + @Test + public void testOfferEventAndRun() throws Exception { + client.offer(TEST_EVENT); + + Thread thread = new Thread(client); + thread.start(); + + // MockEventQueue will interrupt the thread when the queue is drained + thread.join(1000); + assertFalse(thread.isAlive()); + + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); + assertEquals(TEST_EVENT, ois.readObject()); + } + + @Test + public void testOfferEventSequenceAndRun() throws Exception { + for (int i = 0; i < 10; i++) { + client.offer(TEST_EVENT + i); + } + + Thread thread = new Thread(client); + thread.start(); + thread.join(1000); + assertFalse(thread.isAlive()); + + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); + for (int i = 0; i < 10; i++) { + assertEquals(TEST_EVENT + i, ois.readObject()); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBaseTest.java index a03b4e4dd1108fe4545bb192d7b16d97f54e7d20..1b47c9891af9a2706912324577a8b49e3273537a 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/SSLServerSocketAppenderBaseTest.java @@ -30,37 +30,35 @@ import ch.qos.logback.core.spi.PreSerializationTransformer; */ public class SSLServerSocketAppenderBaseTest { - private MockContext context = new MockContext(Executors.newCachedThreadPool()); - - private SSLServerSocketAppenderBase appender = - new InstrumentedSSLServerSocketAppenderBase(); - - @Before - public void setUp() throws Exception { - appender.setContext(context); - } - - @Test - public void testUsingDefaultConfig() throws Exception { - // should be able to start successfully with no SSL configuration at all - appender.start(); - assertNotNull(appender.getServerSocketFactory()); - appender.stop(); - } + private MockContext context = new MockContext(Executors.newCachedThreadPool()); - private static class InstrumentedSSLServerSocketAppenderBase - extends SSLServerSocketAppenderBase { + private SSLServerSocketAppenderBase appender = new InstrumentedSSLServerSocketAppenderBase(); - @Override - protected void postProcessEvent(Object event) { - throw new UnsupportedOperationException(); + @Before + public void setUp() throws Exception { + appender.setContext(context); } - @Override - protected PreSerializationTransformer getPST() { - throw new UnsupportedOperationException(); + @Test + public void testUsingDefaultConfig() throws Exception { + // should be able to start successfully with no SSL configuration at all + appender.start(); + assertNotNull(appender.getServerSocketFactory()); + appender.stop(); } - - } - + + private static class InstrumentedSSLServerSocketAppenderBase extends SSLServerSocketAppenderBase { + + @Override + protected void postProcessEvent(Object event) { + throw new UnsupportedOperationException(); + } + + @Override + protected PreSerializationTransformer getPST() { + throw new UnsupportedOperationException(); + } + + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketAppenderBaseFunctionalTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketAppenderBaseFunctionalTest.java index 32e0552781e7d0275655b9d92f680a36e923564c..b1c0dd8c23a0c9fa0ca303e3ecc8345c9a1baeab 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketAppenderBaseFunctionalTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketAppenderBaseFunctionalTest.java @@ -37,47 +37,46 @@ import ch.qos.logback.core.net.mock.MockContext; */ public class ServerSocketAppenderBaseFunctionalTest { - private static final String TEST_EVENT = "test event"; - - private static final int EVENT_COUNT = 10; - - private ExecutorService executor = Executors.newCachedThreadPool(); - private MockContext context = new MockContext(executor); - private ServerSocket serverSocket; - private InstrumentedServerSocketAppenderBase appender; - - @Before - public void setUp() throws Exception { - - serverSocket = ServerSocketUtil.createServerSocket(); - - appender = new InstrumentedServerSocketAppenderBase(serverSocket); - appender.setContext(context); - } - - @After - public void tearDown() throws Exception { - executor.shutdownNow(); - executor.awaitTermination(10000, TimeUnit.MILLISECONDS); - assertTrue(executor.isTerminated()); - } - - @Test - public void testLogEventClient() throws Exception { - appender.start(); - Socket socket = new Socket(InetAddress.getLocalHost(), - serverSocket.getLocalPort()); - - socket.setSoTimeout(1000); - ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); - - for (int i = 0; i < EVENT_COUNT; i++) { - appender.append(TEST_EVENT + i); - assertEquals(TEST_EVENT + i, ois.readObject()); + private static final String TEST_EVENT = "test event"; + + private static final int EVENT_COUNT = 10; + + private ExecutorService executor = Executors.newCachedThreadPool(); + private MockContext context = new MockContext(executor); + private ServerSocket serverSocket; + private InstrumentedServerSocketAppenderBase appender; + + @Before + public void setUp() throws Exception { + + serverSocket = ServerSocketUtil.createServerSocket(); + + appender = new InstrumentedServerSocketAppenderBase(serverSocket); + appender.setContext(context); + } + + @After + public void tearDown() throws Exception { + executor.shutdownNow(); + executor.awaitTermination(10000, TimeUnit.MILLISECONDS); + assertTrue(executor.isTerminated()); + } + + @Test + public void testLogEventClient() throws Exception { + appender.start(); + Socket socket = new Socket(InetAddress.getLocalHost(), serverSocket.getLocalPort()); + + socket.setSoTimeout(1000); + ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); + + for (int i = 0; i < EVENT_COUNT; i++) { + appender.append(TEST_EVENT + i); + assertEquals(TEST_EVENT + i, ois.readObject()); + } + + socket.close(); + appender.stop(); } - - socket.close(); - appender.stop(); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketListenerTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketListenerTest.java index cbfb52b538f105cfc90abd917973f7cdcaae9807..6e0340fa017a318c4ee80916a9245dd9c6db7e5d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketListenerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketListenerTest.java @@ -27,7 +27,6 @@ import org.junit.Test; import ch.qos.logback.core.net.server.Client; import ch.qos.logback.core.net.server.ServerSocketListener; - /** * Unit tests for {@link ServerSocketListener}. * @@ -35,121 +34,115 @@ import ch.qos.logback.core.net.server.ServerSocketListener; */ public class ServerSocketListenerTest { - private ServerSocket serverSocket; - private ServerSocketListener listener; - - @Before - public void setUp() throws Exception { - serverSocket = ServerSocketUtil.createServerSocket(); - assertNotNull(serverSocket); - listener = new InstrumentedServerSocketListener(serverSocket); - } - - @Test - public void testAcceptClient() throws Exception { - RunnableClient localClient = new RunnableClient( - InetAddress.getLocalHost(), serverSocket.getLocalPort()); - Thread thread = new Thread(localClient); - thread.start(); - synchronized (localClient) { - int retries = 200; - while (retries-- > 0 && !localClient.isConnected()) { - localClient.wait(10); - } - } - assertTrue(localClient.isConnected()); - localClient.close(); - - serverSocket.setSoTimeout(5000); - Client client = listener.acceptClient(); - assertNotNull(client); - client.close(); - } - - private static class InstrumentedServerSocketListener - extends ServerSocketListener { - - public InstrumentedServerSocketListener(ServerSocket serverSocket) { - super(serverSocket); - } + private ServerSocket serverSocket; + private ServerSocketListener listener; - @Override - protected RemoteClient createClient(String id, Socket socket) - throws IOException { - return new RemoteClient(socket); - } - - } - - private static class RemoteClient implements Client { - - private final Socket socket; - - public RemoteClient(Socket socket) { - this.socket = socket; + @Before + public void setUp() throws Exception { + serverSocket = ServerSocketUtil.createServerSocket(); + assertNotNull(serverSocket); + listener = new InstrumentedServerSocketListener(serverSocket); } - public void run() { - } - - public void close() { - try { - socket.close(); - } - catch (IOException ex) { - ex.printStackTrace(System.err); - } - } - - } - - private static class RunnableClient implements Client { - - private final InetAddress inetAddress; - private final int port; - private boolean connected; - private boolean closed; - - public RunnableClient(InetAddress inetAddress, int port) { - super(); - this.inetAddress = inetAddress; - this.port = port; - } + @Test + public void testAcceptClient() throws Exception { + RunnableClient localClient = new RunnableClient(InetAddress.getLocalHost(), serverSocket.getLocalPort()); + Thread thread = new Thread(localClient); + thread.start(); + synchronized (localClient) { + int retries = 200; + while (retries-- > 0 && !localClient.isConnected()) { + localClient.wait(10); + } + } + assertTrue(localClient.isConnected()); + localClient.close(); - public synchronized boolean isConnected() { - return connected; + serverSocket.setSoTimeout(5000); + Client client = listener.acceptClient(); + assertNotNull(client); + client.close(); } - public synchronized void setConnected(boolean connected) { - this.connected = connected; + private static class InstrumentedServerSocketListener extends ServerSocketListener { + + public InstrumentedServerSocketListener(ServerSocket serverSocket) { + super(serverSocket); + } + + @Override + protected RemoteClient createClient(String id, Socket socket) throws IOException { + return new RemoteClient(socket); + } + } - public void run() { - try { - Socket socket = new Socket(inetAddress, port); - synchronized (this) { - setConnected(true); - notifyAll(); - while (!closed && !Thread.currentThread().isInterrupted()) { + private static class RemoteClient implements Client { + + private final Socket socket; + + public RemoteClient(Socket socket) { + this.socket = socket; + } + + public void run() { + } + + public void close() { try { - wait(); - } - catch (InterruptedException ex) { - Thread.currentThread().interrupt(); + socket.close(); + } catch (IOException ex) { + ex.printStackTrace(System.err); } - } - socket.close(); } - } - catch (IOException ex) { - ex.printStackTrace(System.err); - } + } - public synchronized void close() { - closed = true; - notifyAll(); + private static class RunnableClient implements Client { + + private final InetAddress inetAddress; + private final int port; + private boolean connected; + private boolean closed; + + public RunnableClient(InetAddress inetAddress, int port) { + super(); + this.inetAddress = inetAddress; + this.port = port; + } + + public synchronized boolean isConnected() { + return connected; + } + + public synchronized void setConnected(boolean connected) { + this.connected = connected; + } + + public void run() { + try { + Socket socket = new Socket(inetAddress, port); + synchronized (this) { + setConnected(true); + notifyAll(); + while (!closed && !Thread.currentThread().isInterrupted()) { + try { + wait(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + socket.close(); + } + } catch (IOException ex) { + ex.printStackTrace(System.err); + } + } + + public synchronized void close() { + closed = true; + notifyAll(); + } + } - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketUtil.java b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketUtil.java index 422be29cd2f1a7a065f6856b5d059c4412e69e4e..1e43b537a56b771bbf4f41d940c98d1d41fe0c25 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketUtil.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/server/ServerSocketUtil.java @@ -27,43 +27,41 @@ import javax.net.ServerSocketFactory; */ public class ServerSocketUtil { - /** - * Creates a new {@link ServerSocket} bound to a random unused port. - *

- * This method is a convenience overload for - * {@link #createServerSocket(ServerSocketFactory)} using the platform's - * default {@link ServerSocketFactory}. - * @return socket - * @throws IOException - */ - public static ServerSocket createServerSocket() throws IOException { - return createServerSocket(ServerSocketFactory.getDefault()); - } - - /** - * Creates a new {@link ServerSocket} bound to a random unused port. - * @param socketFactory socket factory that will be used to create the - * socket - * @return socket - * @throws IOException - */ - public static ServerSocket createServerSocket( - ServerSocketFactory socketFactory) throws IOException { - ServerSocket socket = null; - int retries = 10; - while (retries-- > 0 && socket == null) { - int port = (int)((65536 - 1024) * Math.random()) + 1024; - try { - socket = socketFactory.createServerSocket(port); - } - catch (BindException ex) { - // try again with different port - } + /** + * Creates a new {@link ServerSocket} bound to a random unused port. + *

+ * This method is a convenience overload for + * {@link #createServerSocket(ServerSocketFactory)} using the platform's + * default {@link ServerSocketFactory}. + * @return socket + * @throws IOException + */ + public static ServerSocket createServerSocket() throws IOException { + return createServerSocket(ServerSocketFactory.getDefault()); } - if (socket == null) { - throw new BindException("cannot find an unused port to bind"); + + /** + * Creates a new {@link ServerSocket} bound to a random unused port. + * @param socketFactory socket factory that will be used to create the + * socket + * @return socket + * @throws IOException + */ + public static ServerSocket createServerSocket(ServerSocketFactory socketFactory) throws IOException { + ServerSocket socket = null; + int retries = 10; + while (retries-- > 0 && socket == null) { + int port = (int) ((65536 - 1024) * Math.random()) + 1024; + try { + socket = socketFactory.createServerSocket(port); + } catch (BindException ex) { + // try again with different port + } + } + if (socket == null) { + throw new BindException("cannot find an unused port to bind"); + } + return socket; } - return socket; - } - + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBeanTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBeanTest.java index 4e4130826e3c22f68830d15ac9cc59f5815c4768..77b9c02faf7373a6d0e208f8ddaa7dab159f6960 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBeanTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyManagerFactoryFactoryBeanTest.java @@ -21,7 +21,6 @@ import org.junit.Test; import ch.qos.logback.core.net.ssl.KeyManagerFactoryFactoryBean; - /** * Unit tests for {@link KeyManagerFactoryFactoryBean}. * @@ -29,26 +28,24 @@ import ch.qos.logback.core.net.ssl.KeyManagerFactoryFactoryBean; */ public class KeyManagerFactoryFactoryBeanTest { - private KeyManagerFactoryFactoryBean factoryBean = - new KeyManagerFactoryFactoryBean(); - - @Test - public void testDefaults() throws Exception { - assertNotNull(factoryBean.createKeyManagerFactory()); - } - - @Test - public void testExplicitAlgorithm() throws Exception { - factoryBean.setAlgorithm(KeyManagerFactory.getDefaultAlgorithm()); - assertNotNull(factoryBean.createKeyManagerFactory()); - } - - @Test - public void testExplicitProvider() throws Exception { - KeyManagerFactory factory = KeyManagerFactory.getInstance( - KeyManagerFactory.getDefaultAlgorithm()); - factoryBean.setProvider(factory.getProvider().getName()); - assertNotNull(factoryBean.createKeyManagerFactory()); - } - + private KeyManagerFactoryFactoryBean factoryBean = new KeyManagerFactoryFactoryBean(); + + @Test + public void testDefaults() throws Exception { + assertNotNull(factoryBean.createKeyManagerFactory()); + } + + @Test + public void testExplicitAlgorithm() throws Exception { + factoryBean.setAlgorithm(KeyManagerFactory.getDefaultAlgorithm()); + assertNotNull(factoryBean.createKeyManagerFactory()); + } + + @Test + public void testExplicitProvider() throws Exception { + KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + factoryBean.setProvider(factory.getProvider().getName()); + assertNotNull(factoryBean.createKeyManagerFactory()); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBeanTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBeanTest.java index ca78bf2b5fdf01ede49e7bf4c5fd17cab7a602ef..a9f25ee24b759be47493d3e1497bc8f00c8026ac 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBeanTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/KeyStoreFactoryBeanTest.java @@ -22,7 +22,6 @@ import org.junit.Test; import ch.qos.logback.core.net.ssl.KeyStoreFactoryBean; import ch.qos.logback.core.net.ssl.SSL; - /** * Unit tests for {@link KeyStoreFactoryBean}. * @@ -30,41 +29,41 @@ import ch.qos.logback.core.net.ssl.SSL; */ public class KeyStoreFactoryBeanTest { - private KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); - - @Test - public void testDefaults() throws Exception { - factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - assertNotNull(factoryBean.createKeyStore()); - } + private KeyStoreFactoryBean factoryBean = new KeyStoreFactoryBean(); + + @Test + public void testDefaults() throws Exception { + factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + assertNotNull(factoryBean.createKeyStore()); + } + + @Test + public void testExplicitProvider() throws Exception { + factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + KeyStore keyStore = factoryBean.createKeyStore(); + factoryBean.setProvider(keyStore.getProvider().getName()); + assertNotNull(factoryBean.createKeyStore()); + } - @Test - public void testExplicitProvider() throws Exception { - factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - KeyStore keyStore = factoryBean.createKeyStore(); - factoryBean.setProvider(keyStore.getProvider().getName()); - assertNotNull(factoryBean.createKeyStore()); - } - - @Test - public void testExplicitType() throws Exception { - factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - factoryBean.setType(SSL.DEFAULT_KEYSTORE_TYPE); - assertNotNull(factoryBean.createKeyStore()); - } + @Test + public void testExplicitType() throws Exception { + factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + factoryBean.setType(SSL.DEFAULT_KEYSTORE_TYPE); + assertNotNull(factoryBean.createKeyStore()); + } - @Test - public void testPKCS12Type() throws Exception { - factoryBean.setLocation(SSLTestConstants.KEYSTORE_PKCS12_RESOURCE); - factoryBean.setType(SSLTestConstants.PKCS12_TYPE); - assertNotNull(factoryBean.createKeyStore()); - } + @Test + public void testPKCS12Type() throws Exception { + factoryBean.setLocation(SSLTestConstants.KEYSTORE_PKCS12_RESOURCE); + factoryBean.setType(SSLTestConstants.PKCS12_TYPE); + assertNotNull(factoryBean.createKeyStore()); + } - @Test - public void testExplicitPassphrase() throws Exception { - factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - factoryBean.setPassword(SSL.DEFAULT_KEYSTORE_PASSWORD); - assertNotNull(factoryBean.createKeyStore()); - } + @Test + public void testExplicitPassphrase() throws Exception { + factoryBean.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + factoryBean.setPassword(SSL.DEFAULT_KEYSTORE_PASSWORD); + assertNotNull(factoryBean.createKeyStore()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/PackageTest.java index 3e1ba3dd05eb1df368eab3b109cbbfcbda15785b..bc7e587b2a25f6f061512fe41e6397354dd070a0 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/PackageTest.java @@ -17,15 +17,9 @@ package ch.qos.logback.core.net.ssl; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({KeyManagerFactoryFactoryBeanTest.class, - KeyStoreFactoryBeanTest.class, - SecureRandomFactoryBeanTest.class, - SSLConfigurationTest.class, - SSLContextFactoryBeanTest.class, - SSLParametersConfigurationTest.class, - TrustManagerFactoryFactoryBeanTest.class}) +@Suite.SuiteClasses({ KeyManagerFactoryFactoryBeanTest.class, KeyStoreFactoryBeanTest.class, SecureRandomFactoryBeanTest.class, SSLConfigurationTest.class, + SSLContextFactoryBeanTest.class, SSLParametersConfigurationTest.class, TrustManagerFactoryFactoryBeanTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLConfigurationTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLConfigurationTest.java index cf5ea691c33521e333ee3dfaa9dc7768dbdafab6..2bad45540ddf88de06075ef63b2b5fad0f439b71 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLConfigurationTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLConfigurationTest.java @@ -24,11 +24,11 @@ import org.junit.Test; */ public class SSLConfigurationTest { - private SSLConfiguration configuration = new SSLConfiguration(); - - @Test - public void testParameters() throws Exception { - assertNotNull(configuration.getParameters()); - } - + private SSLConfiguration configuration = new SSLConfiguration(); + + @Test + public void testParameters() throws Exception { + assertNotNull(configuration.getParameters()); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBeanTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBeanTest.java index 9c019d0cafc11da2f1e08c22e1895fa2719c7510..7c68c656b4c400c12df47fb67a65341c9e85b942 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBeanTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLContextFactoryBeanTest.java @@ -32,82 +32,71 @@ import ch.qos.logback.core.net.ssl.mock.MockTrustManagerFactoryFactoryBean; */ public class SSLContextFactoryBeanTest { - private static final String SSL_CONFIGURATION_MESSAGE_PATTERN = - "SSL protocol '.*?' provider '.*?'"; - - private static final String KEY_MANAGER_FACTORY_MESSAGE_PATTERN = - "key manager algorithm '.*?' provider '.*?'"; - - private static final String TRUST_MANAGER_FACTORY_MESSAGE_PATTERN = - "trust manager algorithm '.*?' provider '.*?'"; - - private static final String KEY_STORE_MESSAGE_PATTERN = - "key store of type '.*?' provider '.*?': .*"; - - private static final String TRUST_STORE_MESSAGE_PATTERN = - "trust store of type '.*?' provider '.*?': .*"; - - private static final String SECURE_RANDOM_MESSAGE_PATTERN = - "secure random algorithm '.*?' provider '.*?'"; - - private MockKeyManagerFactoryFactoryBean keyManagerFactory = - new MockKeyManagerFactoryFactoryBean(); - - private MockTrustManagerFactoryFactoryBean trustManagerFactory = - new MockTrustManagerFactoryFactoryBean(); - - private MockKeyStoreFactoryBean keyStore = - new MockKeyStoreFactoryBean(); - - private MockKeyStoreFactoryBean trustStore = - new MockKeyStoreFactoryBean(); - - private MockSecureRandomFactoryBean secureRandom = - new MockSecureRandomFactoryBean(); - - private MockContextAware context = new MockContextAware(); - private SSLContextFactoryBean factoryBean = new SSLContextFactoryBean(); - - @Before - public void setUp() throws Exception { - keyStore.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - trustStore.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); - } - - @Test - public void testCreateDefaultContext() throws Exception { - // should be able to create a context with no configuration at all - assertNotNull(factoryBean.createContext(context)); - assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN)); - } - - @Test - public void testCreateContext() throws Exception { - factoryBean.setKeyManagerFactory(keyManagerFactory); - factoryBean.setKeyStore(keyStore); - factoryBean.setTrustManagerFactory(trustManagerFactory); - factoryBean.setTrustStore(trustStore); - factoryBean.setSecureRandom(secureRandom); - - assertNotNull(factoryBean.createContext(context)); - - assertTrue(keyManagerFactory.isFactoryCreated()); - assertTrue(trustManagerFactory.isFactoryCreated()); - assertTrue(keyStore.isKeyStoreCreated()); - assertTrue(trustStore.isKeyStoreCreated()); - assertTrue(secureRandom.isSecureRandomCreated()); - - // it's important that each configured component output an appropriate - // informational message to the context; i.e. this logging is not just - // for programmers, it's there for systems administrators to use in - // verifying that SSL is configured properly - - assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN)); - assertTrue(context.hasInfoMatching(KEY_MANAGER_FACTORY_MESSAGE_PATTERN)); - assertTrue(context.hasInfoMatching(TRUST_MANAGER_FACTORY_MESSAGE_PATTERN)); - assertTrue(context.hasInfoMatching(KEY_STORE_MESSAGE_PATTERN)); - assertTrue(context.hasInfoMatching(TRUST_STORE_MESSAGE_PATTERN)); - assertTrue(context.hasInfoMatching(SECURE_RANDOM_MESSAGE_PATTERN)); - } - + private static final String SSL_CONFIGURATION_MESSAGE_PATTERN = "SSL protocol '.*?' provider '.*?'"; + + private static final String KEY_MANAGER_FACTORY_MESSAGE_PATTERN = "key manager algorithm '.*?' provider '.*?'"; + + private static final String TRUST_MANAGER_FACTORY_MESSAGE_PATTERN = "trust manager algorithm '.*?' provider '.*?'"; + + private static final String KEY_STORE_MESSAGE_PATTERN = "key store of type '.*?' provider '.*?': .*"; + + private static final String TRUST_STORE_MESSAGE_PATTERN = "trust store of type '.*?' provider '.*?': .*"; + + private static final String SECURE_RANDOM_MESSAGE_PATTERN = "secure random algorithm '.*?' provider '.*?'"; + + private MockKeyManagerFactoryFactoryBean keyManagerFactory = new MockKeyManagerFactoryFactoryBean(); + + private MockTrustManagerFactoryFactoryBean trustManagerFactory = new MockTrustManagerFactoryFactoryBean(); + + private MockKeyStoreFactoryBean keyStore = new MockKeyStoreFactoryBean(); + + private MockKeyStoreFactoryBean trustStore = new MockKeyStoreFactoryBean(); + + private MockSecureRandomFactoryBean secureRandom = new MockSecureRandomFactoryBean(); + + private MockContextAware context = new MockContextAware(); + private SSLContextFactoryBean factoryBean = new SSLContextFactoryBean(); + + @Before + public void setUp() throws Exception { + keyStore.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + trustStore.setLocation(SSLTestConstants.KEYSTORE_JKS_RESOURCE); + } + + @Test + public void testCreateDefaultContext() throws Exception { + // should be able to create a context with no configuration at all + assertNotNull(factoryBean.createContext(context)); + assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN)); + } + + @Test + public void testCreateContext() throws Exception { + factoryBean.setKeyManagerFactory(keyManagerFactory); + factoryBean.setKeyStore(keyStore); + factoryBean.setTrustManagerFactory(trustManagerFactory); + factoryBean.setTrustStore(trustStore); + factoryBean.setSecureRandom(secureRandom); + + assertNotNull(factoryBean.createContext(context)); + + assertTrue(keyManagerFactory.isFactoryCreated()); + assertTrue(trustManagerFactory.isFactoryCreated()); + assertTrue(keyStore.isKeyStoreCreated()); + assertTrue(trustStore.isKeyStoreCreated()); + assertTrue(secureRandom.isSecureRandomCreated()); + + // it's important that each configured component output an appropriate + // informational message to the context; i.e. this logging is not just + // for programmers, it's there for systems administrators to use in + // verifying that SSL is configured properly + + assertTrue(context.hasInfoMatching(SSL_CONFIGURATION_MESSAGE_PATTERN)); + assertTrue(context.hasInfoMatching(KEY_MANAGER_FACTORY_MESSAGE_PATTERN)); + assertTrue(context.hasInfoMatching(TRUST_MANAGER_FACTORY_MESSAGE_PATTERN)); + assertTrue(context.hasInfoMatching(KEY_STORE_MESSAGE_PATTERN)); + assertTrue(context.hasInfoMatching(TRUST_STORE_MESSAGE_PATTERN)); + assertTrue(context.hasInfoMatching(SECURE_RANDOM_MESSAGE_PATTERN)); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLParametersConfigurationTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLParametersConfigurationTest.java index 204f77455a95d410e6e0fb350ff45f5f67343cf9..ab5bf8b92184e6a1d705ca1b364bf66dbfa59ffb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLParametersConfigurationTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLParametersConfigurationTest.java @@ -23,7 +23,6 @@ import org.junit.Test; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.net.ssl.mock.MockSSLConfigurable; - /** * Unit tests for {@link SSLParametersConfiguration}. * @@ -31,115 +30,107 @@ import ch.qos.logback.core.net.ssl.mock.MockSSLConfigurable; */ public class SSLParametersConfigurationTest { - private MockSSLConfigurable configurable = new MockSSLConfigurable(); - - private SSLParametersConfiguration configuration = - new SSLParametersConfiguration(); - - @Before - public void setUp() throws Exception { - configuration.setContext(new ContextBase()); - } - - @Test - public void testSetIncludedProtocols() throws Exception { - configurable.setSupportedProtocols(new String[] { "A", "B", "C", "D" }); - configuration.setIncludedProtocols("A,B ,C, D"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" }, - configurable.getEnabledProtocols())); - } - - @Test - public void testSetExcludedProtocols() throws Exception { - configurable.setSupportedProtocols(new String[] { "A", "B" }); - configuration.setExcludedProtocols("A"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[] { "B" }, - configurable.getEnabledProtocols())); - } - - @Test - public void testSetIncludedAndExcludedProtocols() throws Exception { - configurable.setSupportedProtocols(new String[] { "A", "B", "C" }); - configuration.setIncludedProtocols("A, B"); - configuration.setExcludedProtocols("B"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[] { "A" }, - configurable.getEnabledProtocols())); - } - - @Test - public void testSetIncludedCipherSuites() throws Exception { - configurable.setSupportedCipherSuites(new String[] { "A", "B", "C", "D" }); - configuration.setIncludedCipherSuites("A,B ,C, D"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" }, - configurable.getEnabledCipherSuites())); - } - - @Test - public void testSetExcludedCipherSuites() throws Exception { - configurable.setSupportedCipherSuites(new String[] { "A", "B" }); - configuration.setExcludedCipherSuites("A"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[]{ "B" }, - configurable.getEnabledCipherSuites())); - } - - @Test - public void testSetExcludedAndIncludedCipherSuites() throws Exception { - configurable.setSupportedCipherSuites(new String[] { "A", "B", "C" }); - configuration.setIncludedCipherSuites("A, B"); - configuration.setExcludedCipherSuites("B"); - configuration.configure(configurable); - assertTrue(Arrays.equals(new String[] { "A" }, - configurable.getEnabledCipherSuites())); - } - - @Test - public void testSetNeedClientAuth() throws Exception { - configuration.setNeedClientAuth(true); - configuration.configure(configurable); - assertTrue(configurable.isNeedClientAuth()); - } - - @Test - public void testSetWantClientAuth() throws Exception { - configuration.setWantClientAuth(true); - configuration.configure(configurable); - assertTrue(configurable.isWantClientAuth()); - } - - @Test - public void testPassDefaultProtocols() throws Exception { - final String[] protocols = new String[] { "A" }; - configurable.setDefaultProtocols(protocols); - configuration.configure(configurable); - assertTrue(Arrays.equals(protocols, configurable.getEnabledProtocols())); - } - - @Test - public void testPassDefaultCipherSuites() throws Exception { - final String[] cipherSuites = new String[] { "A" }; - configurable.setDefaultCipherSuites(cipherSuites); - configuration.configure(configurable); - assertTrue(Arrays.equals(cipherSuites, - configurable.getEnabledCipherSuites())); - } - - @Test - public void testPassDefaultNeedClientAuth() throws Exception { - configurable.setNeedClientAuth(true); - configuration.configure(configurable); - assertTrue(configurable.isNeedClientAuth()); - } - - @Test - public void testPassDefaultWantClientAuth() throws Exception { - configurable.setWantClientAuth(true); - configuration.configure(configurable); - assertTrue(configurable.isWantClientAuth()); - } + private MockSSLConfigurable configurable = new MockSSLConfigurable(); + + private SSLParametersConfiguration configuration = new SSLParametersConfiguration(); + + @Before + public void setUp() throws Exception { + configuration.setContext(new ContextBase()); + } + + @Test + public void testSetIncludedProtocols() throws Exception { + configurable.setSupportedProtocols(new String[] { "A", "B", "C", "D" }); + configuration.setIncludedProtocols("A,B ,C, D"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" }, configurable.getEnabledProtocols())); + } + + @Test + public void testSetExcludedProtocols() throws Exception { + configurable.setSupportedProtocols(new String[] { "A", "B" }); + configuration.setExcludedProtocols("A"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "B" }, configurable.getEnabledProtocols())); + } + + @Test + public void testSetIncludedAndExcludedProtocols() throws Exception { + configurable.setSupportedProtocols(new String[] { "A", "B", "C" }); + configuration.setIncludedProtocols("A, B"); + configuration.setExcludedProtocols("B"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "A" }, configurable.getEnabledProtocols())); + } + + @Test + public void testSetIncludedCipherSuites() throws Exception { + configurable.setSupportedCipherSuites(new String[] { "A", "B", "C", "D" }); + configuration.setIncludedCipherSuites("A,B ,C, D"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "A", "B", "C", "D" }, configurable.getEnabledCipherSuites())); + } + + @Test + public void testSetExcludedCipherSuites() throws Exception { + configurable.setSupportedCipherSuites(new String[] { "A", "B" }); + configuration.setExcludedCipherSuites("A"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "B" }, configurable.getEnabledCipherSuites())); + } + + @Test + public void testSetExcludedAndIncludedCipherSuites() throws Exception { + configurable.setSupportedCipherSuites(new String[] { "A", "B", "C" }); + configuration.setIncludedCipherSuites("A, B"); + configuration.setExcludedCipherSuites("B"); + configuration.configure(configurable); + assertTrue(Arrays.equals(new String[] { "A" }, configurable.getEnabledCipherSuites())); + } + + @Test + public void testSetNeedClientAuth() throws Exception { + configuration.setNeedClientAuth(true); + configuration.configure(configurable); + assertTrue(configurable.isNeedClientAuth()); + } + + @Test + public void testSetWantClientAuth() throws Exception { + configuration.setWantClientAuth(true); + configuration.configure(configurable); + assertTrue(configurable.isWantClientAuth()); + } + + @Test + public void testPassDefaultProtocols() throws Exception { + final String[] protocols = new String[] { "A" }; + configurable.setDefaultProtocols(protocols); + configuration.configure(configurable); + assertTrue(Arrays.equals(protocols, configurable.getEnabledProtocols())); + } + + @Test + public void testPassDefaultCipherSuites() throws Exception { + final String[] cipherSuites = new String[] { "A" }; + configurable.setDefaultCipherSuites(cipherSuites); + configuration.configure(configurable); + assertTrue(Arrays.equals(cipherSuites, configurable.getEnabledCipherSuites())); + } + + @Test + public void testPassDefaultNeedClientAuth() throws Exception { + configurable.setNeedClientAuth(true); + configuration.configure(configurable); + assertTrue(configurable.isNeedClientAuth()); + } + + @Test + public void testPassDefaultWantClientAuth() throws Exception { + configurable.setWantClientAuth(true); + configuration.configure(configurable); + assertTrue(configurable.isWantClientAuth()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLTestConstants.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLTestConstants.java index 1c4e0cf7400ee4bf0f2809162c4c1dc22b96a716..3e788716a58bc49937eae06514402cfbaaa2bbed 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLTestConstants.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SSLTestConstants.java @@ -20,14 +20,14 @@ package ch.qos.logback.core.net.ssl; */ public interface SSLTestConstants { - String KEYSTORE_JKS_RESOURCE = "net/ssl/keystore.jks"; - - String KEYSTORE_PKCS12_RESOURCE = "net/ssl/keystore.p12"; + String KEYSTORE_JKS_RESOURCE = "net/ssl/keystore.jks"; - String PKCS12_TYPE = "PKCS12"; + String KEYSTORE_PKCS12_RESOURCE = "net/ssl/keystore.p12"; - String FAKE_ALGORITHM_NAME = "A_FAKE_ALGORITHM_NAME"; + String PKCS12_TYPE = "PKCS12"; - String FAKE_PROVIDER_NAME = "A_FAKE_PROVIDER_NAME"; + String FAKE_ALGORITHM_NAME = "A_FAKE_ALGORITHM_NAME"; + + String FAKE_PROVIDER_NAME = "A_FAKE_PROVIDER_NAME"; } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBeanTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBeanTest.java index 755076dd1ab6570ec81c445ff0d470fdc9f6eacf..223dc716fa88a1cf82293ebec1d4448e72ea1be9 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBeanTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/SecureRandomFactoryBeanTest.java @@ -26,7 +26,6 @@ import org.junit.Test; import ch.qos.logback.core.net.ssl.SSL; import ch.qos.logback.core.net.ssl.SecureRandomFactoryBean; - /** * Unit tests for {@link SecureRandomFactoryBean}. * @@ -34,43 +33,40 @@ import ch.qos.logback.core.net.ssl.SecureRandomFactoryBean; */ public class SecureRandomFactoryBeanTest { - private SecureRandomFactoryBean factoryBean = new SecureRandomFactoryBean(); - - @Test - public void testDefaults() throws Exception { - assertNotNull(factoryBean.createSecureRandom()); - } - - @Test - public void testExplicitProvider() throws Exception { - SecureRandom secureRandom = SecureRandom.getInstance( - SSL.DEFAULT_SECURE_RANDOM_ALGORITHM); - factoryBean.setProvider(secureRandom.getProvider().getName()); - assertNotNull(factoryBean.createSecureRandom()); - } + private SecureRandomFactoryBean factoryBean = new SecureRandomFactoryBean(); - @Test - public void testUnknownProvider() throws Exception { - factoryBean.setProvider(SSLTestConstants.FAKE_PROVIDER_NAME); - try { - factoryBean.createSecureRandom(); - fail("expected NoSuchProviderException"); + @Test + public void testDefaults() throws Exception { + assertNotNull(factoryBean.createSecureRandom()); } - catch (NoSuchProviderException ex) { - assertTrue(ex.getMessage().contains(SSLTestConstants.FAKE_PROVIDER_NAME)); + + @Test + public void testExplicitProvider() throws Exception { + SecureRandom secureRandom = SecureRandom.getInstance(SSL.DEFAULT_SECURE_RANDOM_ALGORITHM); + factoryBean.setProvider(secureRandom.getProvider().getName()); + assertNotNull(factoryBean.createSecureRandom()); } - } - @Test - public void testUnknownAlgorithm() throws Exception { - factoryBean.setAlgorithm(SSLTestConstants.FAKE_ALGORITHM_NAME); - try { - factoryBean.createSecureRandom(); - fail("expected NoSuchAlgorithmException"); + @Test + public void testUnknownProvider() throws Exception { + factoryBean.setProvider(SSLTestConstants.FAKE_PROVIDER_NAME); + try { + factoryBean.createSecureRandom(); + fail("expected NoSuchProviderException"); + } catch (NoSuchProviderException ex) { + assertTrue(ex.getMessage().contains(SSLTestConstants.FAKE_PROVIDER_NAME)); + } } - catch (NoSuchAlgorithmException ex) { - assertTrue(ex.getMessage().contains(SSLTestConstants.FAKE_ALGORITHM_NAME)); + + @Test + public void testUnknownAlgorithm() throws Exception { + factoryBean.setAlgorithm(SSLTestConstants.FAKE_ALGORITHM_NAME); + try { + factoryBean.createSecureRandom(); + fail("expected NoSuchAlgorithmException"); + } catch (NoSuchAlgorithmException ex) { + assertTrue(ex.getMessage().contains(SSLTestConstants.FAKE_ALGORITHM_NAME)); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBeanTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBeanTest.java index e2eb12df5780d8418ddc3d37ff71ce696724e9ea..408478a2c24f49c1d6d4f662cacdbec94e8877ec 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBeanTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/TrustManagerFactoryFactoryBeanTest.java @@ -21,7 +21,6 @@ import org.junit.Test; import ch.qos.logback.core.net.ssl.TrustManagerFactoryFactoryBean; - /** * Unit tests for {@link TrustManagerFactoryFactoryBean}. * @@ -29,26 +28,24 @@ import ch.qos.logback.core.net.ssl.TrustManagerFactoryFactoryBean; */ public class TrustManagerFactoryFactoryBeanTest { - private TrustManagerFactoryFactoryBean factoryBean = - new TrustManagerFactoryFactoryBean(); - - @Test - public void testDefaults() throws Exception { - assertNotNull(factoryBean.createTrustManagerFactory()); - } - - @Test - public void testExplicitAlgorithm() throws Exception { - factoryBean.setAlgorithm(TrustManagerFactory.getDefaultAlgorithm()); - assertNotNull(factoryBean.createTrustManagerFactory()); - } - - @Test - public void testExplicitProvider() throws Exception { - TrustManagerFactory factory = TrustManagerFactory.getInstance( - TrustManagerFactory.getDefaultAlgorithm()); - factoryBean.setProvider(factory.getProvider().getName()); - assertNotNull(factoryBean.createTrustManagerFactory()); - } - + private TrustManagerFactoryFactoryBean factoryBean = new TrustManagerFactoryFactoryBean(); + + @Test + public void testDefaults() throws Exception { + assertNotNull(factoryBean.createTrustManagerFactory()); + } + + @Test + public void testExplicitAlgorithm() throws Exception { + factoryBean.setAlgorithm(TrustManagerFactory.getDefaultAlgorithm()); + assertNotNull(factoryBean.createTrustManagerFactory()); + } + + @Test + public void testExplicitProvider() throws Exception { + TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factoryBean.setProvider(factory.getProvider().getName()); + assertNotNull(factoryBean.createTrustManagerFactory()); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockContextAware.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockContextAware.java index 162e153e2ef635c867e0b820cdaf19bca2eccb6d..1080deb853a270ebfd5e0e015b722d6ceaa2f0a3 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockContextAware.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockContextAware.java @@ -24,45 +24,45 @@ import ch.qos.logback.core.spi.ContextAwareBase; * * @author Carl Harris */ -public class MockContextAware extends ContextAwareBase - implements ContextAware { +public class MockContextAware extends ContextAwareBase implements ContextAware { - private final List info = new LinkedList(); - private final List warn = new LinkedList(); - private final List error = new LinkedList(); - - @Override - public void addInfo(String msg) { - info.add(msg); - } + private final List info = new LinkedList(); + private final List warn = new LinkedList(); + private final List error = new LinkedList(); - @Override - public void addWarn(String msg) { - warn.add(msg); - } + @Override + public void addInfo(String msg) { + info.add(msg); + } + + @Override + public void addWarn(String msg) { + warn.add(msg); + } - @Override - public void addError(String msg) { - error.add(msg); - } + @Override + public void addError(String msg) { + error.add(msg); + } + + public boolean hasInfoMatching(String regex) { + return hasMatching(info, regex); + } - public boolean hasInfoMatching(String regex) { - return hasMatching(info, regex); - } - - public boolean hasWarnMatching(String regex) { - return hasMatching(info, regex); - } - - public boolean hasErrorMatching(String regex) { - return hasMatching(info, regex); - } - - private boolean hasMatching(List messages, String regex) { - for (String message : messages) { - if (message.matches(regex)) return true; + public boolean hasWarnMatching(String regex) { + return hasMatching(info, regex); } - return false; - } - + + public boolean hasErrorMatching(String regex) { + return hasMatching(info, regex); + } + + private boolean hasMatching(List messages, String regex) { + for (String message : messages) { + if (message.matches(regex)) + return true; + } + return false; + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyManagerFactoryFactoryBean.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyManagerFactoryFactoryBean.java index 9c3adc144714cf93f0491aaf183dc93b6f731563..8d6016569ea6fe6305b783ecce3cb2e77d0dd515 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyManagerFactoryFactoryBean.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyManagerFactoryFactoryBean.java @@ -25,20 +25,18 @@ import ch.qos.logback.core.net.ssl.KeyManagerFactoryFactoryBean; * * @author Carl Harris */ -public class MockKeyManagerFactoryFactoryBean - extends KeyManagerFactoryFactoryBean { - - private boolean factoryCreated; - - @Override - public KeyManagerFactory createKeyManagerFactory() - throws NoSuchProviderException, NoSuchAlgorithmException { - factoryCreated = true; - return super.createKeyManagerFactory(); - } - - public boolean isFactoryCreated() { - return factoryCreated; - } - +public class MockKeyManagerFactoryFactoryBean extends KeyManagerFactoryFactoryBean { + + private boolean factoryCreated; + + @Override + public KeyManagerFactory createKeyManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException { + factoryCreated = true; + return super.createKeyManagerFactory(); + } + + public boolean isFactoryCreated() { + return factoryCreated; + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyStoreFactoryBean.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyStoreFactoryBean.java index edf476b72b4c1b90565790a756883e93e193e303..280ad873bb26fea9805fd6ef776b9177fe483c3b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyStoreFactoryBean.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockKeyStoreFactoryBean.java @@ -27,17 +27,16 @@ import ch.qos.logback.core.net.ssl.KeyStoreFactoryBean; */ public class MockKeyStoreFactoryBean extends KeyStoreFactoryBean { - private boolean keyStoreCreated; - - @Override - public KeyStore createKeyStore() throws NoSuchProviderException, - NoSuchAlgorithmException, KeyStoreException { - keyStoreCreated = true; - return super.createKeyStore(); - } + private boolean keyStoreCreated; - public boolean isKeyStoreCreated() { - return keyStoreCreated; - } + @Override + public KeyStore createKeyStore() throws NoSuchProviderException, NoSuchAlgorithmException, KeyStoreException { + keyStoreCreated = true; + return super.createKeyStore(); + } + + public boolean isKeyStoreCreated() { + return keyStoreCreated; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSSLConfigurable.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSSLConfigurable.java index a03144fa8f01666e31ee743e4c843e2bc47d8381..8c47e32dc5f285f8189bf6a4dbb6a5aa248044d8 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSSLConfigurable.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSSLConfigurable.java @@ -17,79 +17,79 @@ import ch.qos.logback.core.net.ssl.SSLConfigurable; public class MockSSLConfigurable implements SSLConfigurable { - private static final String[] EMPTY = new String[0]; - - private String[] defaultProtocols = EMPTY; - private String[] supportedProtocols = EMPTY; - private String[] enabledProtocols = EMPTY; - private String[] defaultCipherSuites = EMPTY; - private String[] supportedCipherSuites = EMPTY; - private String[] enabledCipherSuites = EMPTY; - private boolean needClientAuth; - private boolean wantClientAuth; - - public String[] getDefaultProtocols() { - return defaultProtocols; - } - - public void setDefaultProtocols(String[] defaultProtocols) { - this.defaultProtocols = defaultProtocols; - } - - public String[] getSupportedProtocols() { - return supportedProtocols; - } - - public void setSupportedProtocols(String[] supportedProtocols) { - this.supportedProtocols = supportedProtocols; - } - - public String[] getEnabledProtocols() { - return enabledProtocols; - } - - public void setEnabledProtocols(String[] enabledProtocols) { - this.enabledProtocols = enabledProtocols; - } - - public String[] getDefaultCipherSuites() { - return defaultCipherSuites; - } - - public void setDefaultCipherSuites(String[] defaultCipherSuites) { - this.defaultCipherSuites = defaultCipherSuites; - } - - public String[] getSupportedCipherSuites() { - return supportedCipherSuites; - } - - public void setSupportedCipherSuites(String[] supportedCipherSuites) { - this.supportedCipherSuites = supportedCipherSuites; - } - - public String[] getEnabledCipherSuites() { - return enabledCipherSuites; - } - - public void setEnabledCipherSuites(String[] enabledCipherSuites) { - this.enabledCipherSuites = enabledCipherSuites; - } - - public boolean isNeedClientAuth() { - return needClientAuth; - } - - public void setNeedClientAuth(boolean needClientAuth) { - this.needClientAuth = needClientAuth; - } - - public boolean isWantClientAuth() { - return wantClientAuth; - } - - public void setWantClientAuth(boolean wantClientAuth) { - this.wantClientAuth = wantClientAuth; - } + private static final String[] EMPTY = new String[0]; + + private String[] defaultProtocols = EMPTY; + private String[] supportedProtocols = EMPTY; + private String[] enabledProtocols = EMPTY; + private String[] defaultCipherSuites = EMPTY; + private String[] supportedCipherSuites = EMPTY; + private String[] enabledCipherSuites = EMPTY; + private boolean needClientAuth; + private boolean wantClientAuth; + + public String[] getDefaultProtocols() { + return defaultProtocols; + } + + public void setDefaultProtocols(String[] defaultProtocols) { + this.defaultProtocols = defaultProtocols; + } + + public String[] getSupportedProtocols() { + return supportedProtocols; + } + + public void setSupportedProtocols(String[] supportedProtocols) { + this.supportedProtocols = supportedProtocols; + } + + public String[] getEnabledProtocols() { + return enabledProtocols; + } + + public void setEnabledProtocols(String[] enabledProtocols) { + this.enabledProtocols = enabledProtocols; + } + + public String[] getDefaultCipherSuites() { + return defaultCipherSuites; + } + + public void setDefaultCipherSuites(String[] defaultCipherSuites) { + this.defaultCipherSuites = defaultCipherSuites; + } + + public String[] getSupportedCipherSuites() { + return supportedCipherSuites; + } + + public void setSupportedCipherSuites(String[] supportedCipherSuites) { + this.supportedCipherSuites = supportedCipherSuites; + } + + public String[] getEnabledCipherSuites() { + return enabledCipherSuites; + } + + public void setEnabledCipherSuites(String[] enabledCipherSuites) { + this.enabledCipherSuites = enabledCipherSuites; + } + + public boolean isNeedClientAuth() { + return needClientAuth; + } + + public void setNeedClientAuth(boolean needClientAuth) { + this.needClientAuth = needClientAuth; + } + + public boolean isWantClientAuth() { + return wantClientAuth; + } + + public void setWantClientAuth(boolean wantClientAuth) { + this.wantClientAuth = wantClientAuth; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSecureRandomFactoryBean.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSecureRandomFactoryBean.java index 429c42ca4784688828566a53b64e4a18fcba990f..5355d84a50e45752f51bbf1a7714f4e7940780d1 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSecureRandomFactoryBean.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockSecureRandomFactoryBean.java @@ -26,17 +26,16 @@ import ch.qos.logback.core.net.ssl.SecureRandomFactoryBean; */ public class MockSecureRandomFactoryBean extends SecureRandomFactoryBean { - private boolean secureRandomCreated; + private boolean secureRandomCreated; - @Override - public SecureRandom createSecureRandom() throws NoSuchProviderException, - NoSuchAlgorithmException { - secureRandomCreated = true; - return super.createSecureRandom(); - } + @Override + public SecureRandom createSecureRandom() throws NoSuchProviderException, NoSuchAlgorithmException { + secureRandomCreated = true; + return super.createSecureRandom(); + } + + public boolean isSecureRandomCreated() { + return secureRandomCreated; + } - public boolean isSecureRandomCreated() { - return secureRandomCreated; - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockTrustManagerFactoryFactoryBean.java b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockTrustManagerFactoryFactoryBean.java index ac5d522793af2c4b08c205c6a37422dfbb9cf488..21dbc3eb2107069d5c2134f31e22edb483334a16 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockTrustManagerFactoryFactoryBean.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/ssl/mock/MockTrustManagerFactoryFactoryBean.java @@ -25,21 +25,18 @@ import ch.qos.logback.core.net.ssl.TrustManagerFactoryFactoryBean; * * @author Carl Harris */ -public class MockTrustManagerFactoryFactoryBean - extends TrustManagerFactoryFactoryBean { - - private boolean factoryCreated; - - @Override - public TrustManagerFactory createTrustManagerFactory() - throws NoSuchProviderException, NoSuchAlgorithmException { - factoryCreated = true; - return super.createTrustManagerFactory(); - } - - public boolean isFactoryCreated() { - return factoryCreated; - } - - +public class MockTrustManagerFactoryFactoryBean extends TrustManagerFactoryFactoryBean { + + private boolean factoryCreated; + + @Override + public TrustManagerFactory createTrustManagerFactory() throws NoSuchProviderException, NoSuchAlgorithmException { + factoryCreated = true; + return super.createTrustManagerFactory(); + } + + public boolean isFactoryCreated() { + return factoryCreated; + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/Converter123.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/Converter123.java index 575725bf0aa1943da9736680fb9d95a7d00fcd32..ce4cf60c90edd7ccaa25d093c794b365c8b35d75 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/Converter123.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/Converter123.java @@ -17,8 +17,8 @@ import ch.qos.logback.core.pattern.DynamicConverter; public class Converter123 extends DynamicConverter { - public String convert(Object event) { - return "123"; - } + public String convert(Object event) { + return "123"; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/ConverterHello.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/ConverterHello.java index 54679cde0924a21f4e057575b47a771ad1db55b3..dbbb258fea2c96016554a044af5d562f81f619dd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/ConverterHello.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/ConverterHello.java @@ -17,8 +17,8 @@ import ch.qos.logback.core.pattern.DynamicConverter; public class ConverterHello extends DynamicConverter { - public String convert(Object event) { - return "Hello"; - } + public String convert(Object event) { + return "Hello"; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/ExceptionalConverter.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/ExceptionalConverter.java index f32738a509d7c29877fde0c29160dcbd4b5dd2f3..481ac3ae3b51797589f53d1e1a1bb92fb225c622 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/ExceptionalConverter.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/ExceptionalConverter.java @@ -16,12 +16,12 @@ package ch.qos.logback.core.pattern; import ch.qos.logback.core.pattern.DynamicConverter; public class ExceptionalConverter extends DynamicConverter { - - public String convert(Object event) { - if(!isStarted()) { - throw new IllegalStateException("this converter must be started before use"); + + public String convert(Object event) { + if (!isStarted()) { + throw new IllegalStateException("this converter must be started before use"); + } + return ""; } - return ""; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/PackageTest.java index 79ceb4c57924b9082313abac00cf5fa64a88a6f6..8dd22ef393df8751abb4145c0ed833d7c32a13f6 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({SpacePadderTest.class, ch.qos.logback.core.pattern.parser.PackageTest.class}) -public class PackageTest { +@SuiteClasses({ SpacePadderTest.class, ch.qos.logback.core.pattern.parser.PackageTest.class }) +public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/SpacePadderTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/SpacePadderTest.java index f7235169dad42ac628393f889a13c3e6f76f8799..5361c9b87e6be3bbbb4e29fafd5ae6277f117740 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/SpacePadderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/SpacePadderTest.java @@ -23,85 +23,85 @@ import org.junit.Test; public class SpacePadderTest { - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void smoke() { - { - StringBuilder buf = new StringBuilder(); - String s = "a"; - SpacePadder.leftPad(buf, s, 4); - assertEquals(" a", buf.toString()); + @BeforeClass + public static void setUpBeforeClass() throws Exception { } - { - StringBuilder buf = new StringBuilder(); - String s = "a"; - SpacePadder.rightPad(buf, s, 4); - assertEquals("a ", buf.toString()); + + @AfterClass + public static void tearDownAfterClass() throws Exception { } - } - @Test - public void nullString() { - String s = null; - { - StringBuilder buf = new StringBuilder(); - SpacePadder.leftPad(buf, s, 2); - assertEquals(" ", buf.toString()); + @Before + public void setUp() throws Exception { } - { - StringBuilder buf = new StringBuilder(); - SpacePadder.rightPad(buf, s, 2); - assertEquals(" ", buf.toString()); + + @After + public void tearDown() throws Exception { } - } - @Test - public void longString() { - { - StringBuilder buf = new StringBuilder(); - String s = "abc"; - SpacePadder.leftPad(buf, s, 2); - assertEquals(s, buf.toString()); + @Test + public void smoke() { + { + StringBuilder buf = new StringBuilder(); + String s = "a"; + SpacePadder.leftPad(buf, s, 4); + assertEquals(" a", buf.toString()); + } + { + StringBuilder buf = new StringBuilder(); + String s = "a"; + SpacePadder.rightPad(buf, s, 4); + assertEquals("a ", buf.toString()); + } } - { - StringBuilder buf = new StringBuilder(); - String s = "abc"; - SpacePadder.rightPad(buf, s, 2); - assertEquals(s, buf.toString()); + @Test + public void nullString() { + String s = null; + { + StringBuilder buf = new StringBuilder(); + SpacePadder.leftPad(buf, s, 2); + assertEquals(" ", buf.toString()); + } + { + StringBuilder buf = new StringBuilder(); + SpacePadder.rightPad(buf, s, 2); + assertEquals(" ", buf.toString()); + } } - } - - @Test - public void lengthyPad() { - { - StringBuilder buf = new StringBuilder(); - String s = "abc"; - SpacePadder.leftPad(buf, s, 33); - assertEquals(" abc", buf.toString()); + + @Test + public void longString() { + { + StringBuilder buf = new StringBuilder(); + String s = "abc"; + SpacePadder.leftPad(buf, s, 2); + assertEquals(s, buf.toString()); + } + + { + StringBuilder buf = new StringBuilder(); + String s = "abc"; + SpacePadder.rightPad(buf, s, 2); + assertEquals(s, buf.toString()); + } } - { - StringBuilder buf = new StringBuilder(); - String s = "abc"; - SpacePadder.rightPad(buf, s, 33); - assertEquals("abc ", buf.toString()); + + @Test + public void lengthyPad() { + { + StringBuilder buf = new StringBuilder(); + String s = "abc"; + SpacePadder.leftPad(buf, s, 33); + assertEquals(" abc", buf.toString()); + } + { + StringBuilder buf = new StringBuilder(); + String s = "abc"; + SpacePadder.rightPad(buf, s, 33); + assertEquals("abc ", buf.toString()); + } + } - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/AbstractPatternLayoutBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/AbstractPatternLayoutBaseTest.java index 7a24545fb8e316e98297b838c326fe5a48efa413..cee1ecb9b44737697b97527e00abc8d444eaa369 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/AbstractPatternLayoutBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/AbstractPatternLayoutBaseTest.java @@ -27,80 +27,81 @@ import ch.qos.logback.core.status.StatusChecker; import ch.qos.logback.core.status.StatusManager; import ch.qos.logback.core.util.StatusPrinter; - abstract public class AbstractPatternLayoutBaseTest { - - abstract public PatternLayoutBase getPatternLayoutBase(); - abstract public E getEventObject(); - abstract public Context getContext(); - - @Test - public void testUnStarted() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - String s = plb.doLayout(getEventObject()); - assertEquals("", s); - StatusManager sm = context.getStatusManager(); - StatusPrinter.print(sm); - } - /** - * This test checks that the pattern layout implementation starts its - * converters. ExceptionalConverter throws an exception if it's convert - * method is called before being started. - */ - @Test - public void testConverterStart() { - PatternLayoutBase plb = getPatternLayoutBase(); - plb.setContext(getContext()); - plb.getInstanceConverterMap().put("EX", ExceptionalConverter.class.getName()); - plb.setPattern("%EX"); - plb.start(); - String result = plb.doLayout(getEventObject()); - assertFalse(result.contains("%PARSER_ERROR_EX")); - //System.out.println("========="+result); - } + abstract public PatternLayoutBase getPatternLayoutBase(); + + abstract public E getEventObject(); + + abstract public Context getContext(); + + @Test + public void testUnStarted() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + String s = plb.doLayout(getEventObject()); + assertEquals("", s); + StatusManager sm = context.getStatusManager(); + StatusPrinter.print(sm); + } + + /** + * This test checks that the pattern layout implementation starts its + * converters. ExceptionalConverter throws an exception if it's convert + * method is called before being started. + */ + @Test + public void testConverterStart() { + PatternLayoutBase plb = getPatternLayoutBase(); + plb.setContext(getContext()); + plb.getInstanceConverterMap().put("EX", ExceptionalConverter.class.getName()); + plb.setPattern("%EX"); + plb.start(); + String result = plb.doLayout(getEventObject()); + assertFalse(result.contains("%PARSER_ERROR_EX")); + // System.out.println("========="+result); + } - @Test - public void testStarted() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - String s = plb.doLayout(getEventObject()); - assertEquals("", s); - StatusManager sm = context.getStatusManager(); - StatusPrinter.print(sm); - } + @Test + public void testStarted() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + String s = plb.doLayout(getEventObject()); + assertEquals("", s); + StatusManager sm = context.getStatusManager(); + StatusPrinter.print(sm); + } - @Test - public void testNullPattern() { - //System.out.println("testNullPattern"); - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern(null); - plb.start(); - String s = plb.doLayout(getEventObject()); - assertEquals("", s); - StatusChecker checker = new StatusChecker(context.getStatusManager()); - //StatusPrinter.print(context); - checker.assertContainsMatch("Empty or null pattern."); - } + @Test + public void testNullPattern() { + // System.out.println("testNullPattern"); + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern(null); + plb.start(); + String s = plb.doLayout(getEventObject()); + assertEquals("", s); + StatusChecker checker = new StatusChecker(context.getStatusManager()); + // StatusPrinter.print(context); + checker.assertContainsMatch("Empty or null pattern."); + } - @Test - public void testEmptyPattern() { - //System.out.println("testNullPattern"); - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern(""); - plb.start(); - String s = plb.doLayout(getEventObject()); - assertEquals("", s); - StatusChecker checker = new StatusChecker(context.getStatusManager()); - //StatusPrinter.print(context); - checker.assertContainsMatch("Empty or null pattern."); - } + @Test + public void testEmptyPattern() { + // System.out.println("testNullPattern"); + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern(""); + plb.start(); + String s = plb.doLayout(getEventObject()); + assertEquals("", s); + StatusChecker checker = new StatusChecker(context.getStatusManager()); + // StatusPrinter.print(context); + checker.assertContainsMatch("Empty or null pattern."); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/CompilerTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/CompilerTest.java index 42b8a99698eb19b452c57c15132b6dc57f2f0970..4b8a64f5bb938262ff58e07a7115d60d9f4b4cf5 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/CompilerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/CompilerTest.java @@ -30,227 +30,225 @@ import static org.junit.Assert.assertEquals; public class CompilerTest { - Map converterMap = new HashMap(); - Context context = new ContextBase(); - - @Before - public void setUp() { - converterMap.put("OTT", Converter123.class.getName()); - converterMap.put("hello", ConverterHello.class.getName()); - converterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); - } - - - String write(final Converter head, Object event) { - StringBuilder buf = new StringBuilder(); - Converter c = head; - while (c != null) { - c.write(buf, event); - c = c.getNext(); - } - return buf.toString(); - } - - @Test - public void testLiteral() throws Exception { - Parser p = new Parser("hello"); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("hello", result); - } - - @Test - public void testBasic() throws Exception { - { - Parser p = new Parser("abc %hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hello", result); - } - { - Parser p = new Parser("abc %hello %OTT"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hello 123", result); - } - } - - @Test - public void testFormat() throws Exception { - { - Parser p = new Parser("abc %7hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hello", result); - } - - { - Parser p = new Parser("abc %-7hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hello ", result); - } - - { - Parser p = new Parser("abc %.3hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc llo", result); - } - - { - Parser p = new Parser("abc %.-3hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hel", result); - } - - { - Parser p = new Parser("abc %4.5OTT"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc 123", result); - } - { - Parser p = new Parser("abc %-4.5OTT"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc 123 ", result); - } - { - Parser p = new Parser("abc %3.4hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc ello", result); - } - { - Parser p = new Parser("abc %-3.-4hello"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("abc Hell", result); - } - } - - @Test - public void testComposite() throws Exception { -// { -// Parser p = new Parser("%(ABC)"); -// p.setContext(context); -// Node t = p.parse(); -// Converter head = p.compile(t, converterMap); -// String result = write(head, new Object()); -// assertEquals("ABC", result); -// } - { - Context c = new ContextBase(); - Parser p = new Parser("%(ABC %hello)"); - p.setContext(c); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - StatusPrinter.print(c); - assertEquals("ABC Hello", result); - } - { - Parser p = new Parser("%(ABC %hello)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("ABC Hello", result); - } - } - - @Test - public void testCompositeFormatting() throws Exception { - { - Parser p = new Parser("xyz %4.10(ABC)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz ABC", result); - } - - { - Parser p = new Parser("xyz %-4.10(ABC)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz ABC ", result); - } - - { - Parser p = new Parser("xyz %.2(ABC %hello)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz lo", result); - } - - { - Parser p = new Parser("xyz %.-2(ABC)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz AB", result); - } - - { - Parser p = new Parser("xyz %30.30(ABC %20hello)"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz ABC Hello", result); - } - } - - @Test - public void testUnknownWord() throws Exception { - Parser p = new Parser("%unknown"); - p.setContext(context); - Node t = p.parse(); - p.compile(t, converterMap); - StatusChecker checker = new StatusChecker(context.getStatusManager()); - checker - .assertContainsMatch("\\[unknown] is not a valid conversion word"); - } - - @Test - public void testWithNopEscape() throws Exception { - { - Parser p = new Parser("xyz %hello\\_world"); - p.setContext(context); - Node t = p.parse(); - Converter head = p.compile(t, converterMap); - String result = write(head, new Object()); - assertEquals("xyz Helloworld", result); + Map converterMap = new HashMap(); + Context context = new ContextBase(); + + @Before + public void setUp() { + converterMap.put("OTT", Converter123.class.getName()); + converterMap.put("hello", ConverterHello.class.getName()); + converterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP); + } + + String write(final Converter head, Object event) { + StringBuilder buf = new StringBuilder(); + Converter c = head; + while (c != null) { + c.write(buf, event); + c = c.getNext(); + } + return buf.toString(); + } + + @Test + public void testLiteral() throws Exception { + Parser p = new Parser("hello"); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("hello", result); + } + + @Test + public void testBasic() throws Exception { + { + Parser p = new Parser("abc %hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hello", result); + } + { + Parser p = new Parser("abc %hello %OTT"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hello 123", result); + } + } + + @Test + public void testFormat() throws Exception { + { + Parser p = new Parser("abc %7hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hello", result); + } + + { + Parser p = new Parser("abc %-7hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hello ", result); + } + + { + Parser p = new Parser("abc %.3hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc llo", result); + } + + { + Parser p = new Parser("abc %.-3hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hel", result); + } + + { + Parser p = new Parser("abc %4.5OTT"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc 123", result); + } + { + Parser p = new Parser("abc %-4.5OTT"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc 123 ", result); + } + { + Parser p = new Parser("abc %3.4hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc ello", result); + } + { + Parser p = new Parser("abc %-3.-4hello"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("abc Hell", result); + } + } + + @Test + public void testComposite() throws Exception { + // { + // Parser p = new Parser("%(ABC)"); + // p.setContext(context); + // Node t = p.parse(); + // Converter head = p.compile(t, converterMap); + // String result = write(head, new Object()); + // assertEquals("ABC", result); + // } + { + Context c = new ContextBase(); + Parser p = new Parser("%(ABC %hello)"); + p.setContext(c); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + StatusPrinter.print(c); + assertEquals("ABC Hello", result); + } + { + Parser p = new Parser("%(ABC %hello)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("ABC Hello", result); + } + } + + @Test + public void testCompositeFormatting() throws Exception { + { + Parser p = new Parser("xyz %4.10(ABC)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz ABC", result); + } + + { + Parser p = new Parser("xyz %-4.10(ABC)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz ABC ", result); + } + + { + Parser p = new Parser("xyz %.2(ABC %hello)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz lo", result); + } + + { + Parser p = new Parser("xyz %.-2(ABC)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz AB", result); + } + + { + Parser p = new Parser("xyz %30.30(ABC %20hello)"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz ABC Hello", result); + } + } + + @Test + public void testUnknownWord() throws Exception { + Parser p = new Parser("%unknown"); + p.setContext(context); + Node t = p.parse(); + p.compile(t, converterMap); + StatusChecker checker = new StatusChecker(context.getStatusManager()); + checker.assertContainsMatch("\\[unknown] is not a valid conversion word"); + } + + @Test + public void testWithNopEscape() throws Exception { + { + Parser p = new Parser("xyz %hello\\_world"); + p.setContext(context); + Node t = p.parse(); + Converter head = p.compile(t, converterMap); + String result = write(head, new Object()); + assertEquals("xyz Helloworld", result); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/FormatInfoTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/FormatInfoTest.java index 1f458abb56d0c472c2f8fdcd65e1845aa5821b1b..4d9bf2e70a01d8920012f08a5fc37252095eac08 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/FormatInfoTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/FormatInfoTest.java @@ -20,101 +20,100 @@ import org.junit.Test; import ch.qos.logback.core.pattern.FormatInfo; - -public class FormatInfoTest { - - @Test - public void testEndingInDot() { - try { - FormatInfo.valueOf("45."); - fail("45. is not a valid format info string"); - } catch (IllegalArgumentException iae) { - // OK - } - } - - @Test - public void testBasic() { - { - FormatInfo fi = FormatInfo.valueOf("45"); - FormatInfo witness = new FormatInfo(); - witness.setMin(45); - assertEquals(witness, fi); - } - - { - FormatInfo fi = FormatInfo.valueOf("4.5"); - FormatInfo witness = new FormatInfo(); - witness.setMin(4); - witness.setMax(5); - assertEquals(witness, fi); - } - } - - @Test - public void testRightPad() { - { - FormatInfo fi = FormatInfo.valueOf("-40"); - FormatInfo witness = new FormatInfo(); - witness.setMin(40); - witness.setLeftPad(false); - assertEquals(witness, fi); - } - - { - FormatInfo fi = FormatInfo.valueOf("-12.5"); - FormatInfo witness = new FormatInfo(); - witness.setMin(12); - witness.setMax(5); - witness.setLeftPad(false); - assertEquals(witness, fi); - } - - { - FormatInfo fi = FormatInfo.valueOf("-14.-5"); - FormatInfo witness = new FormatInfo(); - witness.setMin(14); - witness.setMax(5); - witness.setLeftPad(false); - witness.setLeftTruncate(false); - assertEquals(witness, fi); +public class FormatInfoTest { + + @Test + public void testEndingInDot() { + try { + FormatInfo.valueOf("45."); + fail("45. is not a valid format info string"); + } catch (IllegalArgumentException iae) { + // OK + } } - } - @Test - public void testMinOnly() { - { - FormatInfo fi = FormatInfo.valueOf("49"); - FormatInfo witness = new FormatInfo(); - witness.setMin(49); - assertEquals(witness, fi); + @Test + public void testBasic() { + { + FormatInfo fi = FormatInfo.valueOf("45"); + FormatInfo witness = new FormatInfo(); + witness.setMin(45); + assertEquals(witness, fi); + } + + { + FormatInfo fi = FormatInfo.valueOf("4.5"); + FormatInfo witness = new FormatInfo(); + witness.setMin(4); + witness.setMax(5); + assertEquals(witness, fi); + } } - { - FormatInfo fi = FormatInfo.valueOf("-587"); - FormatInfo witness = new FormatInfo(); - witness.setMin(587); - witness.setLeftPad(false); - assertEquals(witness, fi); + @Test + public void testRightPad() { + { + FormatInfo fi = FormatInfo.valueOf("-40"); + FormatInfo witness = new FormatInfo(); + witness.setMin(40); + witness.setLeftPad(false); + assertEquals(witness, fi); + } + + { + FormatInfo fi = FormatInfo.valueOf("-12.5"); + FormatInfo witness = new FormatInfo(); + witness.setMin(12); + witness.setMax(5); + witness.setLeftPad(false); + assertEquals(witness, fi); + } + + { + FormatInfo fi = FormatInfo.valueOf("-14.-5"); + FormatInfo witness = new FormatInfo(); + witness.setMin(14); + witness.setMax(5); + witness.setLeftPad(false); + witness.setLeftTruncate(false); + assertEquals(witness, fi); + } } - } + @Test + public void testMinOnly() { + { + FormatInfo fi = FormatInfo.valueOf("49"); + FormatInfo witness = new FormatInfo(); + witness.setMin(49); + assertEquals(witness, fi); + } + + { + FormatInfo fi = FormatInfo.valueOf("-587"); + FormatInfo witness = new FormatInfo(); + witness.setMin(587); + witness.setLeftPad(false); + assertEquals(witness, fi); + } - @Test - public void testMaxOnly() { - { - FormatInfo fi = FormatInfo.valueOf(".49"); - FormatInfo witness = new FormatInfo(); - witness.setMax(49); - assertEquals(witness, fi); } - { - FormatInfo fi = FormatInfo.valueOf(".-5"); - FormatInfo witness = new FormatInfo(); - witness.setMax(5); - witness.setLeftTruncate(false); - assertEquals(witness, fi); + @Test + public void testMaxOnly() { + { + FormatInfo fi = FormatInfo.valueOf(".49"); + FormatInfo witness = new FormatInfo(); + witness.setMax(49); + assertEquals(witness, fi); + } + + { + FormatInfo fi = FormatInfo.valueOf(".-5"); + FormatInfo witness = new FormatInfo(); + witness.setMax(5); + witness.setLeftTruncate(false); + assertEquals(witness, fi); + } } - } } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/OptionTokenizerTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/OptionTokenizerTest.java index ec05ff4147fd5d6cc25a3b790db18b0c528642bb..75e5e66e8a54b7aee823877d5ebf879dd96c984f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/OptionTokenizerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/OptionTokenizerTest.java @@ -17,124 +17,124 @@ import org.junit.Test; public class OptionTokenizerTest { - @Test - public void testEmpty() { + @Test + public void testEmpty() { - } + } -// -// @Test -// public void testEmpty() throws ScanException { -// { -// List ol = new OptionTokenizer("").tokenize(); -// List witness = new ArrayList(); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer(" ").tokenize(); -// List witness = new ArrayList(); -// assertEquals(witness, ol); -// } -// } -// -// @Test -// public void testSimple() throws ScanException { -// { -// List ol = new OptionTokenizer("abc").tokenize(); -// List witness = new ArrayList(); -// witness.add("abc"); -// assertEquals(witness, ol); -// } -// } -// -// @Test -// public void testSingleQuote() throws ScanException { -// { -// List ol = new OptionTokenizer("' '").tokenize(); -// List witness = new ArrayList(); -// witness.add(" "); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("' x\t'").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\t"); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("' x\\t'").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\\t"); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("' x\\''").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\\'"); -// assertEquals(witness, ol); -// } -// } -// -// -// -// @Test -// public void testDoubleQuote() throws ScanException { -// { -// List ol = new OptionTokenizer("\" \"").tokenize(); -// List witness = new ArrayList(); -// witness.add(" "); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("\" x\t\"").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\t"); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("\" x\\t\"").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\\t"); -// assertEquals(witness, ol); -// } -// -// { -// List ol = new OptionTokenizer("\" x\\\"\"").tokenize(); -// List witness = new ArrayList(); -// witness.add(" x\\\""); -// assertEquals(witness, ol); -// } -// } -// -// @Test -// public void testMultiple() throws ScanException { -// { -// List ol = new OptionTokenizer("a, b").tokenize(); -// List witness = new ArrayList(); -// witness.add("a"); -// witness.add("b"); -// assertEquals(witness, ol); -// } -// { -// List ol = new OptionTokenizer("'a', b").tokenize(); -// List witness = new ArrayList(); -// witness.add("a"); -// witness.add("b"); -// assertEquals(witness, ol); -// } -// { -// List ol = new OptionTokenizer("'', b").tokenize(); -// List witness = new ArrayList(); -// witness.add(""); -// witness.add("b"); -// assertEquals(witness, ol); -// } -// } -// + // + // @Test + // public void testEmpty() throws ScanException { + // { + // List ol = new OptionTokenizer("").tokenize(); + // List witness = new ArrayList(); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer(" ").tokenize(); + // List witness = new ArrayList(); + // assertEquals(witness, ol); + // } + // } + // + // @Test + // public void testSimple() throws ScanException { + // { + // List ol = new OptionTokenizer("abc").tokenize(); + // List witness = new ArrayList(); + // witness.add("abc"); + // assertEquals(witness, ol); + // } + // } + // + // @Test + // public void testSingleQuote() throws ScanException { + // { + // List ol = new OptionTokenizer("' '").tokenize(); + // List witness = new ArrayList(); + // witness.add(" "); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("' x\t'").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\t"); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("' x\\t'").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\\t"); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("' x\\''").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\\'"); + // assertEquals(witness, ol); + // } + // } + // + // + // + // @Test + // public void testDoubleQuote() throws ScanException { + // { + // List ol = new OptionTokenizer("\" \"").tokenize(); + // List witness = new ArrayList(); + // witness.add(" "); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("\" x\t\"").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\t"); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("\" x\\t\"").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\\t"); + // assertEquals(witness, ol); + // } + // + // { + // List ol = new OptionTokenizer("\" x\\\"\"").tokenize(); + // List witness = new ArrayList(); + // witness.add(" x\\\""); + // assertEquals(witness, ol); + // } + // } + // + // @Test + // public void testMultiple() throws ScanException { + // { + // List ol = new OptionTokenizer("a, b").tokenize(); + // List witness = new ArrayList(); + // witness.add("a"); + // witness.add("b"); + // assertEquals(witness, ol); + // } + // { + // List ol = new OptionTokenizer("'a', b").tokenize(); + // List witness = new ArrayList(); + // witness.add("a"); + // witness.add("b"); + // assertEquals(witness, ol); + // } + // { + // List ol = new OptionTokenizer("'', b").tokenize(); + // List witness = new ArrayList(); + // witness.add(""); + // witness.add("b"); + // assertEquals(witness, ol); + // } + // } + // } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/PackageTest.java index fa8462f53a7ce63e030199dee26d45c157bd3bb3..23b25310efedf0d28b3ece17001a21f57699c57d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/PackageTest.java @@ -18,11 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({TokenStreamTest.class, - OptionTokenizerTest.class, - ParserTest.class, - FormatInfoTest.class, - CompilerTest.class, - SamplePatternLayoutTest.class}) +@SuiteClasses({ TokenStreamTest.class, OptionTokenizerTest.class, ParserTest.class, FormatInfoTest.class, CompilerTest.class, SamplePatternLayoutTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/ParserTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/ParserTest.java index cea5c52bb553cf0dce352c64c1c61ad97b57b8fa..7255bfa861a9fc37b5cd5dc66eafd6dacb834c8e 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/ParserTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/ParserTest.java @@ -30,262 +30,260 @@ import ch.qos.logback.core.pattern.FormatInfo; public class ParserTest { - String BARE = Token.BARE_COMPOSITE_KEYWORD_TOKEN.getValue().toString(); - Context context = new ContextBase(); - - - @Test - public void testBasic() throws Exception { - Parser p = new Parser("hello"); - Node t = p.parse(); - assertEquals(Node.LITERAL, t.getType()); - assertEquals("hello", t.getValue()); - } - - @Test - public void testKeyword() throws Exception { - - { - Parser p = new Parser("hello%xyz"); - Node t = p.parse(); - Node witness = new Node(Node.LITERAL, "hello"); - witness.next = new SimpleKeywordNode("xyz"); - assertEquals(witness, t); + String BARE = Token.BARE_COMPOSITE_KEYWORD_TOKEN.getValue().toString(); + Context context = new ContextBase(); + + @Test + public void testBasic() throws Exception { + Parser p = new Parser("hello"); + Node t = p.parse(); + assertEquals(Node.LITERAL, t.getType()); + assertEquals("hello", t.getValue()); } - { - Parser p = new Parser("hello%xyz{x}"); - Node t = p.parse(); - Node witness = new Node(Node.LITERAL, "hello"); - SimpleKeywordNode n = new SimpleKeywordNode("xyz"); - List optionList = new ArrayList(); - optionList.add("x"); - n.setOptions(optionList); - witness.next = n; - assertEquals(witness, t); + @Test + public void testKeyword() throws Exception { + + { + Parser p = new Parser("hello%xyz"); + Node t = p.parse(); + Node witness = new Node(Node.LITERAL, "hello"); + witness.next = new SimpleKeywordNode("xyz"); + assertEquals(witness, t); + } + + { + Parser p = new Parser("hello%xyz{x}"); + Node t = p.parse(); + Node witness = new Node(Node.LITERAL, "hello"); + SimpleKeywordNode n = new SimpleKeywordNode("xyz"); + List optionList = new ArrayList(); + optionList.add("x"); + n.setOptions(optionList); + witness.next = n; + assertEquals(witness, t); + } } - } - @Test - public void testComposite() throws Exception { - { - Parser p = new Parser("hello%(%child)"); - Node t = p.parse(); + @Test + public void testComposite() throws Exception { + { + Parser p = new Parser("hello%(%child)"); + Node t = p.parse(); + + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + Node child = new SimpleKeywordNode("child"); + composite.setChildNode(child); + witness.next = composite; + + // System.out.println("w:" + witness); + // System.out.println(t); + + assertEquals(witness, t); + } + + // System.out.println("testRecursive part 2"); + { + Parser p = new Parser("hello%(%child )"); + Node t = p.parse(); + + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + Node child = new SimpleKeywordNode("child"); + composite.setChildNode(child); + witness.next = composite; + child.next = new Node(Node.LITERAL, " "); + assertEquals(witness, t); + } + + { + Parser p = new Parser("hello%(%child %h)"); + Node t = p.parse(); + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + Node child = new SimpleKeywordNode("child"); + composite.setChildNode(child); + child.next = new Node(Node.LITERAL, " "); + child.next.next = new SimpleKeywordNode("h"); + witness.next = composite; + assertEquals(witness, t); + } + + { + Parser p = new Parser("hello%(%child %h) %m"); + Node t = p.parse(); + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + Node child = new SimpleKeywordNode("child"); + composite.setChildNode(child); + child.next = new Node(Node.LITERAL, " "); + child.next.next = new SimpleKeywordNode("h"); + witness.next = composite; + composite.next = new Node(Node.LITERAL, " "); + composite.next.next = new SimpleKeywordNode("m"); + assertEquals(witness, t); + } + + { + Parser p = new Parser("hello%( %child \\(%h\\) ) %m"); + Node t = p.parse(); + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + Node child = new Node(Node.LITERAL, " "); + composite.setChildNode(child); + Node c = child; + c = c.next = new SimpleKeywordNode("child"); + c = c.next = new Node(Node.LITERAL, " ("); + c = c.next = new SimpleKeywordNode("h"); + c = c.next = new Node(Node.LITERAL, ") "); + witness.next = composite; + composite.next = new Node(Node.LITERAL, " "); + composite.next.next = new SimpleKeywordNode("m"); + assertEquals(witness, t); + } - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - Node child = new SimpleKeywordNode("child"); - composite.setChildNode(child); - witness.next = composite; - - // System.out.println("w:" + witness); - // System.out.println(t); + } - assertEquals(witness, t); + @Test + public void testNested() throws Exception { + { + Parser p = new Parser("%top %(%child%(%h))"); + Node t = p.parse(); + Node witness = new SimpleKeywordNode("top"); + Node w = witness.next = new Node(Node.LITERAL, " "); + CompositeNode composite = new CompositeNode(BARE); + w = w.next = composite; + Node child = new SimpleKeywordNode("child"); + composite.setChildNode(child); + composite = new CompositeNode(BARE); + child.next = composite; + composite.setChildNode(new SimpleKeywordNode("h")); + + assertEquals(witness, t); + } } - // System.out.println("testRecursive part 2"); - { - Parser p = new Parser("hello%(%child )"); - Node t = p.parse(); - - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - Node child = new SimpleKeywordNode("child"); - composite.setChildNode(child); - witness.next = composite; - child.next = new Node(Node.LITERAL, " "); - assertEquals(witness, t); + @Test + public void testFormattingInfo() throws Exception { + { + Parser p = new Parser("%45x"); + Node t = p.parse(); + FormattingNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); + assertEquals(witness, t); + } + { + Parser p = new Parser("%4.5x"); + Node t = p.parse(); + FormattingNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(4, 5)); + assertEquals(witness, t); + } + + { + Parser p = new Parser("%-4.5x"); + Node t = p.parse(); + FormattingNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(4, 5, false, true)); + assertEquals(witness, t); + } + { + Parser p = new Parser("%-4.-5x"); + Node t = p.parse(); + FormattingNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(4, 5, false, false)); + assertEquals(witness, t); + } + + { + Parser p = new Parser("%-4.5x %12y"); + Node t = p.parse(); + FormattingNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(4, 5, false, true)); + Node n = witness.next = new Node(Node.LITERAL, " "); + n = n.next = new SimpleKeywordNode("y"); + ((FormattingNode) n).setFormatInfo(new FormatInfo(12, Integer.MAX_VALUE)); + assertEquals(witness, t); + } } - { - Parser p = new Parser("hello%(%child %h)"); - Node t = p.parse(); - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - Node child = new SimpleKeywordNode("child"); - composite.setChildNode(child); - child.next = new Node(Node.LITERAL, " "); - child.next.next = new SimpleKeywordNode("h"); - witness.next = composite; - assertEquals(witness, t); + @Test + public void testOptions0() throws Exception { + Parser p = new Parser("%45x{'test '}"); + Node t = p.parse(); + SimpleKeywordNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); + List ol = new ArrayList(); + ol.add("test "); + witness.setOptions(ol); + assertEquals(witness, t); } - { - Parser p = new Parser("hello%(%child %h) %m"); - Node t = p.parse(); - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - Node child = new SimpleKeywordNode("child"); - composite.setChildNode(child); - child.next = new Node(Node.LITERAL, " "); - child.next.next = new SimpleKeywordNode("h"); - witness.next = composite; - composite.next = new Node(Node.LITERAL, " "); - composite.next.next = new SimpleKeywordNode("m"); - assertEquals(witness, t); + @Test + public void testOptions1() throws Exception { + Parser p = new Parser("%45x{a, b}"); + Node t = p.parse(); + SimpleKeywordNode witness = new SimpleKeywordNode("x"); + witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); + List ol = new ArrayList(); + ol.add("a"); + ol.add("b"); + witness.setOptions(ol); + assertEquals(witness, t); } - { - Parser p = new Parser("hello%( %child \\(%h\\) ) %m"); - Node t = p.parse(); - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - Node child = new Node(Node.LITERAL, " "); - composite.setChildNode(child); - Node c = child; - c = c.next = new SimpleKeywordNode("child"); - c = c.next = new Node(Node.LITERAL, " ("); - c = c.next = new SimpleKeywordNode("h"); - c = c.next = new Node(Node.LITERAL, ") "); - witness.next = composite; - composite.next = new Node(Node.LITERAL, " "); - composite.next.next = new SimpleKeywordNode("m"); - assertEquals(witness, t); + // see http://jira.qos.ch/browse/LBCORE-180 + @Test + public void keywordGluedToLitteral() throws Exception { + Parser p = new Parser("%x{}a"); + Node t = p.parse(); + SimpleKeywordNode witness = new SimpleKeywordNode("x"); + witness.setOptions(new ArrayList()); + witness.next = new Node(Node.LITERAL, "a"); + assertEquals(witness, t); } + @Test + public void testCompositeFormatting() throws Exception { + Parser p = new Parser("hello%5(XYZ)"); + Node t = p.parse(); - } - - @Test - public void testNested() throws Exception { - { - Parser p = new Parser("%top %(%child%(%h))"); - Node t = p.parse(); - Node witness = new SimpleKeywordNode("top"); - Node w = witness.next = new Node(Node.LITERAL, " "); - CompositeNode composite = new CompositeNode(BARE); - w = w.next = composite; - Node child = new SimpleKeywordNode("child"); - composite.setChildNode(child); - composite = new CompositeNode(BARE); - child.next = composite; - composite.setChildNode(new SimpleKeywordNode("h")); - - assertEquals(witness, t); - } - } - - @Test - public void testFormattingInfo() throws Exception { - { - Parser p = new Parser("%45x"); - Node t = p.parse(); - FormattingNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); - assertEquals(witness, t); - } - { - Parser p = new Parser("%4.5x"); - Node t = p.parse(); - FormattingNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(4, 5)); - assertEquals(witness, t); - } + Node witness = new Node(Node.LITERAL, "hello"); + CompositeNode composite = new CompositeNode(BARE); + composite.setFormatInfo(new FormatInfo(5, Integer.MAX_VALUE)); + Node child = new Node(Node.LITERAL, "XYZ"); + composite.setChildNode(child); + witness.next = composite; - { - Parser p = new Parser("%-4.5x"); - Node t = p.parse(); - FormattingNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(4, 5, false, true)); - assertEquals(witness, t); - } - { - Parser p = new Parser("%-4.-5x"); - Node t = p.parse(); - FormattingNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(4, 5, false, false)); - assertEquals(witness, t); - } + assertEquals(witness, t); - { - Parser p = new Parser("%-4.5x %12y"); - Node t = p.parse(); - FormattingNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(4, 5, false, true)); - Node n = witness.next = new Node(Node.LITERAL, " "); - n = n.next = new SimpleKeywordNode("y"); - ((FormattingNode) n).setFormatInfo(new FormatInfo(12, Integer.MAX_VALUE)); - assertEquals(witness, t); } - } - - @Test - public void testOptions0() throws Exception { - Parser p = new Parser("%45x{'test '}"); - Node t = p.parse(); - SimpleKeywordNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); - List ol = new ArrayList(); - ol.add("test "); - witness.setOptions(ol); - assertEquals(witness, t); - } - - @Test - public void testOptions1() throws Exception { - Parser p = new Parser("%45x{a, b}"); - Node t = p.parse(); - SimpleKeywordNode witness = new SimpleKeywordNode("x"); - witness.setFormatInfo(new FormatInfo(45, Integer.MAX_VALUE)); - List ol = new ArrayList(); - ol.add("a"); - ol.add("b"); - witness.setOptions(ol); - assertEquals(witness, t); - } - - // see http://jira.qos.ch/browse/LBCORE-180 - @Test - public void keywordGluedToLitteral() throws Exception { - Parser p = new Parser("%x{}a"); - Node t = p.parse(); - SimpleKeywordNode witness = new SimpleKeywordNode("x"); - witness.setOptions(new ArrayList()); - witness.next = new Node(Node.LITERAL, "a"); - assertEquals(witness, t); - } - - @Test - public void testCompositeFormatting() throws Exception { - Parser p = new Parser("hello%5(XYZ)"); - Node t = p.parse(); - - Node witness = new Node(Node.LITERAL, "hello"); - CompositeNode composite = new CompositeNode(BARE); - composite.setFormatInfo(new FormatInfo(5, Integer.MAX_VALUE)); - Node child = new Node(Node.LITERAL, "XYZ"); - composite.setChildNode(child); - witness.next = composite; - - assertEquals(witness, t); - - } - - @Test - public void empty() { - try { - Parser p = new Parser(""); - p.parse(); - fail(""); - } catch (ScanException e) { + @Test + public void empty() { + try { + Parser p = new Parser(""); + p.parse(); + fail(""); + } catch (ScanException e) { + + } } - } - - @Test - public void lbcore193() throws Exception { - try { - Parser p = new Parser("hello%(abc"); - p.setContext(context); - Node t = p.parse(); - fail("where the is exception?"); - } catch (ScanException ise) { - assertEquals("Expecting RIGHT_PARENTHESIS token but got null", ise.getMessage()); + + @Test + public void lbcore193() throws Exception { + try { + Parser p = new Parser("hello%(abc"); + p.setContext(context); + Node t = p.parse(); + fail("where the is exception?"); + } catch (ScanException ise) { + assertEquals("Expecting RIGHT_PARENTHESIS token but got null", ise.getMessage()); + } + StatusChecker sc = new StatusChecker(context); + sc.assertContainsMatch("Expecting RIGHT_PARENTHESIS"); + sc.assertContainsMatch("See also " + Parser.MISSING_RIGHT_PARENTHESIS); } - StatusChecker sc = new StatusChecker(context); - sc.assertContainsMatch("Expecting RIGHT_PARENTHESIS"); - sc.assertContainsMatch("See also " + Parser.MISSING_RIGHT_PARENTHESIS); - } } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayout.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayout.java index a6bc0d98a8a44d4d2e71369f9b0027af63f9d40f..7461bc89954f8f4aa76cb5234a379a73d47408de 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayout.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayout.java @@ -20,23 +20,21 @@ import ch.qos.logback.core.pattern.Converter123; import ch.qos.logback.core.pattern.ConverterHello; import ch.qos.logback.core.pattern.PatternLayoutBase; - - public class SamplePatternLayout extends PatternLayoutBase { - Map converterMap = new HashMap(); + Map converterMap = new HashMap(); + + public SamplePatternLayout() { + converterMap.put("OTT", Converter123.class.getName()); + converterMap.put("hello", ConverterHello.class.getName()); + } - public SamplePatternLayout() { - converterMap.put("OTT", Converter123.class.getName()); - converterMap.put("hello", ConverterHello.class.getName()); - } - - public Map getDefaultConverterMap() { - return converterMap; - } + public Map getDefaultConverterMap() { + return converterMap; + } - public String doLayout(E event) { - return writeLoopOnConverters(event); - } + public String doLayout(E event) { + return writeLoopOnConverters(event); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayoutTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayoutTest.java index 85d08c7f4cc59c633eee80de15e1f29601249901..c4c811443879052ae1b23156854b5758f148653f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayoutTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/SamplePatternLayoutTest.java @@ -21,70 +21,68 @@ import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.pattern.PatternLayoutBase; - public class SamplePatternLayoutTest extends AbstractPatternLayoutBaseTest { - Context context = new ContextBase(); + Context context = new ContextBase(); - public PatternLayoutBase getPatternLayoutBase() { - return new SamplePatternLayout(); - } + public PatternLayoutBase getPatternLayoutBase() { + return new SamplePatternLayout(); + } - public Object getEventObject() { - return new Object(); - } - - @Test - public void testOK() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern("x%OTT"); - plb.start(); - String s = plb.doLayout(new Object()); - //System.out.println(s); + public Object getEventObject() { + return new Object(); + } - //StatusManager sm = context.getStatusManager(); - //StatusPrinter.print(sm); - assertEquals("x123", s); - } + @Test + public void testOK() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern("x%OTT"); + plb.start(); + String s = plb.doLayout(new Object()); + // System.out.println(s); - @Test - public void testEscapeClosingParentheses() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern("x(%OTT\\)y"); - plb.start(); - String s = plb.doLayout(new Object()); - assertEquals("x(123)y", s); - } - - @Test - public void testEscapeBothParentheses() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern("x\\(%OTT\\)y"); - plb.start(); - String s = plb.doLayout(new Object()); - assertEquals("x(123)y", s); - } + // StatusManager sm = context.getStatusManager(); + // StatusPrinter.print(sm); + assertEquals("x123", s); + } - @Test - public void testPercentAsLiteral() { - PatternLayoutBase plb = getPatternLayoutBase(); - Context context = new ContextBase(); - plb.setContext(context); - plb.setPattern("hello \\% world"); - plb.start(); - String s = plb.doLayout(new Object()); - assertEquals("hello % world", s); - } + @Test + public void testEscapeClosingParentheses() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern("x(%OTT\\)y"); + plb.start(); + String s = plb.doLayout(new Object()); + assertEquals("x(123)y", s); + } + + @Test + public void testEscapeBothParentheses() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern("x\\(%OTT\\)y"); + plb.start(); + String s = plb.doLayout(new Object()); + assertEquals("x(123)y", s); + } + + @Test + public void testPercentAsLiteral() { + PatternLayoutBase plb = getPatternLayoutBase(); + Context context = new ContextBase(); + plb.setContext(context); + plb.setPattern("hello \\% world"); + plb.start(); + String s = plb.doLayout(new Object()); + assertEquals("hello % world", s); + } - - @Override - public Context getContext() { - return context; - } + @Override + public Context getContext() { + return context; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/TokenStreamTest.java b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/TokenStreamTest.java index 44ebe997b147c48b09f931d8adb37ca55ff7adc8..e2229d5462b0961144992f6ce74d836ff26b1ed1 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/TokenStreamTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/pattern/parser/TokenStreamTest.java @@ -26,396 +26,392 @@ import ch.qos.logback.core.pattern.util.AlmostAsIsEscapeUtil; public class TokenStreamTest { - @Test - public void testEmpty() throws ScanException { - try { - new TokenStream("").tokenize(); - fail("empty string not allowed"); - } catch (IllegalArgumentException e) { - } - } - - @Test - public void testSingleLiteral() throws ScanException { - List tl = new TokenStream("hello").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "hello")); - assertEquals(witness, tl); - } - - @Test - public void testLiteralWithPercent() throws ScanException { - { - List tl = new TokenStream("hello\\%world").tokenize(); - - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "hello%world")); - assertEquals(witness, tl); - } - { - List tl = new TokenStream("hello\\%").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "hello%")); - assertEquals(witness, tl); + @Test + public void testEmpty() throws ScanException { + try { + new TokenStream("").tokenize(); + fail("empty string not allowed"); + } catch (IllegalArgumentException e) { + } } - { - List tl = new TokenStream("\\%").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "%")); - assertEquals(witness, tl); - } - } - - @Test - public void testBasic() throws ScanException { - - // test "%c" - { - List tl = new TokenStream("%c").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "c")); - assertEquals(witness, tl); + @Test + public void testSingleLiteral() throws ScanException { + List tl = new TokenStream("hello").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "hello")); + assertEquals(witness, tl); } - { - // test "xyz%-34c" - List tl = new TokenStream("%a%b").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); - assertEquals(witness, tl); + @Test + public void testLiteralWithPercent() throws ScanException { + { + List tl = new TokenStream("hello\\%world").tokenize(); + + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "hello%world")); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("hello\\%").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "hello%")); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("\\%").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "%")); + assertEquals(witness, tl); + } } - { - // test "xyz%-34c" - List tl = new TokenStream("xyz%-34c").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "xyz")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.FORMAT_MODIFIER, "-34")); - witness.add(new Token(Token.SIMPLE_KEYWORD, "c")); - assertEquals(witness, tl); - } - } - - @Test - public void testComplexNR() throws ScanException { - List tl = new TokenStream("%d{1234} [%34.-67toto] %n").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "d")); - List ol = new ArrayList(); - ol.add("1234"); - witness.add(new Token(Token.OPTION, ol)); - witness.add(new Token(Token.LITERAL, " [")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.FORMAT_MODIFIER, "34.-67")); - witness.add(new Token(Token.SIMPLE_KEYWORD, "toto")); - witness.add(new Token(Token.LITERAL, "] ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "n")); - assertEquals(witness, tl); - } - - @Test - public void testEmptyP() throws ScanException { - List tl = new TokenStream("()").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "(")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); - } - - @Test - public void testEmptyP2() throws ScanException { - List tl = new TokenStream("%()").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); - } - - @Test - public void testEscape() throws ScanException { - { - List tl = new TokenStream("\\%").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "%")); - assertEquals(witness, tl); + @Test + public void testBasic() throws ScanException { + + // test "%c" + { + List tl = new TokenStream("%c").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "c")); + assertEquals(witness, tl); + } + + { + // test "xyz%-34c" + List tl = new TokenStream("%a%b").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); + assertEquals(witness, tl); + } + + { + // test "xyz%-34c" + List tl = new TokenStream("xyz%-34c").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "xyz")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.FORMAT_MODIFIER, "-34")); + witness.add(new Token(Token.SIMPLE_KEYWORD, "c")); + assertEquals(witness, tl); + } } - { - List tl = new TokenStream("\\%\\(\\t\\)\\r\\n").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "%(\t)\r\n")); - assertEquals(witness, tl); + @Test + public void testComplexNR() throws ScanException { + List tl = new TokenStream("%d{1234} [%34.-67toto] %n").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "d")); + List ol = new ArrayList(); + ol.add("1234"); + witness.add(new Token(Token.OPTION, ol)); + witness.add(new Token(Token.LITERAL, " [")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.FORMAT_MODIFIER, "34.-67")); + witness.add(new Token(Token.SIMPLE_KEYWORD, "toto")); + witness.add(new Token(Token.LITERAL, "] ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "n")); + assertEquals(witness, tl); } - { - List tl = new TokenStream("\\\\%x").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "\\")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - assertEquals(witness, tl); + @Test + public void testEmptyP() throws ScanException { + List tl = new TokenStream("()").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "(")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); } - { - List tl = new TokenStream("%x\\)").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - witness.add(new Token(Token.LITERAL, ")")); - assertEquals(witness, tl); + @Test + public void testEmptyP2() throws ScanException { + List tl = new TokenStream("%()").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); } - { - List tl = new TokenStream("%x\\_a").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - witness.add(new Token(Token.LITERAL, "a")); - assertEquals(witness, tl); - } - { - List tl = new TokenStream("%x\\_%b").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); - assertEquals(witness, tl); - } - } - - @Test - public void testOptions() throws ScanException { - { - List tl = new TokenStream("%x{t}").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - List ol = new ArrayList(); - ol.add("t"); - witness.add(new Token(Token.OPTION, ol)); - assertEquals(witness, tl); + @Test + public void testEscape() throws ScanException { + { + List tl = new TokenStream("\\%").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "%")); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("\\%\\(\\t\\)\\r\\n").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "%(\t)\r\n")); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("\\\\%x").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "\\")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("%x\\)").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + witness.add(new Token(Token.LITERAL, ")")); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("%x\\_a").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + witness.add(new Token(Token.LITERAL, "a")); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("%x\\_%b").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); + assertEquals(witness, tl); + } } - { - List tl = new TokenStream("%x{t,y}").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - List ol = new ArrayList(); - ol.add("t"); - ol.add("y"); - witness.add(new Token(Token.OPTION, ol)); - assertEquals(witness, tl); + @Test + public void testOptions() throws ScanException { + { + List tl = new TokenStream("%x{t}").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + List ol = new ArrayList(); + ol.add("t"); + witness.add(new Token(Token.OPTION, ol)); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("%x{t,y}").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + List ol = new ArrayList(); + ol.add("t"); + ol.add("y"); + witness.add(new Token(Token.OPTION, ol)); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("%x{\"hello world.\", \"12y \"}").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + List ol = new ArrayList(); + ol.add("hello world."); + ol.add("12y "); + witness.add(new Token(Token.OPTION, ol)); + assertEquals(witness, tl); + } + + { + List tl = new TokenStream("%x{'opt}'}").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); + List ol = new ArrayList(); + ol.add("opt}"); + witness.add(new Token(Token.OPTION, ol)); + assertEquals(witness, tl); + } } - { - List tl = new TokenStream("%x{\"hello world.\", \"12y \"}").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - List ol = new ArrayList(); - ol.add("hello world."); - ol.add("12y "); - witness.add(new Token(Token.OPTION, ol)); - assertEquals(witness, tl); + @Test + public void testSimpleP() throws ScanException { + List tl = new TokenStream("%(hello %class{.4?})").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(new Token(Token.LITERAL, "hello ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); + List ol = new ArrayList(); + ol.add(".4?"); + witness.add(new Token(Token.OPTION, ol)); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); } - { - List tl = new TokenStream("%x{'opt}'}").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "x")); - List ol = new ArrayList(); - ol.add("opt}"); - witness.add(new Token(Token.OPTION, ol)); - assertEquals(witness, tl); + @Test + public void testSimpleP2() throws ScanException { + List tl = new TokenStream("X %a %-12.550(hello %class{.4?})").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "X ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); + witness.add(new Token(Token.LITERAL, " ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.FORMAT_MODIFIER, "-12.550")); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(new Token(Token.LITERAL, "hello ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); + List ol = new ArrayList(); + ol.add(".4?"); + witness.add(new Token(Token.OPTION, ol)); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); } - } - - @Test - public void testSimpleP() throws ScanException { - List tl = new TokenStream("%(hello %class{.4?})").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(new Token(Token.LITERAL, "hello ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); - List ol = new ArrayList(); - ol.add(".4?"); - witness.add(new Token(Token.OPTION, ol)); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); - } - - @Test - public void testSimpleP2() throws ScanException { - List tl = new TokenStream("X %a %-12.550(hello %class{.4?})").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "X ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); - witness.add(new Token(Token.LITERAL, " ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.FORMAT_MODIFIER, "-12.550")); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(new Token(Token.LITERAL, "hello ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); - List ol = new ArrayList(); - ol.add(".4?"); - witness.add(new Token(Token.OPTION, ol)); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); - } - - @Test - public void testMultipleRecursion() throws ScanException { - List tl = new TokenStream("%-1(%d %45(%class %file))").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.FORMAT_MODIFIER, "-1")); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "d")); - witness.add(new Token(Token.LITERAL, " ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.FORMAT_MODIFIER, "45")); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); - witness.add(new Token(Token.LITERAL, " ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "file")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - - assertEquals(witness, tl); - } - - @Test - public void testNested() throws ScanException { - List tl = new TokenStream("%(%a%(%b))").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); - witness.add(Token.PERCENT_TOKEN); - witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - - assertEquals(witness, tl); - - } - - @Test - public void testEscapedParanteheses() throws ScanException { - { - List tl = new TokenStream("\\(%h\\)").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "(")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "h")); - witness.add(new Token(Token.LITERAL, ")")); - assertEquals(witness, tl); - } - { - List tl = new TokenStream("(%h\\)").tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "(")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "h")); - witness.add(new Token(Token.LITERAL, ")")); - assertEquals(witness, tl); + + @Test + public void testMultipleRecursion() throws ScanException { + List tl = new TokenStream("%-1(%d %45(%class %file))").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.FORMAT_MODIFIER, "-1")); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "d")); + witness.add(new Token(Token.LITERAL, " ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.FORMAT_MODIFIER, "45")); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "class")); + witness.add(new Token(Token.LITERAL, " ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "file")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + + assertEquals(witness, tl); } - { - List tl = new TokenStream("%a(x\\)").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.COMPOSITE_KEYWORD, "a")); - witness.add(new Token(Token.LITERAL, "x)")); - assertEquals(witness, tl); + + @Test + public void testNested() throws ScanException { + List tl = new TokenStream("%(%a%(%b))").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); + witness.add(Token.PERCENT_TOKEN); + witness.add(Token.BARE_COMPOSITE_KEYWORD_TOKEN); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + + assertEquals(witness, tl); + } - { - List tl = new TokenStream("%a\\(x)").tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); - witness.add(new Token(Token.LITERAL, "(x")); - witness.add(new Token(Token.RIGHT_PARENTHESIS)); - - assertEquals(witness, tl); + + @Test + public void testEscapedParanteheses() throws ScanException { + { + List tl = new TokenStream("\\(%h\\)").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "(")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "h")); + witness.add(new Token(Token.LITERAL, ")")); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("(%h\\)").tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "(")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "h")); + witness.add(new Token(Token.LITERAL, ")")); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("%a(x\\)").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.COMPOSITE_KEYWORD, "a")); + witness.add(new Token(Token.LITERAL, "x)")); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("%a\\(x)").tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "a")); + witness.add(new Token(Token.LITERAL, "(x")); + witness.add(new Token(Token.RIGHT_PARENTHESIS)); + + assertEquals(witness, tl); + } } - } - - @Test - public void testWindowsLikeBackSlashes() throws ScanException { - List tl = new TokenStream("c:\\hello\\world.%i", - new AlmostAsIsEscapeUtil()).tokenize(); - - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "c:\\hello\\world.")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "i")); - assertEquals(witness, tl); - } - - @Test - public void compositedKeyword() throws ScanException { - { - List tl = new TokenStream("%d(A)", - new AlmostAsIsEscapeUtil()).tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.COMPOSITE_KEYWORD, "d")); - witness.add(new Token(Token.LITERAL, "A")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); + + @Test + public void testWindowsLikeBackSlashes() throws ScanException { + List tl = new TokenStream("c:\\hello\\world.%i", new AlmostAsIsEscapeUtil()).tokenize(); + + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "c:\\hello\\world.")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "i")); + assertEquals(witness, tl); } - { - List tl = new TokenStream("a %subst(%b C)", - new AlmostAsIsEscapeUtil()).tokenize(); - List witness = new ArrayList(); - witness.add(new Token(Token.LITERAL, "a ")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.COMPOSITE_KEYWORD, "subst")); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); - witness.add(new Token(Token.LITERAL, " C")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - assertEquals(witness, tl); + + @Test + public void compositedKeyword() throws ScanException { + { + List tl = new TokenStream("%d(A)", new AlmostAsIsEscapeUtil()).tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.COMPOSITE_KEYWORD, "d")); + witness.add(new Token(Token.LITERAL, "A")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); + } + { + List tl = new TokenStream("a %subst(%b C)", new AlmostAsIsEscapeUtil()).tokenize(); + List witness = new ArrayList(); + witness.add(new Token(Token.LITERAL, "a ")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.COMPOSITE_KEYWORD, "subst")); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.SIMPLE_KEYWORD, "b")); + witness.add(new Token(Token.LITERAL, " C")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + assertEquals(witness, tl); + } } - } - - @Test - public void compositedKeywordFollowedByOptions() throws ScanException { - { - List tl = new TokenStream("%d(A){o}", - new AlmostAsIsEscapeUtil()).tokenize(); - List witness = new ArrayList(); - witness.add(Token.PERCENT_TOKEN); - witness.add(new Token(Token.COMPOSITE_KEYWORD, "d")); - witness.add(new Token(Token.LITERAL, "A")); - witness.add(Token.RIGHT_PARENTHESIS_TOKEN); - List ol = new ArrayList(); - ol.add("o"); - witness.add(new Token(Token.OPTION, ol)); - - assertEquals(witness, tl); + + @Test + public void compositedKeywordFollowedByOptions() throws ScanException { + { + List tl = new TokenStream("%d(A){o}", new AlmostAsIsEscapeUtil()).tokenize(); + List witness = new ArrayList(); + witness.add(Token.PERCENT_TOKEN); + witness.add(new Token(Token.COMPOSITE_KEYWORD, "d")); + witness.add(new Token(Token.LITERAL, "A")); + witness.add(Token.RIGHT_PARENTHESIS_TOKEN); + List ol = new ArrayList(); + ol.add("o"); + witness.add(new Token(Token.OPTION, ol)); + + assertEquals(witness, tl); + } } - } } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/read/CyclicBufferAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/read/CyclicBufferAppenderTest.java index 36791f8a086bf97a8d4be4aab462dd158af1cbab..fef9258e68ec391cda569e15d98a676cae31d941 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/read/CyclicBufferAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/read/CyclicBufferAppenderTest.java @@ -20,30 +20,29 @@ import static org.junit.Assert.assertEquals; public class CyclicBufferAppenderTest { - private CyclicBufferAppender cyclicBufferAppender; + private CyclicBufferAppender cyclicBufferAppender; - @Before - public void before() { - cyclicBufferAppender = new CyclicBufferAppender(); - cyclicBufferAppender.start(); - } + @Before + public void before() { + cyclicBufferAppender = new CyclicBufferAppender(); + cyclicBufferAppender.start(); + } - @Test + @Test public void reset() { - cyclicBufferAppender.append("foobar"); - assertEquals(1, cyclicBufferAppender.getLength()); - cyclicBufferAppender.reset(); - assertEquals(0, cyclicBufferAppender.getLength()); - } - - @Test - public void genericGet() { - cyclicBufferAppender.append("Some string"); - // get() now has type information, assigning to String should work without cast. - String foo = cyclicBufferAppender.get(0); - assertEquals("Some string", foo); - } - + cyclicBufferAppender.append("foobar"); + assertEquals(1, cyclicBufferAppender.getLength()); + cyclicBufferAppender.reset(); + assertEquals(0, cyclicBufferAppender.getLength()); + } + + @Test + public void genericGet() { + cyclicBufferAppender.append("Some string"); + // get() now has type information, assigning to String should work without cast. + String foo = cyclicBufferAppender.get(0); + assertEquals("Some string", foo); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/recovery/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/recovery/PackageTest.java index 8c10af5575c0d84c891106240ad1ca587129d868..f4a1e55fa2b4f46a228a92c28fbb561422aafefd 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/recovery/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/recovery/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({RecoveryCoordinatorTest.class, ResilientOutputStreamTest.class}) -public class PackageTest { +@SuiteClasses({ RecoveryCoordinatorTest.class, ResilientOutputStreamTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/recovery/RecoveryCoordinatorTest.java b/logback-core/src/test/java/ch/qos/logback/core/recovery/RecoveryCoordinatorTest.java index eb154cf25d0c4f95a351ba7536e5539f3239ebfa..7da610385b7ff1845758ab31a79403e18ba4afbe 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/recovery/RecoveryCoordinatorTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/recovery/RecoveryCoordinatorTest.java @@ -21,7 +21,7 @@ public class RecoveryCoordinatorTest { long now = System.currentTimeMillis(); RecoveryCoordinator rc = new RecoveryCoordinator(now); - + @Test public void recoveryNotNeededAfterInit() { RecoveryCoordinator rc = new RecoveryCoordinator(); diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/DefaultRolloverChecker.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/DefaultRolloverChecker.java index 4c3c1a6b8874938b6924bc09d0c075558dfe4aaa..07f26eca50d42d0b328d93232685fcf6e2b1c806 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/DefaultRolloverChecker.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/DefaultRolloverChecker.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.rolling; - import ch.qos.logback.core.util.Compare; import ch.qos.logback.core.util.CoreTestConstants; @@ -24,32 +23,30 @@ import static org.junit.Assert.assertTrue; public class DefaultRolloverChecker implements RolloverChecker { - final String testId; - final boolean withCompression; - final String compressionSuffix; + final String testId; + final boolean withCompression; + final String compressionSuffix; - public DefaultRolloverChecker(String testId, boolean withCompression, String compressionSuffix) { - this.testId = testId; - this.withCompression = withCompression; - this.compressionSuffix = compressionSuffix; - } + public DefaultRolloverChecker(String testId, boolean withCompression, String compressionSuffix) { + this.testId = testId; + this.withCompression = withCompression; + this.compressionSuffix = compressionSuffix; + } - public void check(List expectedFilenameList) throws IOException { + public void check(List expectedFilenameList) throws IOException { - int i = 0; - for (String fn : expectedFilenameList) { - String suffix = withCompression ? addGZIfNotLast(expectedFilenameList, i, compressionSuffix) : ""; + int i = 0; + for (String fn : expectedFilenameList) { + String suffix = withCompression ? addGZIfNotLast(expectedFilenameList, i, compressionSuffix) : ""; - String witnessFileName = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId + "." + i + suffix; - assertTrue(Compare.compare(fn, witnessFileName)); - i++; + String witnessFileName = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId + "." + i + suffix; + assertTrue(Compare.compare(fn, witnessFileName)); + i++; + } } - } - String addGZIfNotLast(List expectedFilenameList, int i, String suff) { - int lastIndex = expectedFilenameList.size() - 1; - return (i != lastIndex) ? suff : ""; - } + String addGZIfNotLast(List expectedFilenameList, int i, String suff) { + int lastIndex = expectedFilenameList.size() - 1; + return (i != lastIndex) ? suff : ""; + } } - - diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/FileMatchFunction.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/FileMatchFunction.java index 01b8ff82dab35e9fc2bdc1ed1c1d07956c15a85e..314a3d932bac99978ad2d1fc8f07c94514dbc98c 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/FileMatchFunction.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/FileMatchFunction.java @@ -24,5 +24,5 @@ import java.io.File; */ public interface FileMatchFunction { - boolean match(File f, String pattern); + boolean match(File f, String pattern); } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/FileOpener.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/FileOpener.java index a09cf832c85d9fd99845f3191d8d7e28d88779e1..0fd3a99ba2c0ee28ea546387ec87f7829054e15e 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/FileOpener.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/FileOpener.java @@ -16,18 +16,17 @@ package ch.qos.logback.core.rolling; import java.io.FileInputStream; import java.io.InputStream; - /** * Keep the file "output/test.log open for 10 seconds so that we can test * RollingFileAppender's ability to roll file open by another process. * @author Ceki Gülcü */ public class FileOpener { - public static void main(String[] args) throws Exception { - InputStream is = new FileInputStream("output/test.log"); - is.read(); - Thread.sleep(10000); - is.close(); - System.out.println("Exiting FileOpener"); - } + public static void main(String[] args) throws Exception { + InputStream is = new FileInputStream("output/test.log"); + is.read(); + Thread.sleep(10000); + is.close(); + System.out.println("Exiting FileOpener"); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/MultiThreadedRollingTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/MultiThreadedRollingTest.java index 7b84ccab381532e19be530af682cd7f1231f113a..5e9d35483eec711c69251229c7cef2f894b2cfe0 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/MultiThreadedRollingTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/MultiThreadedRollingTest.java @@ -42,251 +42,243 @@ import ch.qos.logback.core.util.StatusPrinter; public class MultiThreadedRollingTest { - final static int NUM_THREADS = 10; - final static int TOTAL_DURATION = 600; - RunnableWithCounterAndDone[] runnableArray; + final static int NUM_THREADS = 10; + final static int TOTAL_DURATION = 600; + RunnableWithCounterAndDone[] runnableArray; - Encoder encoder; - Context context = new ContextBase(); + Encoder encoder; + Context context = new ContextBase(); - static String VERIFY_SH = "verify.sh"; + static String VERIFY_SH = "verify.sh"; - int diff = RandomUtil.getPositiveInt(); - String outputDirStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "multi-" + diff - + "/"; + int diff = RandomUtil.getPositiveInt(); + String outputDirStr = CoreTestConstants.OUTPUT_DIR_PREFIX + "multi-" + diff + "/"; - RollingFileAppender rfa = new RollingFileAppender(); + RollingFileAppender rfa = new RollingFileAppender(); - String pathToBash = EnvUtilForTests.getPathToBash(); - OutputStream scriptOS; + String pathToBash = EnvUtilForTests.getPathToBash(); + OutputStream scriptOS; - @Before - public void setUp() throws Exception { - encoder = new EchoEncoder(); - File outputDir = new File(outputDirStr); - outputDir.mkdirs(); + @Before + public void setUp() throws Exception { + encoder = new EchoEncoder(); + File outputDir = new File(outputDirStr); + outputDir.mkdirs(); - System.out.println("Output dir [" + outputDirStr + "]"); + System.out.println("Output dir [" + outputDirStr + "]"); - scriptOS = openScript(); + scriptOS = openScript(); - rfa.setName("rolling"); - rfa.setEncoder(encoder); - rfa.setContext(context); - rfa.setFile(outputDirStr + "output.log"); + rfa.setName("rolling"); + rfa.setEncoder(encoder); + rfa.setContext(context); + rfa.setFile(outputDirStr + "output.log"); - } + } + + void close(OutputStream os) { + if (os != null) { + try { + os.close(); + } catch (IOException e) { + } + } + } + + @After + public void tearDown() throws Exception { + rfa.stop(); + } + + public void setUpTimeBasedTriggeringPolicy(RollingFileAppender rfa) { + String datePattern = "yyyy-MM-dd'T'HH_mm_ss_SSS"; + TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); + tbrp.setFileNamePattern(outputDirStr + "test-%d{" + datePattern + "}"); + tbrp.setContext(context); + tbrp.setParent(rfa); + tbrp.start(); + + rfa.setRollingPolicy(tbrp); + rfa.start(); + } - void close(OutputStream os) { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - } + public void setUpSizeBasedTriggeringPolicy(RollingFileAppender rfa) { + SizeBasedTriggeringPolicy zbtp = new SizeBasedTriggeringPolicy(); + zbtp.setContext(context); + zbtp.setMaxFileSize("100KB"); + + zbtp.start(); + rfa.setTriggeringPolicy(zbtp); + + FixedWindowRollingPolicy fwrp = new FixedWindowRollingPolicy(); + fwrp.setContext(context); + fwrp.setFileNamePattern(outputDirStr + "test-%i.log"); + fwrp.setMaxIndex(20); + fwrp.setMinIndex(0); + fwrp.setParent(rfa); + fwrp.start(); + rfa.setRollingPolicy(fwrp); + rfa.start(); } - } - - @After - public void tearDown() throws Exception { - rfa.stop(); - } - - public void setUpTimeBasedTriggeringPolicy(RollingFileAppender rfa) { - String datePattern = "yyyy-MM-dd'T'HH_mm_ss_SSS"; - TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); - tbrp.setFileNamePattern(outputDirStr + "test-%d{" + datePattern + "}"); - tbrp.setContext(context); - tbrp.setParent(rfa); - tbrp.start(); - - rfa.setRollingPolicy(tbrp); - rfa.start(); - } - - public void setUpSizeBasedTriggeringPolicy(RollingFileAppender rfa) { - SizeBasedTriggeringPolicy zbtp = new SizeBasedTriggeringPolicy(); - zbtp.setContext(context); - zbtp.setMaxFileSize("100KB"); - - zbtp.start(); - rfa.setTriggeringPolicy(zbtp); - - FixedWindowRollingPolicy fwrp = new FixedWindowRollingPolicy(); - fwrp.setContext(context); - fwrp.setFileNamePattern(outputDirStr + "test-%i.log"); - fwrp.setMaxIndex(20); - fwrp.setMinIndex(0); - fwrp.setParent(rfa); - fwrp.start(); - rfa.setRollingPolicy(fwrp); - rfa.start(); - } - - RunnableWithCounterAndDone[] buildRunnableArray(boolean withDelay) { - RunnableWithCounterAndDone[] runnableArray = new RunnableWithCounterAndDone[NUM_THREADS]; - for (int i = 0; i < NUM_THREADS; i++) { - runnableArray[i] = new RFARunnable(i, rfa, withDelay); + + RunnableWithCounterAndDone[] buildRunnableArray(boolean withDelay) { + RunnableWithCounterAndDone[] runnableArray = new RunnableWithCounterAndDone[NUM_THREADS]; + for (int i = 0; i < NUM_THREADS; i++) { + runnableArray[i] = new RFARunnable(i, rfa, withDelay); + } + return runnableArray; } - return runnableArray; - } - - OutputStream openScript() throws IOException { - return new FileOutputStream(outputDirStr + VERIFY_SH); - } - - @Test - public void multiThreadedTimedBased() throws InterruptedException, - IOException { - setUpTimeBasedTriggeringPolicy(rfa); - executeHarness(TOTAL_DURATION, false); - printScriptForTimeBased(); - verify(); - } - - int testFileCount() { - File outputDir = new File(outputDirStr); - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File dir, String name) { - if (name.matches("test-\\d{1,2}.log")) { - return true; + + OutputStream openScript() throws IOException { + return new FileOutputStream(outputDirStr + VERIFY_SH); + } + + @Test + public void multiThreadedTimedBased() throws InterruptedException, IOException { + setUpTimeBasedTriggeringPolicy(rfa); + executeHarness(TOTAL_DURATION, false); + printScriptForTimeBased(); + verify(); + } + + int testFileCount() { + File outputDir = new File(outputDirStr); + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File dir, String name) { + if (name.matches("test-\\d{1,2}.log")) { + return true; + } + return false; + } + }; + File[] files = outputDir.listFiles(filter); + return files.length; + } + + void verify() throws IOException, InterruptedException { + close(scriptOS); + // no point in this test if we don't have bash + if (pathToBash == null) { + return; } - return false; - } - }; - File[] files = outputDir.listFiles(filter); - return files.length; - } - - void verify() throws IOException, InterruptedException { - close(scriptOS); - // no point in this test if we don't have bash - if (pathToBash == null) { - return; + ProcessBuilder pb = new ProcessBuilder(); + pb.command(pathToBash, VERIFY_SH); + pb.directory(new File(outputDirStr)); + Process process = pb.start(); + process.waitFor(); + int exitCode = process.exitValue(); + + assertEquals(SUCCESSFUL_EXIT_CODE, exitCode); + System.out.println("External script based verification returned with exit code " + exitCode); } - ProcessBuilder pb = new ProcessBuilder(); - pb.command(pathToBash, VERIFY_SH); - pb.directory(new File(outputDirStr)); - Process process = pb.start(); - process.waitFor(); - int exitCode = process.exitValue(); - - assertEquals(SUCCESSFUL_EXIT_CODE, exitCode); - System.out - .println("External script based verification returned with exit code " - + exitCode); - } - - @Test - public void multiThreadedSizeBased() throws InterruptedException, IOException { - setUpSizeBasedTriggeringPolicy(rfa); - // on a fast machine with a fast hard disk, if the tests runs for too - // long the MAX_WINDOW_SIZE is reached, resulting in data loss which - // we cannot test for. - executeHarness(TOTAL_DURATION, true); - int numFiles = testFileCount(); - printScriptForSizeBased(numFiles); - verify(); - } - - private void printScriptHeader(String type) throws IOException { - out("# ===================================================="); - out("# A script to check the exactness of the output "); - out("# produced by " + type + " test"); - out("# ===================================================="); - out("# "); - } - - private void printCommonScriptCore() throws IOException { - out(""); - out("for t in $(seq 0 1 " + (NUM_THREADS - 1) + ")"); - out("do"); - out(" echo \"Testing results of thread $t\""); - out(" grep \"$t \" aggregated | cut -d ' ' -f 2 > ${t}-sample"); - out(" for j in $(seq 1 1 ${end[$t]}); do echo $j; done > ${t}-witness"); - out(" diff -q -w ${t}-sample ${t}-witness;"); - out(" res=$?"); - out(" if [ $res != \"0\" ]; then"); - out(" echo \"FAILED for $t\""); - out(" exit " + FAILURE_EXIT_CODE); - out(" fi"); - out("done"); - out(""); - out("exit " + SUCCESSFUL_EXIT_CODE); - } - - private void printScriptForTimeBased() throws IOException { - printScriptHeader("TimeBased"); - for (int i = 0; i < NUM_THREADS; i++) { - out("end[" + i + "]=" + this.runnableArray[i].getCounter()); + + @Test + public void multiThreadedSizeBased() throws InterruptedException, IOException { + setUpSizeBasedTriggeringPolicy(rfa); + // on a fast machine with a fast hard disk, if the tests runs for too + // long the MAX_WINDOW_SIZE is reached, resulting in data loss which + // we cannot test for. + executeHarness(TOTAL_DURATION, true); + int numFiles = testFileCount(); + printScriptForSizeBased(numFiles); + verify(); + } + + private void printScriptHeader(String type) throws IOException { + out("# ===================================================="); + out("# A script to check the exactness of the output "); + out("# produced by " + type + " test"); + out("# ===================================================="); + out("# "); + } + + private void printCommonScriptCore() throws IOException { + out(""); + out("for t in $(seq 0 1 " + (NUM_THREADS - 1) + ")"); + out("do"); + out(" echo \"Testing results of thread $t\""); + out(" grep \"$t \" aggregated | cut -d ' ' -f 2 > ${t}-sample"); + out(" for j in $(seq 1 1 ${end[$t]}); do echo $j; done > ${t}-witness"); + out(" diff -q -w ${t}-sample ${t}-witness;"); + out(" res=$?"); + out(" if [ $res != \"0\" ]; then"); + out(" echo \"FAILED for $t\""); + out(" exit " + FAILURE_EXIT_CODE); + out(" fi"); + out("done"); + out(""); + out("exit " + SUCCESSFUL_EXIT_CODE); + } + + private void printScriptForTimeBased() throws IOException { + printScriptHeader("TimeBased"); + for (int i = 0; i < NUM_THREADS; i++) { + out("end[" + i + "]=" + this.runnableArray[i].getCounter()); + } + out(""); + out("rm aggregated"); + out("cat test* output.log >> aggregated"); + printCommonScriptCore(); + } - out(""); - out("rm aggregated"); - out("cat test* output.log >> aggregated"); - printCommonScriptCore(); - } + private void printScriptForSizeBased(int numfiles) throws IOException { + printScriptHeader("SizeBased"); - private void printScriptForSizeBased(int numfiles) throws IOException { - printScriptHeader("SizeBased"); + for (int i = 0; i < NUM_THREADS; i++) { + out("end[" + i + "]=" + this.runnableArray[i].getCounter()); + } + out(""); + out("rm aggregated"); + out("for i in $(seq " + (numfiles - 1) + " -1 0); do cat test-$i.log >> aggregated; done"); + out("cat output.log >> aggregated"); + out(""); + printCommonScriptCore(); + } - for (int i = 0; i < NUM_THREADS; i++) { - out("end[" + i + "]=" + this.runnableArray[i].getCounter()); + private void out(String msg) throws IOException { + scriptOS.write(msg.getBytes()); + scriptOS.write("\n".getBytes()); } - out(""); - out("rm aggregated"); - out("for i in $(seq " + (numfiles - 1) - + " -1 0); do cat test-$i.log >> aggregated; done"); - out("cat output.log >> aggregated"); - out(""); - printCommonScriptCore(); - } - - private void out(String msg) throws IOException { - scriptOS.write(msg.getBytes()); - scriptOS.write("\n".getBytes()); - } - - private void executeHarness(int duration, boolean withDelay) - throws InterruptedException { - MultiThreadedHarness multiThreadedHarness = new MultiThreadedHarness( - duration); - this.runnableArray = buildRunnableArray(withDelay); - multiThreadedHarness.execute(runnableArray); - - StatusChecker checker = new StatusChecker(context.getStatusManager()); - if (!checker.isErrorFree(0)) { - StatusPrinter.print(context); - fail("errors reported"); + + private void executeHarness(int duration, boolean withDelay) throws InterruptedException { + MultiThreadedHarness multiThreadedHarness = new MultiThreadedHarness(duration); + this.runnableArray = buildRunnableArray(withDelay); + multiThreadedHarness.execute(runnableArray); + + StatusChecker checker = new StatusChecker(context.getStatusManager()); + if (!checker.isErrorFree(0)) { + StatusPrinter.print(context); + fail("errors reported"); + } } - } - - long diff(long start) { - return System.currentTimeMillis() - start; - } - - static class RFARunnable extends RunnableWithCounterAndDone { - RollingFileAppender rfa; - int id; - boolean withInducedDelay; - - RFARunnable(int id, RollingFileAppender rfa, - boolean withInducedDelay) { - this.id = id; - this.rfa = rfa; - this.withInducedDelay = withInducedDelay; + + long diff(long start) { + return System.currentTimeMillis() - start; } - public void run() { - while (!isDone()) { - counter++; - rfa.doAppend(id + " " + counter); - if ((counter % 64 == 0) && withInducedDelay) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } + static class RFARunnable extends RunnableWithCounterAndDone { + RollingFileAppender rfa; + int id; + boolean withInducedDelay; + + RFARunnable(int id, RollingFileAppender rfa, boolean withInducedDelay) { + this.id = id; + this.rfa = rfa; + this.withInducedDelay = withInducedDelay; + } + + public void run() { + while (!isDone()) { + counter++; + rfa.doAppend(id + " " + counter); + if ((counter % 64 == 0) && withInducedDelay) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + } + } } - } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/PackageTest.java index 35e212ff9049ab3e9fef87798d2632ada22403a4..a1d506aa30214f154fa3988a4ff47d14a4688a98 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/PackageTest.java @@ -17,11 +17,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({RenameUtilTest.class, SizeBasedRollingTest.class, - TimeBasedRollingTest.class, TimeBasedRollingWithArchiveRemoval_Test.class, - MultiThreadedRollingTest.class, - SizeAndTimeBasedFNATP_Test.class, - RollingFileAppenderTest.class, - ch.qos.logback.core.rolling.helper.PackageTest.class}) +@Suite.SuiteClasses({ RenameUtilTest.class, SizeBasedRollingTest.class, TimeBasedRollingTest.class, TimeBasedRollingWithArchiveRemoval_Test.class, + MultiThreadedRollingTest.class, SizeAndTimeBasedFNATP_Test.class, RollingFileAppenderTest.class, ch.qos.logback.core.rolling.helper.PackageTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/RenameUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/RenameUtilTest.java index 7cd976b24a05b0a06650b6d3a9f931248e515303..5467f5995e890dd8f110ddce73f25bd434b7ba43 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/RenameUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/RenameUtilTest.java @@ -34,75 +34,71 @@ import static org.junit.Assert.assertTrue; public class RenameUtilTest { - Encoder encoder; - Context context = new ContextBase(); - StatusChecker statusChecker = new StatusChecker(context); - - long currentTime = System.currentTimeMillis(); - int diff = RandomUtil.getPositiveInt(); - protected String randomOutputDirAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + diff - + "/"; - protected File randomOutputDir = new File(randomOutputDirAsStr); - - @Before - public void setUp() throws Exception { - encoder = new EchoEncoder(); - // if this this the fist test run after 'build clean up' then the - // OUTPUT_DIR_PREFIX might be not yet created - randomOutputDir.mkdirs(); - } - - @Test - public void renameToNonExistingDirectory() throws IOException, RolloverFailure { - RenameUtil renameUtil = new RenameUtil(); - renameUtil.setContext(context); - - int diff2 = RandomUtil.getPositiveInt(); - File fromFile = File.createTempFile("from" + diff, "test", - randomOutputDir); - - String randomTARGETDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff2; - - renameUtil.rename(fromFile.toString(), new File(randomTARGETDir + "/to.test").toString()); - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - assertTrue(statusChecker.isErrorFree(0)); - } - - - @Test - @Ignore - public void MANUAL_renamingOnDifferentVolumesOnLinux() throws IOException, RolloverFailure { - RenameUtil renameUtil = new RenameUtil(); - renameUtil.setContext(context); - - String src = "/tmp/ramdisk/foo.txt"; - FileOutputStream fis = new FileOutputStream(src); - fis.write(("hello" + diff).getBytes()); - - renameUtil.rename(src, "/tmp/foo" + diff + ".txt"); - StatusPrinter.print(context); - } - - - @Test - @Ignore - public void MANUAL_renamingOnDifferentVolumesOnWindows() throws IOException, RolloverFailure { - RenameUtil renameUtil = new RenameUtil(); - renameUtil.setContext(context); - - String src = "c:/tmp/foo.txt"; - FileOutputStream fis = new FileOutputStream(src); - fis.write(("hello" + diff).getBytes()); - fis.close(); - - renameUtil.rename(src, "d:/tmp/foo" + diff + ".txt"); - StatusPrinter.print(context); - assertTrue(statusChecker.isErrorFree(0)); - } - - @Test - public void renameByCopying() { - - } + Encoder encoder; + Context context = new ContextBase(); + StatusChecker statusChecker = new StatusChecker(context); + + long currentTime = System.currentTimeMillis(); + int diff = RandomUtil.getPositiveInt(); + protected String randomOutputDirAsStr = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; + protected File randomOutputDir = new File(randomOutputDirAsStr); + + @Before + public void setUp() throws Exception { + encoder = new EchoEncoder(); + // if this this the fist test run after 'build clean up' then the + // OUTPUT_DIR_PREFIX might be not yet created + randomOutputDir.mkdirs(); + } + + @Test + public void renameToNonExistingDirectory() throws IOException, RolloverFailure { + RenameUtil renameUtil = new RenameUtil(); + renameUtil.setContext(context); + + int diff2 = RandomUtil.getPositiveInt(); + File fromFile = File.createTempFile("from" + diff, "test", randomOutputDir); + + String randomTARGETDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff2; + + renameUtil.rename(fromFile.toString(), new File(randomTARGETDir + "/to.test").toString()); + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + assertTrue(statusChecker.isErrorFree(0)); + } + + @Test + @Ignore + public void MANUAL_renamingOnDifferentVolumesOnLinux() throws IOException, RolloverFailure { + RenameUtil renameUtil = new RenameUtil(); + renameUtil.setContext(context); + + String src = "/tmp/ramdisk/foo.txt"; + FileOutputStream fis = new FileOutputStream(src); + fis.write(("hello" + diff).getBytes()); + + renameUtil.rename(src, "/tmp/foo" + diff + ".txt"); + StatusPrinter.print(context); + } + + @Test + @Ignore + public void MANUAL_renamingOnDifferentVolumesOnWindows() throws IOException, RolloverFailure { + RenameUtil renameUtil = new RenameUtil(); + renameUtil.setContext(context); + + String src = "c:/tmp/foo.txt"; + FileOutputStream fis = new FileOutputStream(src); + fis.write(("hello" + diff).getBytes()); + fis.close(); + + renameUtil.rename(src, "d:/tmp/foo" + diff + ".txt"); + StatusPrinter.print(context); + assertTrue(statusChecker.isErrorFree(0)); + } + + @Test + public void renameByCopying() { + + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/RollingFileAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/RollingFileAppenderTest.java index 23499520447c33386003b23fadeb2973f5597f49..a9f560cc4b6c8658fd1528c3b4293ce7afcc138f 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/RollingFileAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/RollingFileAppenderTest.java @@ -35,236 +35,231 @@ import ch.qos.logback.core.util.StatusPrinter; public class RollingFileAppenderTest extends AbstractAppenderTest { - RollingFileAppender rfa = new RollingFileAppender(); - Context context = new ContextBase(); - - TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); - int diff = RandomUtil.getPositiveInt(); - String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; - - @Before - public void setUp() throws Exception { - // noStartTest fails if the context is set in setUp - // rfa.setContext(context); - - rfa.setEncoder(new DummyEncoder()); - rfa.setName("test"); - tbrp.setContext(context); - tbrp.setParent(rfa); - } - - @After - public void tearDown() throws Exception { - } - - @Override - protected Appender getAppender() { - return rfa; - } - - @Override - protected Appender getConfiguredAppender() { - rfa.setContext(context); - tbrp - .setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - - rfa.start(); - return rfa; - } - - @Test - public void testPrudentModeLogicalImplications() { - rfa.setContext(context); - // prudent mode will force "file" property to be null - rfa.setFile("some non null value"); - rfa.setAppend(false); - rfa.setPrudent(true); - - tbrp - .setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - - rfa.start(); - - assertTrue(rfa.isAppend()); - assertNull(rfa.rawFileProperty()); - assertTrue(rfa.isStarted()); - } - - @Test - public void testPrudentModeLogicalImplicationsOnCompression() { - rfa.setContext(context); - rfa.setAppend(false); - rfa.setPrudent(true); - - tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log.zip"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - - rfa.start(); - - StatusChecker checker = new StatusChecker(context); - assertFalse(rfa.isStarted()); - assertEquals(Status.ERROR, checker.getHighestLevel(0)); - } - - @Test - public void testFilePropertyAfterRollingPolicy() { - rfa.setContext(context); - rfa.setRollingPolicy(tbrp); - rfa.setFile("x"); - StatusPrinter.print(context); - StatusChecker statusChecker = new StatusChecker(context.getStatusManager()); - statusChecker.assertContainsMatch(Status.ERROR, - "File property must be set before any triggeringPolicy "); - } - - @Test - public void testFilePropertyAfterTriggeringPolicy() { - rfa.setContext(context); - rfa.setTriggeringPolicy(new SizeBasedTriggeringPolicy()); - rfa.setFile("x"); - StatusChecker statusChecker = new StatusChecker(context.getStatusManager()); - statusChecker.assertContainsMatch(Status.ERROR, - "File property must be set before any triggeringPolicy "); - } - - @Test - public void testFileNameWithParenthesis() { - // if ')' is not escaped, the test throws - // java.lang.IllegalStateException: FileNamePattern [.../program(x86)/toto-%d.log] does not contain a valid DateToken - rfa.setContext(context); - tbrp.setFileNamePattern(randomOutputDir + "program(x86)/toto-%d.log"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - rfa.start(); - rfa.doAppend("hello"); - } - - @Test - public void stopTimeBasedRollingPolicy() { - rfa.setContext(context); - - tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log.zip"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - rfa.start(); - - StatusPrinter.print(context); - assertTrue(tbrp.isStarted()); - assertTrue(rfa.isStarted()); - rfa.stop(); - assertFalse(rfa.isStarted()); - assertFalse(tbrp.isStarted()); - - } - - @Test - public void stopFixedWindowRollingPolicy() { - rfa.setContext(context); - rfa.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-.log"); - - FixedWindowRollingPolicy fwRollingPolicy = new FixedWindowRollingPolicy(); - fwRollingPolicy.setContext(context); - fwRollingPolicy.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%i.log.zip"); - fwRollingPolicy.setParent(rfa); - fwRollingPolicy.start(); - SizeBasedTriggeringPolicy sbTriggeringPolicy = new SizeBasedTriggeringPolicy(); - sbTriggeringPolicy.setContext(context); - sbTriggeringPolicy.start(); - - rfa.setRollingPolicy(fwRollingPolicy); - rfa.setTriggeringPolicy(sbTriggeringPolicy); - - rfa.start(); - - StatusPrinter.print(context); - assertTrue(fwRollingPolicy.isStarted()); - assertTrue(sbTriggeringPolicy.isStarted()); - assertTrue(rfa.isStarted()); - rfa.stop(); - assertFalse(rfa.isStarted()); - assertFalse(fwRollingPolicy.isStarted()); - assertFalse(sbTriggeringPolicy.isStarted()); - - } - - /** - * Test for http://jira.qos.ch/browse/LOGBACK-796 - */ - @Test - public void testFileShouldNotMatchFileNamePattern() { - rfa.setContext(context); - rfa.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX + "x-2013-04.log"); - tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "x-%d{yyyy-MM}.log"); - tbrp.start(); - - rfa.setRollingPolicy(tbrp); - rfa.start(); - StatusChecker statusChecker = new StatusChecker(context); - final String msg = "File property collides with fileNamePattern. Aborting."; - boolean containsMatch = statusChecker.containsMatch(Status.ERROR, msg); - assertTrue("Missing error: " + msg, containsMatch); - } - - @Test - public void collidingTimeformat() { - rfa.setContext(context); - rfa.setAppend(false); - rfa.setPrudent(true); - - tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d{dd}.log.zip"); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - - rfa.start(); - - StatusChecker checker = new StatusChecker(context); - assertFalse(rfa.isStarted()); - assertEquals(Status.ERROR, checker.getHighestLevel(0)); - StatusPrinter.print(context); - checker.assertContainsMatch("The date format in FileNamePattern will result"); - } - - @Test - public void collidingFileNamePattern() { - String filenamePattern = CoreTestConstants.OUTPUT_DIR_PREFIX + diff+ "-collision-%d.log.zip"; - - RollingFileAppender appender0 = new RollingFileAppender(); - appender0.setName("FA0"); - appender0.setContext(context); - appender0.setEncoder(new DummyEncoder()); - TimeBasedRollingPolicy tbrp0 = new TimeBasedRollingPolicy(); - tbrp0.setContext(context); - tbrp0.setFileNamePattern(filenamePattern); - tbrp0.setParent(appender0); - tbrp0.start(); - appender0.setRollingPolicy(tbrp0); - appender0.start(); - assertTrue(appender0.isStarted()); - - - - RollingFileAppender appender1 = new RollingFileAppender(); - appender1.setName("FA1"); - appender1.setFile("X"); - appender1.setContext(context); - appender1.setEncoder(new DummyEncoder()); - TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); - tbrp1.setContext(context); - tbrp1.setFileNamePattern(filenamePattern); - tbrp1.setParent(appender1); - tbrp1.start(); - appender1.setRollingPolicy(tbrp1); - appender1.start(); - - //StatusPrinter.print(context); - - assertFalse(appender1.isStarted()); - StatusChecker checker = new StatusChecker(context); - checker.assertContainsMatch(Status.ERROR, "'FileNamePattern' option has the same value"); - } + RollingFileAppender rfa = new RollingFileAppender(); + Context context = new ContextBase(); + + TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); + int diff = RandomUtil.getPositiveInt(); + String randomOutputDir = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "/"; + + @Before + public void setUp() throws Exception { + // noStartTest fails if the context is set in setUp + // rfa.setContext(context); + + rfa.setEncoder(new DummyEncoder()); + rfa.setName("test"); + tbrp.setContext(context); + tbrp.setParent(rfa); + } + + @After + public void tearDown() throws Exception { + } + + @Override + protected Appender getAppender() { + return rfa; + } + + @Override + protected Appender getConfiguredAppender() { + rfa.setContext(context); + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + + rfa.start(); + return rfa; + } + + @Test + public void testPrudentModeLogicalImplications() { + rfa.setContext(context); + // prudent mode will force "file" property to be null + rfa.setFile("some non null value"); + rfa.setAppend(false); + rfa.setPrudent(true); + + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + + rfa.start(); + + assertTrue(rfa.isAppend()); + assertNull(rfa.rawFileProperty()); + assertTrue(rfa.isStarted()); + } + + @Test + public void testPrudentModeLogicalImplicationsOnCompression() { + rfa.setContext(context); + rfa.setAppend(false); + rfa.setPrudent(true); + + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log.zip"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + + rfa.start(); + + StatusChecker checker = new StatusChecker(context); + assertFalse(rfa.isStarted()); + assertEquals(Status.ERROR, checker.getHighestLevel(0)); + } + + @Test + public void testFilePropertyAfterRollingPolicy() { + rfa.setContext(context); + rfa.setRollingPolicy(tbrp); + rfa.setFile("x"); + StatusPrinter.print(context); + StatusChecker statusChecker = new StatusChecker(context.getStatusManager()); + statusChecker.assertContainsMatch(Status.ERROR, "File property must be set before any triggeringPolicy "); + } + + @Test + public void testFilePropertyAfterTriggeringPolicy() { + rfa.setContext(context); + rfa.setTriggeringPolicy(new SizeBasedTriggeringPolicy()); + rfa.setFile("x"); + StatusChecker statusChecker = new StatusChecker(context.getStatusManager()); + statusChecker.assertContainsMatch(Status.ERROR, "File property must be set before any triggeringPolicy "); + } + + @Test + public void testFileNameWithParenthesis() { + // if ')' is not escaped, the test throws + // java.lang.IllegalStateException: FileNamePattern [.../program(x86)/toto-%d.log] does not contain a valid + // DateToken + rfa.setContext(context); + tbrp.setFileNamePattern(randomOutputDir + "program(x86)/toto-%d.log"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + rfa.start(); + rfa.doAppend("hello"); + } + + @Test + public void stopTimeBasedRollingPolicy() { + rfa.setContext(context); + + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d.log.zip"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + rfa.start(); + + StatusPrinter.print(context); + assertTrue(tbrp.isStarted()); + assertTrue(rfa.isStarted()); + rfa.stop(); + assertFalse(rfa.isStarted()); + assertFalse(tbrp.isStarted()); + + } + + @Test + public void stopFixedWindowRollingPolicy() { + rfa.setContext(context); + rfa.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-.log"); + + FixedWindowRollingPolicy fwRollingPolicy = new FixedWindowRollingPolicy(); + fwRollingPolicy.setContext(context); + fwRollingPolicy.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%i.log.zip"); + fwRollingPolicy.setParent(rfa); + fwRollingPolicy.start(); + SizeBasedTriggeringPolicy sbTriggeringPolicy = new SizeBasedTriggeringPolicy(); + sbTriggeringPolicy.setContext(context); + sbTriggeringPolicy.start(); + + rfa.setRollingPolicy(fwRollingPolicy); + rfa.setTriggeringPolicy(sbTriggeringPolicy); + + rfa.start(); + + StatusPrinter.print(context); + assertTrue(fwRollingPolicy.isStarted()); + assertTrue(sbTriggeringPolicy.isStarted()); + assertTrue(rfa.isStarted()); + rfa.stop(); + assertFalse(rfa.isStarted()); + assertFalse(fwRollingPolicy.isStarted()); + assertFalse(sbTriggeringPolicy.isStarted()); + + } + + /** + * Test for http://jira.qos.ch/browse/LOGBACK-796 + */ + @Test + public void testFileShouldNotMatchFileNamePattern() { + rfa.setContext(context); + rfa.setFile(CoreTestConstants.OUTPUT_DIR_PREFIX + "x-2013-04.log"); + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "x-%d{yyyy-MM}.log"); + tbrp.start(); + + rfa.setRollingPolicy(tbrp); + rfa.start(); + StatusChecker statusChecker = new StatusChecker(context); + final String msg = "File property collides with fileNamePattern. Aborting."; + boolean containsMatch = statusChecker.containsMatch(Status.ERROR, msg); + assertTrue("Missing error: " + msg, containsMatch); + } + + @Test + public void collidingTimeformat() { + rfa.setContext(context); + rfa.setAppend(false); + rfa.setPrudent(true); + + tbrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "toto-%d{dd}.log.zip"); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + + rfa.start(); + + StatusChecker checker = new StatusChecker(context); + assertFalse(rfa.isStarted()); + assertEquals(Status.ERROR, checker.getHighestLevel(0)); + StatusPrinter.print(context); + checker.assertContainsMatch("The date format in FileNamePattern will result"); + } + + @Test + public void collidingFileNamePattern() { + String filenamePattern = CoreTestConstants.OUTPUT_DIR_PREFIX + diff + "-collision-%d.log.zip"; + + RollingFileAppender appender0 = new RollingFileAppender(); + appender0.setName("FA0"); + appender0.setContext(context); + appender0.setEncoder(new DummyEncoder()); + TimeBasedRollingPolicy tbrp0 = new TimeBasedRollingPolicy(); + tbrp0.setContext(context); + tbrp0.setFileNamePattern(filenamePattern); + tbrp0.setParent(appender0); + tbrp0.start(); + appender0.setRollingPolicy(tbrp0); + appender0.start(); + assertTrue(appender0.isStarted()); + + RollingFileAppender appender1 = new RollingFileAppender(); + appender1.setName("FA1"); + appender1.setFile("X"); + appender1.setContext(context); + appender1.setEncoder(new DummyEncoder()); + TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); + tbrp1.setContext(context); + tbrp1.setFileNamePattern(filenamePattern); + tbrp1.setParent(appender1); + tbrp1.start(); + appender1.setRollingPolicy(tbrp1); + appender1.start(); + + // StatusPrinter.print(context); + + assertFalse(appender1.isStarted()); + StatusChecker checker = new StatusChecker(context); + checker.assertContainsMatch(Status.ERROR, "'FileNamePattern' option has the same value"); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/RolloverChecker.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/RolloverChecker.java index 46a9b7b225fb540015779cce790778ebfa8e3af4..a674cb1a6e826a37d040e6f7b23e11b586faa625 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/RolloverChecker.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/RolloverChecker.java @@ -16,7 +16,6 @@ package ch.qos.logback.core.rolling; import java.io.IOException; import java.util.List; - public interface RolloverChecker { - public void check(List expectedFilenameList) throws IOException; + public void check(List expectedFilenameList) throws IOException; } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_Test.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_Test.java index 0e5483b4a65a21a6c52825c8fc4a9fd46e05463e..335d455af0ff64f1883280659413da377b862052 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_Test.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_Test.java @@ -119,7 +119,7 @@ public class SizeAndTimeBasedFNATP_Test extends ScaffoldingForRollingTests { // wait for compression to finish waitForJobsToComplete(); - //StatusPrinter.print(context); + // StatusPrinter.print(context); existenceCheck(expectedFilenameList); sortedContentCheck(randomOutputDir, runLength, prefix); } @@ -199,13 +199,13 @@ public class SizeAndTimeBasedFNATP_Test extends ScaffoldingForRollingTests { initRollingFileAppender(rfa1, file); sizeThreshold = 300; initPolicies(rfa1, tbrp1, randomOutputDir + testId + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}.txt" + compressionSuffix, sizeThreshold, currentTime, 0); - - //StatusPrinter.print(context); + + // StatusPrinter.print(context); assertFalse(rfa1.isStarted()); StatusChecker checker = new StatusChecker(context); - checker.assertContainsMatch("Missing integer token"); + checker.assertContainsMatch("Missing integer token"); } - + @Test public void checkDateCollision() { String stem = "toto.log"; @@ -216,10 +216,10 @@ public class SizeAndTimeBasedFNATP_Test extends ScaffoldingForRollingTests { initRollingFileAppender(rfa1, file); sizeThreshold = 300; initPolicies(rfa1, tbrp1, randomOutputDir + testId + "-%d{EE}.txt" + compressionSuffix, sizeThreshold, currentTime, 0); - - //StatusPrinter.print(context); + + // StatusPrinter.print(context); assertFalse(rfa1.isStarted()); StatusChecker checker = new StatusChecker(context); - checker.assertContainsMatch("The date format in FileNamePattern"); + checker.assertContainsMatch("The date format in FileNamePattern"); } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedRollingTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedRollingTest.java index 35a637d7c7d6adf200b2f9da868b1f628e2a54c8..27cec14dc96f17f37d841afe1c8d16fa1f8d775a 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedRollingTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedRollingTest.java @@ -24,95 +24,94 @@ import java.util.List; public class SizeBasedRollingTest extends ScaffoldingForRollingTests { - RollingFileAppender rfa = new RollingFileAppender(); - FixedWindowRollingPolicy fwrp = new FixedWindowRollingPolicy(); - SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = new SizeBasedTriggeringPolicy(); - EchoEncoder encoder = new EchoEncoder(); - - - @Before - public void setUp() { - super.setUp(); - fwrp.setContext(context); - fwrp.setParent(rfa); - rfa.setContext(context); - sizeBasedTriggeringPolicy.setContext(context); - } - - private void initRFA(String filename) { - rfa.setEncoder(encoder); - if (filename != null) { - rfa.setFile(filename); + RollingFileAppender rfa = new RollingFileAppender(); + FixedWindowRollingPolicy fwrp = new FixedWindowRollingPolicy(); + SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = new SizeBasedTriggeringPolicy(); + EchoEncoder encoder = new EchoEncoder(); + + @Before + public void setUp() { + super.setUp(); + fwrp.setContext(context); + fwrp.setParent(rfa); + rfa.setContext(context); + sizeBasedTriggeringPolicy.setContext(context); } - } - - /** - * Test whether FixedWindowRollingPolicy throws an exception when the - * ActiveFileName is not set. - */ - @Test(expected = IllegalStateException.class) - public void activeFileNameNotSet() { - sizeBasedTriggeringPolicy.setMaxFileSize("100"); - sizeBasedTriggeringPolicy.start(); - - fwrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "sizeBased-test1.%i"); - fwrp.start(); - // The absence of activeFileName option should cause an exception. - } - - - void generic(String testName, String fileName, String filenamePattern, List expectedFilenameList) throws InterruptedException, IOException { - rfa.setName("ROLLING"); - initRFA(randomOutputDir + fileName); - - sizeBasedTriggeringPolicy.setMaxFileSize("100"); - fwrp.setMinIndex(0); - fwrp.setFileNamePattern(randomOutputDir + filenamePattern); - - rfa.triggeringPolicy = sizeBasedTriggeringPolicy; - rfa.rollingPolicy = fwrp; - - fwrp.start(); - sizeBasedTriggeringPolicy.start(); - rfa.start(); - - int runLength = 40; - String prefix = "hello"; - for (int i = 0; i < runLength; i++){ - Thread.sleep(10); - rfa.doAppend(prefix + i); + + private void initRFA(String filename) { + rfa.setEncoder(encoder); + if (filename != null) { + rfa.setFile(filename); + } + } + + /** + * Test whether FixedWindowRollingPolicy throws an exception when the + * ActiveFileName is not set. + */ + @Test(expected = IllegalStateException.class) + public void activeFileNameNotSet() { + sizeBasedTriggeringPolicy.setMaxFileSize("100"); + sizeBasedTriggeringPolicy.start(); + + fwrp.setFileNamePattern(CoreTestConstants.OUTPUT_DIR_PREFIX + "sizeBased-test1.%i"); + fwrp.start(); + // The absence of activeFileName option should cause an exception. + } + + void generic(String testName, String fileName, String filenamePattern, List expectedFilenameList) throws InterruptedException, IOException { + rfa.setName("ROLLING"); + initRFA(randomOutputDir + fileName); + + sizeBasedTriggeringPolicy.setMaxFileSize("100"); + fwrp.setMinIndex(0); + fwrp.setFileNamePattern(randomOutputDir + filenamePattern); + + rfa.triggeringPolicy = sizeBasedTriggeringPolicy; + rfa.rollingPolicy = fwrp; + + fwrp.start(); + sizeBasedTriggeringPolicy.start(); + rfa.start(); + + int runLength = 40; + String prefix = "hello"; + for (int i = 0; i < runLength; i++) { + Thread.sleep(10); + rfa.doAppend(prefix + i); + } + rfa.stop(); + + existenceCheck(expectedFilenameList); + reverseSortedContentCheck(randomOutputDir, runLength, prefix); + } + + @Test + public void smoke() throws IOException, InterruptedException { + expectedFilenameList.add(randomOutputDir + "a-sizeBased-smoke.log"); + expectedFilenameList.add(randomOutputDir + "sizeBased-smoke.0"); + expectedFilenameList.add(randomOutputDir + "sizeBased-smoke.1"); + generic("zipped", "a-sizeBased-smoke.log", "sizeBased-smoke.%i", expectedFilenameList); + + } + + @Test + public void gz() throws IOException, InterruptedException { + expectedFilenameList.add(randomOutputDir + "a-sbr-gzed.log"); + expectedFilenameList.add(randomOutputDir + "sbr-gzed.0.gz"); + expectedFilenameList.add(randomOutputDir + "sbr-gzed.1.gz"); + generic("gzed", "a-sbr-gzed.log", "sbr-gzed.%i.gz", expectedFilenameList); + } + + // see also LBCORE-199 + @Test + public void zipped() throws IOException, InterruptedException { + expectedFilenameList.add(randomOutputDir + "a-sbr-zipped.log"); + expectedFilenameList.add(randomOutputDir + "sbr-zipped.0.zip"); + expectedFilenameList.add(randomOutputDir + "sbr-zipped.1.zip"); + generic("zipped", "a-sbr-zipped.log", "sbr-zipped.%i.zip", expectedFilenameList); + + List zipFiles = filterElementsInListBySuffix(".zip"); + zipEntryNameCheck(zipFiles, "sbr-zipped.20\\d{2}-\\d{2}-\\d{2}_\\d{4}"); } - rfa.stop(); - - existenceCheck(expectedFilenameList); - reverseSortedContentCheck(randomOutputDir, runLength, prefix); - } - - @Test - public void smoke() throws IOException, InterruptedException { - expectedFilenameList.add(randomOutputDir + "a-sizeBased-smoke.log"); - expectedFilenameList.add(randomOutputDir + "sizeBased-smoke.0"); - expectedFilenameList.add(randomOutputDir + "sizeBased-smoke.1"); - generic("zipped", "a-sizeBased-smoke.log", "sizeBased-smoke.%i", expectedFilenameList); - - } - @Test - public void gz() throws IOException, InterruptedException { - expectedFilenameList.add(randomOutputDir + "a-sbr-gzed.log"); - expectedFilenameList.add(randomOutputDir + "sbr-gzed.0.gz"); - expectedFilenameList.add(randomOutputDir + "sbr-gzed.1.gz"); - generic("gzed", "a-sbr-gzed.log", "sbr-gzed.%i.gz", expectedFilenameList); - } - - // see also LBCORE-199 - @Test - public void zipped() throws IOException, InterruptedException { - expectedFilenameList.add(randomOutputDir + "a-sbr-zipped.log"); - expectedFilenameList.add(randomOutputDir + "sbr-zipped.0.zip"); - expectedFilenameList.add(randomOutputDir + "sbr-zipped.1.zip"); - generic("zipped", "a-sbr-zipped.log", "sbr-zipped.%i.zip", expectedFilenameList); - - List zipFiles = filterElementsInListBySuffix(".zip"); - zipEntryNameCheck(zipFiles, "sbr-zipped.20\\d{2}-\\d{2}-\\d{2}_\\d{4}"); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicyTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicyTest.java index 64b005a54f7c5ccd256b1eb9c71ff7f260da60ff..e5a5a3790bcf13bd0952eb6be058df3b9c22b420 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicyTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/SizeBasedTriggeringPolicyTest.java @@ -19,40 +19,39 @@ import ch.qos.logback.core.ContextBase; public class SizeBasedTriggeringPolicyTest extends TestCase { - public void testStringToLong() { - Context context = new ContextBase(); - SizeBasedTriggeringPolicy policy = new SizeBasedTriggeringPolicy(); - policy.setContext(context); + public void testStringToLong() { + Context context = new ContextBase(); + SizeBasedTriggeringPolicy policy = new SizeBasedTriggeringPolicy(); + policy.setContext(context); - Long result; + Long result; - { - result = policy.toFileSize("123"); - assertEquals(new Long("123"), result); - } - { - result = policy.toFileSize("123KB"); - // = 123 * 1024 - assertEquals(new Long("125952"), result); - } - { - result = policy.toFileSize("123MB"); - // = 123 * 1024 * 1024 - assertEquals(new Long("128974848"), result); - } - { - result = policy.toFileSize("123GB"); - // = 123 * 1024 * 1024 * 1024 - assertEquals(new Long("132070244352"), result); - } + { + result = policy.toFileSize("123"); + assertEquals(new Long("123"), result); + } + { + result = policy.toFileSize("123KB"); + // = 123 * 1024 + assertEquals(new Long("125952"), result); + } + { + result = policy.toFileSize("123MB"); + // = 123 * 1024 * 1024 + assertEquals(new Long("128974848"), result); + } + { + result = policy.toFileSize("123GB"); + // = 123 * 1024 * 1024 * 1024 + assertEquals(new Long("132070244352"), result); + } - { - result = policy.toFileSize("123xxxx"); - // = 123 * 1024 * 1024 * 1024 - assertEquals(new Long(SizeBasedTriggeringPolicy.DEFAULT_MAX_FILE_SIZE), - result); - assertEquals(2, context.getStatusManager().getCount()); - } + { + result = policy.toFileSize("123xxxx"); + // = 123 * 1024 * 1024 * 1024 + assertEquals(new Long(SizeBasedTriggeringPolicy.DEFAULT_MAX_FILE_SIZE), result); + assertEquals(2, context.getStatusManager().getCount()); + } - } + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBaseTest.java index 06068e8e3de96b197c313852d8946398e5b254e3..5f6f963bd8aecd75767a498306dfd8e3f3f0a52a 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedFileNamingAndTriggeringPolicyBaseTest.java @@ -27,78 +27,78 @@ import ch.qos.logback.core.ContextBase; */ public class TimeBasedFileNamingAndTriggeringPolicyBaseTest { - static long MILLIS_IN_MINUTE = 60*1000; - static long MILLIS_IN_HOUR = 60*MILLIS_IN_MINUTE; - - Context context = new ContextBase(); - RollingFileAppender rfa = new RollingFileAppender(); - TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); - DefaultTimeBasedFileNamingAndTriggeringPolicy timeBasedFNATP = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); - - @Before - public void setUp() { - rfa.setContext(context); - tbrp.setContext(context); - timeBasedFNATP.setContext(context); - - rfa.setRollingPolicy(tbrp); - tbrp.setParent(rfa); - tbrp.setTimeBasedFileNamingAndTriggeringPolicy(timeBasedFNATP); - timeBasedFNATP.setTimeBasedRollingPolicy(tbrp); - } - - @Test - public void singleDate() { - // Tuesday December 20th 17:59:01 CET 2011 - long startTime = 1324400341553L; - tbrp.setFileNamePattern("foo-%d{yyyy-MM'T'mm}.log"); - tbrp.start(); - - timeBasedFNATP.setCurrentTime(startTime); - timeBasedFNATP.start(); - - timeBasedFNATP.setCurrentTime(startTime+MILLIS_IN_MINUTE); - timeBasedFNATP.isTriggeringEvent(null, null); - String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); - assertEquals("foo-2011-12T59.log", elapsedPeriodsFileName); - } - - // see "log rollover should be configurable using %d multiple times in file name pattern" - // http://jira.qos.ch/browse/LBCORE-242 - - @Test - public void multiDate() { - // Tuesday December 20th 17:59:01 CET 2011 - long startTime = 1324400341553L; - tbrp.setFileNamePattern("foo-%d{yyyy-MM, AUX}/%d{mm}.log"); - tbrp.start(); - - timeBasedFNATP.setCurrentTime(startTime); - timeBasedFNATP.start(); - - timeBasedFNATP.setCurrentTime(startTime+MILLIS_IN_MINUTE); - boolean triggerred = timeBasedFNATP.isTriggeringEvent(null, null); - assertTrue(triggerred); - String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); - assertEquals("foo-2011-12/59.log", elapsedPeriodsFileName); - } - - @Test - public void withTimeZone() { - // Tuesday December 20th 17:59:01 CET 2011 - long startTime = 1324400341553L; - tbrp.setFileNamePattern("foo-%d{yyyy-MM-dd, GMT+5}.log"); - tbrp.start(); - - timeBasedFNATP.setCurrentTime(startTime); - timeBasedFNATP.start(); - - timeBasedFNATP.setCurrentTime(startTime+MILLIS_IN_MINUTE+2*MILLIS_IN_HOUR); - boolean triggerred = timeBasedFNATP.isTriggeringEvent(null, null); - assertTrue(triggerred); - String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); - assertEquals("foo-2011-12-20.log", elapsedPeriodsFileName); - - } + static long MILLIS_IN_MINUTE = 60 * 1000; + static long MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE; + + Context context = new ContextBase(); + RollingFileAppender rfa = new RollingFileAppender(); + TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); + DefaultTimeBasedFileNamingAndTriggeringPolicy timeBasedFNATP = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); + + @Before + public void setUp() { + rfa.setContext(context); + tbrp.setContext(context); + timeBasedFNATP.setContext(context); + + rfa.setRollingPolicy(tbrp); + tbrp.setParent(rfa); + tbrp.setTimeBasedFileNamingAndTriggeringPolicy(timeBasedFNATP); + timeBasedFNATP.setTimeBasedRollingPolicy(tbrp); + } + + @Test + public void singleDate() { + // Tuesday December 20th 17:59:01 CET 2011 + long startTime = 1324400341553L; + tbrp.setFileNamePattern("foo-%d{yyyy-MM'T'mm}.log"); + tbrp.start(); + + timeBasedFNATP.setCurrentTime(startTime); + timeBasedFNATP.start(); + + timeBasedFNATP.setCurrentTime(startTime + MILLIS_IN_MINUTE); + timeBasedFNATP.isTriggeringEvent(null, null); + String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); + assertEquals("foo-2011-12T59.log", elapsedPeriodsFileName); + } + + // see "log rollover should be configurable using %d multiple times in file name pattern" + // http://jira.qos.ch/browse/LBCORE-242 + + @Test + public void multiDate() { + // Tuesday December 20th 17:59:01 CET 2011 + long startTime = 1324400341553L; + tbrp.setFileNamePattern("foo-%d{yyyy-MM, AUX}/%d{mm}.log"); + tbrp.start(); + + timeBasedFNATP.setCurrentTime(startTime); + timeBasedFNATP.start(); + + timeBasedFNATP.setCurrentTime(startTime + MILLIS_IN_MINUTE); + boolean triggerred = timeBasedFNATP.isTriggeringEvent(null, null); + assertTrue(triggerred); + String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); + assertEquals("foo-2011-12/59.log", elapsedPeriodsFileName); + } + + @Test + public void withTimeZone() { + // Tuesday December 20th 17:59:01 CET 2011 + long startTime = 1324400341553L; + tbrp.setFileNamePattern("foo-%d{yyyy-MM-dd, GMT+5}.log"); + tbrp.start(); + + timeBasedFNATP.setCurrentTime(startTime); + timeBasedFNATP.start(); + + timeBasedFNATP.setCurrentTime(startTime + MILLIS_IN_MINUTE + 2 * MILLIS_IN_HOUR); + boolean triggerred = timeBasedFNATP.isTriggeringEvent(null, null); + assertTrue(triggerred); + String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); + assertEquals("foo-2011-12-20.log", elapsedPeriodsFileName); + + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingTest.java index b548ba0f435ff8db7843ee11a1007bb005e4986c..3d499b1b4991a01fbd08b094408e9bc83ebe4098 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingTest.java @@ -48,238 +48,233 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class TimeBasedRollingTest extends ScaffoldingForRollingTests { - static final int NO_RESTART = 0; - static final int WITH_RESTART = 1; - static final int WITH_RESTART_AND_LONG_WAIT = 2000; + static final int NO_RESTART = 0; + static final int WITH_RESTART = 1; + static final int WITH_RESTART_AND_LONG_WAIT = 2000; - static final boolean FILE_OPTION_SET = true; - static final boolean FILE_OPTION_BLANK = false; + static final boolean FILE_OPTION_SET = true; + static final boolean FILE_OPTION_BLANK = false; + RollingFileAppender rfa1 = new RollingFileAppender(); + TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); - RollingFileAppender rfa1 = new RollingFileAppender(); - TimeBasedRollingPolicy tbrp1 = new TimeBasedRollingPolicy(); + RollingFileAppender rfa2 = new RollingFileAppender(); + TimeBasedRollingPolicy tbrp2 = new TimeBasedRollingPolicy(); - RollingFileAppender rfa2 = new RollingFileAppender(); - TimeBasedRollingPolicy tbrp2 = new TimeBasedRollingPolicy(); + EchoEncoder encoder = new EchoEncoder(); - EchoEncoder encoder = new EchoEncoder(); + RolloverChecker rolloverChecker; - RolloverChecker rolloverChecker; + @Before + @Override + public void setUp() { + super.setUp(); + } + + @After + public void tearDown() { + } + + void initRFA(RollingFileAppender rfa, String filename) { + rfa.setContext(context); + rfa.setEncoder(encoder); + if (filename != null) { + rfa.setFile(filename); + } + } + + void initTRBP(RollingFileAppender rfa, TimeBasedRollingPolicy tbrp, String filenamePattern, long givenTime) { + tbrp.setContext(context); + tbrp.setFileNamePattern(filenamePattern); + tbrp.setParent(rfa); + tbrp.timeBasedFileNamingAndTriggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); + tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime); + rfa.setRollingPolicy(tbrp); + tbrp.start(); + rfa.start(); + } + + void genericTest(String testId, String patternPrefix, String compressionSuffix, boolean fileOptionIsSet, int waitDuration) throws IOException { + String fileName = fileOptionIsSet ? testId2FileName(testId) : null; + initRFA(rfa1, fileName); + + String fileNamePatternStr = randomOutputDir + patternPrefix + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}" + compressionSuffix; + + initTRBP(rfa1, tbrp1, fileNamePatternStr, currentTime); + + // compute the current filename + addExpectedFileName_ByDate(fileNamePatternStr, getMillisOfCurrentPeriodsStart()); + + incCurrentTime(1100); + tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + + for (int i = 0; i < 3; i++) { + rfa1.doAppend("Hello---" + i); + addExpectedFileNamedIfItsTime_ByDate(fileNamePatternStr); + incCurrentTime(500); + tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + add(tbrp1.future); + } + rfa1.stop(); + waitForJobsToComplete(); + + if (waitDuration != NO_RESTART) { + doRestart(testId, patternPrefix, fileOptionIsSet, waitDuration); + } + waitForJobsToComplete(); + + massageExpectedFilesToCorresponToCurrentTarget(fileName, fileOptionIsSet); + StatusPrinter.print(context); + rolloverChecker.check(expectedFilenameList); + } + + void defaultTest(String testId, String patternPrefix, String compressionSuffix, boolean fileOptionIsSet, int waitDuration) throws IOException { + boolean withCompression = compressionSuffix.length() > 0; + rolloverChecker = new DefaultRolloverChecker(testId, withCompression, compressionSuffix); + genericTest(testId, patternPrefix, compressionSuffix, fileOptionIsSet, waitDuration); + } - @Before - @Override - public void setUp() { - super.setUp(); - } + void doRestart(String testId, String patternPart, boolean fileOptionIsSet, int waitDuration) { + // change the timestamp of the currently actively file + File activeFile = new File(rfa1.getFile()); + activeFile.setLastModified(currentTime); + + incCurrentTime(waitDuration); + + String filePatternStr = randomOutputDir + patternPart + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}"; + + String fileName = fileOptionIsSet ? testId2FileName(testId) : null; + initRFA(rfa2, fileName); + initTRBP(rfa2, tbrp2, filePatternStr, currentTime); + for (int i = 0; i < 3; i++) { + rfa2.doAppend("World---" + i); + addExpectedFileNamedIfItsTime_ByDate(filePatternStr); + incCurrentTime(100); + tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + add(tbrp2.future); + } + rfa2.stop(); + } + + @Test + public void noCompression_FileBlank_NoRestart_1() throws IOException { + defaultTest("test1", "test1", "", FILE_OPTION_BLANK, NO_RESTART); + } + + @Test + public void withCompression_FileBlank_NoRestart_2() throws IOException { + defaultTest("test2", "test2", ".gz", FILE_OPTION_BLANK, NO_RESTART); + } + + @Test + public void noCompression_FileBlank_StopRestart_3() throws IOException { + defaultTest("test3", "test3", "", FILE_OPTION_BLANK, WITH_RESTART); + } + + @Test + public void noCompression_FileSet_StopRestart_4() throws IOException { + defaultTest("test4", "test4", "", FILE_OPTION_SET, WITH_RESTART); + } - @After - public void tearDown() { - } + @Test + public void noCompression_FileSet_StopRestart_WithLongWait_4B() throws IOException { + defaultTest("test4B", "test4B", "", FILE_OPTION_SET, WITH_RESTART_AND_LONG_WAIT); + } - void initRFA(RollingFileAppender rfa, String filename) { - rfa.setContext(context); - rfa.setEncoder(encoder); - if (filename != null) { - rfa.setFile(filename); + @Test + public void noCompression_FileSet_NoRestart_5() throws IOException { + defaultTest("test5", "test6", "", FILE_OPTION_SET, NO_RESTART); } - } - - void initTRBP(RollingFileAppender rfa, - TimeBasedRollingPolicy tbrp, String filenamePattern, - long givenTime) { - tbrp.setContext(context); - tbrp.setFileNamePattern(filenamePattern); - tbrp.setParent(rfa); - tbrp.timeBasedFileNamingAndTriggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); - tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime); - rfa.setRollingPolicy(tbrp); - tbrp.start(); - rfa.start(); - } - - - void genericTest(String testId, String patternPrefix, String compressionSuffix, boolean fileOptionIsSet, int waitDuration) throws IOException { - String fileName = fileOptionIsSet ? testId2FileName(testId) : null; - initRFA(rfa1, fileName); - - String fileNamePatternStr = randomOutputDir + patternPrefix + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}" + compressionSuffix; - - initTRBP(rfa1, tbrp1, fileNamePatternStr, currentTime); - - // compute the current filename - addExpectedFileName_ByDate(fileNamePatternStr, getMillisOfCurrentPeriodsStart()); - - incCurrentTime(1100); - tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); - - for (int i = 0; i < 3; i++) { - rfa1.doAppend("Hello---" + i); - addExpectedFileNamedIfItsTime_ByDate(fileNamePatternStr); - incCurrentTime(500); - tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); - add(tbrp1.future); + + @Test + public void withCompression_FileSet_NoRestart_6() throws IOException { + defaultTest("test6", "test6", ".gz", FILE_OPTION_SET, NO_RESTART); } - rfa1.stop(); - waitForJobsToComplete(); - if (waitDuration != NO_RESTART) { - doRestart(testId, patternPrefix, fileOptionIsSet, waitDuration); + // LOGBACK-168 + @Test + public void withMissingTargetDirWithCompression() throws IOException { + defaultTest("test7", "%d{yyyy-MM-dd, aux}/", ".gz", FILE_OPTION_SET, NO_RESTART); } - waitForJobsToComplete(); - - massageExpectedFilesToCorresponToCurrentTarget(fileName, fileOptionIsSet); - StatusPrinter.print(context); - rolloverChecker.check(expectedFilenameList); - } - - void defaultTest(String testId, String patternPrefix, String compressionSuffix, boolean fileOptionIsSet, int waitDuration) throws IOException { - boolean withCompression = compressionSuffix.length() > 0; - rolloverChecker = new DefaultRolloverChecker(testId, withCompression, compressionSuffix); - genericTest(testId, patternPrefix, compressionSuffix, fileOptionIsSet, waitDuration); - } - - void doRestart(String testId, String patternPart, boolean fileOptionIsSet, int waitDuration) { - // change the timestamp of the currently actively file - File activeFile = new File(rfa1.getFile()); - activeFile.setLastModified(currentTime); - - incCurrentTime(waitDuration); - - String filePatternStr = randomOutputDir + patternPart + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}"; - - String fileName = fileOptionIsSet ? testId2FileName(testId) : null; - initRFA(rfa2, fileName); - initTRBP(rfa2, tbrp2, filePatternStr, currentTime); - for (int i = 0; i < 3; i++) { - rfa2.doAppend("World---" + i); - addExpectedFileNamedIfItsTime_ByDate(filePatternStr); - incCurrentTime(100); - tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); - add(tbrp2.future); + + @Test + public void withMissingTargetDirWithZipCompression() throws IOException { + defaultTest("test8", "%d{yyyy-MM-dd, aux}/", ".zip", FILE_OPTION_SET, NO_RESTART); } - rfa2.stop(); - } - - - @Test - public void noCompression_FileBlank_NoRestart_1() throws IOException { - defaultTest("test1", "test1", "", FILE_OPTION_BLANK, NO_RESTART); - } - - @Test - public void withCompression_FileBlank_NoRestart_2() throws IOException { - defaultTest("test2", "test2", ".gz", FILE_OPTION_BLANK, NO_RESTART); - } - - @Test - public void noCompression_FileBlank_StopRestart_3() throws IOException { - defaultTest("test3", "test3", "", FILE_OPTION_BLANK, WITH_RESTART); - } - - @Test - public void noCompression_FileSet_StopRestart_4() throws IOException { - defaultTest("test4", "test4", "", FILE_OPTION_SET, WITH_RESTART); - } - - @Test - public void noCompression_FileSet_StopRestart_WithLongWait_4B() throws IOException { - defaultTest("test4B", "test4B", "", FILE_OPTION_SET, WITH_RESTART_AND_LONG_WAIT); - } - - @Test - public void noCompression_FileSet_NoRestart_5() throws IOException { - defaultTest("test5", "test6", "", FILE_OPTION_SET, NO_RESTART); - } - - @Test - public void withCompression_FileSet_NoRestart_6() throws IOException { - defaultTest("test6", "test6", ".gz", FILE_OPTION_SET, NO_RESTART); - } - - // LOGBACK-168 - @Test - public void withMissingTargetDirWithCompression() throws IOException { - defaultTest("test7", "%d{yyyy-MM-dd, aux}/", ".gz", FILE_OPTION_SET, NO_RESTART); - } - - @Test - public void withMissingTargetDirWithZipCompression() throws IOException { - defaultTest("test8", "%d{yyyy-MM-dd, aux}/", ".zip", FILE_OPTION_SET, NO_RESTART); - } - - @Test - public void failed_rename() throws IOException { - if (!EnvUtilForTests.isWindows()) - return; - - FileOutputStream fos = null; - try { - String fileName = testId2FileName("failed_rename"); - File file = new File(fileName); - file.getParentFile().mkdirs(); - - fos = new FileOutputStream(fileName); - - String testId = "failed_rename"; - rolloverChecker = new ZRolloverChecker(testId); - genericTest(testId, "failed_rename", "", FILE_OPTION_SET, NO_RESTART); - - - } finally { - StatusPrinter.print(context); - if (fos != null) fos.close(); + + @Test + public void failed_rename() throws IOException { + if (!EnvUtilForTests.isWindows()) + return; + + FileOutputStream fos = null; + try { + String fileName = testId2FileName("failed_rename"); + File file = new File(fileName); + file.getParentFile().mkdirs(); + + fos = new FileOutputStream(fileName); + + String testId = "failed_rename"; + rolloverChecker = new ZRolloverChecker(testId); + genericTest(testId, "failed_rename", "", FILE_OPTION_SET, NO_RESTART); + + } finally { + StatusPrinter.print(context); + if (fos != null) + fos.close(); + } } - } - -// -// @Test -// public void withMissingTargetDir() throws Exception { -// String testId = "missingTargetDir"; -// -// initRFA(rfa1, testId2FileName(testId)); -// int secondDiff = RandomUtil.getPositiveInt(); -// String randomTargetDir = CoreTestConstants.OUTPUT_DIR_PREFIX + secondDiff + '/'; -// -// System.out.println("randomOutputDir" + randomOutputDir); -// System.out.println("randomTargetDir" + randomTargetDir); -// -// initTRBP(rfa1, tbrp1, randomTargetDir + testId + "-%d{" -// + DATE_PATTERN_WITH_SECONDS + "}", currentTime); -// -// addExpectedFileName_ByDate(randomTargetDir, testId, getDateOfCurrentPeriodsStart(), false); -// -// incCurrentTime(1100); -// tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); -// -// for (int i = 0; i < 3; i++) { -// rfa1.doAppend("Hello---" + i); -// addExpectedFileNamedIfItsTime_ByDate(randomTargetDir, testId, false); -// incCurrentTime(500); -// tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); -// } -// massageExpectedFilesToCorresponToCurrentTarget("missingTargetDir.log"); -// int i = 0; -// for (String fn : expectedFilenameList) { -// System.out.println("expectedFile=" + fn); -// assertTrue(Compare.compare(fn, CoreTestConstants.TEST_SRC_PREFIX -// + "witness/rolling/tbr-test5." + i++)); -// } -// -// } -// -// ========================================================================= -// utility methods -// ========================================================================= -// -// void massageExpectedFilesToCorresponToCurrentTarget(String file) { -// // we added one too many files by date -// expectedFilenameList.remove(expectedFilenameList.size() - 1); -// // since file is set, we have to add it -// addExpectedFileName_ByFile(file); -// } -// -// void addExpectedFileName_ByFile(String filenameSuffix) { -// String fn = randomOutputDir + filenameSuffix; -// expectedFilenameList.add(fn); -// } + + // + // @Test + // public void withMissingTargetDir() throws Exception { + // String testId = "missingTargetDir"; + // + // initRFA(rfa1, testId2FileName(testId)); + // int secondDiff = RandomUtil.getPositiveInt(); + // String randomTargetDir = CoreTestConstants.OUTPUT_DIR_PREFIX + secondDiff + '/'; + // + // System.out.println("randomOutputDir" + randomOutputDir); + // System.out.println("randomTargetDir" + randomTargetDir); + // + // initTRBP(rfa1, tbrp1, randomTargetDir + testId + "-%d{" + // + DATE_PATTERN_WITH_SECONDS + "}", currentTime); + // + // addExpectedFileName_ByDate(randomTargetDir, testId, getDateOfCurrentPeriodsStart(), false); + // + // incCurrentTime(1100); + // tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + // + // for (int i = 0; i < 3; i++) { + // rfa1.doAppend("Hello---" + i); + // addExpectedFileNamedIfItsTime_ByDate(randomTargetDir, testId, false); + // incCurrentTime(500); + // tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + // } + // massageExpectedFilesToCorresponToCurrentTarget("missingTargetDir.log"); + // int i = 0; + // for (String fn : expectedFilenameList) { + // System.out.println("expectedFile=" + fn); + // assertTrue(Compare.compare(fn, CoreTestConstants.TEST_SRC_PREFIX + // + "witness/rolling/tbr-test5." + i++)); + // } + // + // } + // + // ========================================================================= + // utility methods + // ========================================================================= + // + // void massageExpectedFilesToCorresponToCurrentTarget(String file) { + // // we added one too many files by date + // expectedFilenameList.remove(expectedFilenameList.size() - 1); + // // since file is set, we have to add it + // addExpectedFileName_ByFile(file); + // } + // + // void addExpectedFileName_ByFile(String filenameSuffix) { + // String fn = randomOutputDir + filenameSuffix; + // expectedFilenameList.add(fn); + // } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingWithArchiveRemoval_Test.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingWithArchiveRemoval_Test.java index 7b964e726e6bb26cddbdcdf6d2641c046139d675..ff20e757b6a4533bdfd0201428d0a5bf7a750770 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingWithArchiveRemoval_Test.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/TimeBasedRollingWithArchiveRemoval_Test.java @@ -35,392 +35,376 @@ import ch.qos.logback.core.rolling.helper.RollingCalendar; import ch.qos.logback.core.util.StatusPrinter; public class TimeBasedRollingWithArchiveRemoval_Test extends ScaffoldingForRollingTests { - String MONTHLY_DATE_PATTERN = "yyyy-MM"; - String MONTHLY_CRONOLOG_DATE_PATTERN = "yyyy/MM"; - final String DAILY_CRONOLOG_DATE_PATTERN = "yyyy/MM/dd"; - - - RollingFileAppender rfa = new RollingFileAppender(); - TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); - - // by default tbfnatp is an instance of DefaultTimeBasedFileNamingAndTriggeringPolicy - TimeBasedFileNamingAndTriggeringPolicy tbfnatp = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); - - long MILLIS_IN_MINUTE = 60 * 1000; - long MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE; - long MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR; - long MILLIS_IN_MONTH = (long) ((365.242199 / 12) * MILLIS_IN_DAY); - int MONTHS_IN_YEAR = 12; - - int slashCount = 0; - - @Before - public void setUp() { - super.setUp(); - } - - - private int computeSlashCount(String datePattern) { - if (datePattern == null) - return 0; - else { - int count = 0; - for (int i = 0; i < datePattern.length(); i++) { - char c = datePattern.charAt(i); - if (c == '/') - count++; - } - return count; - } - } - - - // test that the number of files at the end of the test is same as the expected number taking into account end dates - // near the beginning of a new year. This test has been run in a loop with start date varying over a two years - // with success. - @Test - public void monthlyRolloverOverManyPeriods() { - - slashCount = computeSlashCount(MONTHLY_CRONOLOG_DATE_PATTERN); - int numPeriods = 40; - int maxHistory = 2; - String fileNamePattern = randomOutputDir + "/%d{" + MONTHLY_CRONOLOG_DATE_PATTERN + "}/clean.txt.zip"; - - long startTime = currentTime; - long endTime = logOverMultiplePeriodsContinuously(currentTime, fileNamePattern, MILLIS_IN_MONTH, maxHistory, - numPeriods); - System.out.println("randomOutputDir:" + randomOutputDir); - System.out.println("start:" + startTime + ", end=" + endTime); - int differenceInMonths = RollingCalendar.diffInMonths(startTime, endTime); - System.out.println("differenceInMonths:" + differenceInMonths); - Calendar startTimeAsCalendar = Calendar.getInstance(); - startTimeAsCalendar.setTimeInMillis(startTime); - int indexOfStartPeriod = startTimeAsCalendar.get(Calendar.MONTH); - boolean withExtraFolder = extraFolder(differenceInMonths, MONTHS_IN_YEAR, indexOfStartPeriod, maxHistory); - - check(expectedCountWithFolders(maxHistory, withExtraFolder)); - } - - void generateDailyRollover(long now, int maxHistory, int simulatedNumberOfPeriods, int startInactivity, - int numInactivityPeriods) { - slashCount = computeSlashCount(DAILY_DATE_PATTERN); - logOverMultiplePeriods(now, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", MILLIS_IN_DAY, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); - check(expectedCountWithoutFoldersWithInactivity(maxHistory, simulatedNumberOfPeriods, startInactivity + numInactivityPeriods)); - } - - @Test - public void basicDailyRollover() { - int maxHistory = 20; - int simulatedNumberOfPeriods = 20 * 3; - int startInactivity = 0; - int numInactivityPeriods = 0; - generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); - } - - // Since the duration of a month (in seconds) varies from month to month, tests with inactivity period must - // be conducted with daily rollover not monthly - @Test - public void dailyRollover15() { - int maxHistory = 5; - int simulatedNumberOfPeriods = 15; - int startInactivity = 6; - int numInactivityPeriods = 3; - generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); - } - - @Test - public void dailyRolloverWithInactivity70() { - int maxHistory = 6; - int simulatedNumberOfPeriods = 70; - int startInactivity = 30; - int numInactivityPeriods = 1; - generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); - } - - @Test - public void dailyRolloverWithInactivity10() { - int maxHistory = 6; - int simulatedNumberOfPeriods = 10; - int startInactivity = 3; - int numInactivityPeriods = 4; - generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); - } - - @Test - public void dailyRolloverWithSecondPhase() { - slashCount = computeSlashCount(DAILY_DATE_PATTERN); - int maxHistory = 5; - long endTime = logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", - MILLIS_IN_DAY, maxHistory, maxHistory * 2); - logOverMultiplePeriodsContinuously(endTime + MILLIS_IN_DAY * 10, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", - MILLIS_IN_DAY, maxHistory, maxHistory); - check(expectedCountWithoutFolders(maxHistory)); - } - - @Test - public void dailyCronologRollover() { - slashCount = computeSlashCount(DAILY_CRONOLOG_DATE_PATTERN); - logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_CRONOLOG_DATE_PATTERN + "}/clean.txt.zip", - MILLIS_IN_DAY, 8, 8 * 3); - int expectedDirMin = 9 + slashCount; - int expectDirMax = expectedDirMin + 1 + 1; - expectedFileAndDirCount(9, expectedDirMin, expectDirMax); - } - - @Test - public void dailySizeBasedRollover() { - SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); - sizeAndTimeBasedFNATP.setMaxFileSize("10000"); - tbfnatp = sizeAndTimeBasedFNATP; - slashCount = computeSlashCount(DAILY_DATE_PATTERN); - logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}-clean.%i.zip", MILLIS_IN_DAY, - 5, 5 * 4); - checkPatternCompliance(5 + 1 + slashCount, "\\d{4}-\\d{2}-\\d{2}-clean(\\.\\d)(.zip)?"); - } - - @Test - public void dailyChronologSizeBasedRollover() { - SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); - sizeAndTimeBasedFNATP.setMaxFileSize("10000"); - tbfnatp = sizeAndTimeBasedFNATP; - slashCount = 1; - logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i.zip", MILLIS_IN_DAY, - 5, 5 * 4); - checkDirPatternCompliance(6); - } - - @Test - public void dailyChronologSizeBasedRolloverWithSecondPhase() { - SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); - sizeAndTimeBasedFNATP.setMaxFileSize("10000"); - tbfnatp = sizeAndTimeBasedFNATP; - slashCount = 1; - int maxHistory = 5; - int simulatedNumberOfPeriods = maxHistory * 4; - long endTime = logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i", MILLIS_IN_DAY, - maxHistory, 3); - logOverMultiplePeriodsContinuously(endTime + MILLIS_IN_DAY * 7, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i", - MILLIS_IN_DAY, maxHistory, simulatedNumberOfPeriods); - checkDirPatternCompliance(maxHistory + 1); - } - - - void logOncePeriod(long currentTime, String fileNamePattern, int maxHistory) { - buildRollingFileAppender(currentTime, fileNamePattern, maxHistory, DO_CLEAN_HISTORY_ON_START); - rfa.doAppend("Hello ----------------------------------------------------------" + new Date(currentTime)); - rfa.stop(); - } - - @Test - public void cleanHistoryOnStart() { - long now = this.currentTime; - String fileNamePattern = randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt"; - int maxHistory = 3; - for (int i = 0; i <= 5; i++) { - logOncePeriod(now, fileNamePattern, maxHistory); - now = now + MILLIS_IN_DAY; - } - //StatusPrinter.print(context); - check(expectedCountWithoutFolders(maxHistory)); - } - - @Test - public void cleanHistoryOnStartWithDayPattern() { - long now = this.currentTime; - String fileNamePattern = randomOutputDir + "clean-%d{yyyy-MM-dd}.txt"; - int maxHistory = 3; - for (int i = 0; i <= 5; i++) { - logOncePeriod(now, fileNamePattern, maxHistory); - now = now + MILLIS_IN_DAY; - } - StatusPrinter.print(context); - check(expectedCountWithoutFolders(maxHistory)); - } - - @Test - public void cleanHistoryOnStartWithHourPattern() { - long now = this.currentTime; - String fileNamePattern = randomOutputDir + "clean-%d{HH}.txt"; - int maxHistory = 3; - for (int i = 0; i <= 5; i++) { - logOncePeriod(now, fileNamePattern, maxHistory); - now = now + MILLIS_IN_HOUR; - } - //StatusPrinter.print(context); - check(expectedCountWithoutFolders(maxHistory)); - } - - int expectedCountWithoutFolders(int maxHistory) { - return maxHistory + 1; - } - - - int expectedCountWithFolders(int maxHistory, boolean withExtraFolder) { - int numLogFiles = (maxHistory + 1); - int numLogFilesAndFolders = numLogFiles * 2; - int result = numLogFilesAndFolders + slashCount; - if (withExtraFolder) result += 1; - return result; - } - - - void buildRollingFileAppender(long currentTime, String fileNamePattern, int maxHistory, - boolean cleanHistoryOnStart) { - rfa.setContext(context); - rfa.setEncoder(encoder); - tbrp.setContext(context); - tbrp.setFileNamePattern(fileNamePattern); - tbrp.setMaxHistory(maxHistory); - tbrp.setParent(rfa); - tbrp.setCleanHistoryOnStart(cleanHistoryOnStart); - tbrp.timeBasedFileNamingAndTriggeringPolicy = tbfnatp; - tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); - tbrp.start(); - rfa.setRollingPolicy(tbrp); - rfa.start(); - } - - boolean DO_CLEAN_HISTORY_ON_START = true; - boolean DO_NOT_CLEAN_HISTORY_ON_START = false; - - - long logOverMultiplePeriodsContinuously(long simulatedTime, String fileNamePattern, long periodDurationInMillis, int maxHistory, - int simulatedNumberOfPeriods) { - return logOverMultiplePeriods(simulatedTime, fileNamePattern, periodDurationInMillis, maxHistory, - simulatedNumberOfPeriods, 0, 0); - } - - long logOverMultiplePeriods(long simulatedTime, String fileNamePattern, long periodDurationInMillis, int maxHistory, - int simulatedNumberOfPeriods, int startInactivity, - int numInactivityPeriods) { - buildRollingFileAppender(simulatedTime, fileNamePattern, maxHistory, DO_NOT_CLEAN_HISTORY_ON_START); - int ticksPerPeriod = 512; - int runLength = simulatedNumberOfPeriods * ticksPerPeriod; - int startInactivityIndex = 1 + startInactivity * ticksPerPeriod; - int endInactivityIndex = startInactivityIndex + numInactivityPeriods * ticksPerPeriod; - long tickDuration = periodDurationInMillis / ticksPerPeriod; - - for (int i = 0; i <= runLength; i++) { - if (i < startInactivityIndex || i > endInactivityIndex) { - rfa.doAppend("Hello ----------------------------------------------------------" + i); - } - tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(addTime(tbrp.timeBasedFileNamingAndTriggeringPolicy.getCurrentTime(), - tickDuration)); - add(tbrp.future); - waitForJobsToComplete(); - } - rfa.stop(); - return tbrp.timeBasedFileNamingAndTriggeringPolicy.getCurrentTime(); - } - - boolean extraFolder(int numPeriods, int periodsPerEra, int beginPeriod, int maxHistory) { - int valueOfLastMonth = ((beginPeriod) + numPeriods) % periodsPerEra; - return (valueOfLastMonth < maxHistory); - } - - long addTime(long time, long timeToWait) { - return time + timeToWait; - } - - - void expectedFileAndDirCount(int expectedFileAndDirCount, int expectedDirCountMin, int expectedDirCountMax) { - File dir = new File(randomOutputDir); - List fileList = new ArrayList(); - findFilesInFolderRecursivelyByPatterMatch(dir, fileList, "clean"); - List dirList = new ArrayList(); - findAllFoldersInFolderRecursively(dir, dirList); - String msg = "expectedDirCountMin=" + expectedDirCountMin + ", expectedDirCountMax=" + expectedDirCountMax + " actual value=" + dirList.size(); - assertTrue(msg, expectedDirCountMin <= dirList.size() && dirList.size() <= expectedDirCountMax); - } - - - void check(int expectedCount) { - File dir = new File(randomOutputDir); - List fileList = new ArrayList(); - findAllDirsOrStringContainsFilesRecursively(dir, fileList, "clean"); - assertEquals(expectedCount, fileList.size()); - } - - int expectedCountWithoutFoldersWithInactivity(int maxHistory, int totalPeriods, int endOfInactivity) { - int availableHistory = (totalPeriods + 1) - endOfInactivity; - int actualHistory = Math.min(availableHistory, maxHistory + 1); - return actualHistory; - } - - void genericFindMatching(final FileMatchFunction matchFunc, File dir, List fileList, final String pattern, boolean includeDirs) { - if (dir.isDirectory()) { - File[] matchArray = dir.listFiles(new FileFilter() { - public boolean accept(File f) { - return f.isDirectory() || matchFunc.match(f, pattern); + String MONTHLY_DATE_PATTERN = "yyyy-MM"; + String MONTHLY_CRONOLOG_DATE_PATTERN = "yyyy/MM"; + final String DAILY_CRONOLOG_DATE_PATTERN = "yyyy/MM/dd"; + + RollingFileAppender rfa = new RollingFileAppender(); + TimeBasedRollingPolicy tbrp = new TimeBasedRollingPolicy(); + + // by default tbfnatp is an instance of DefaultTimeBasedFileNamingAndTriggeringPolicy + TimeBasedFileNamingAndTriggeringPolicy tbfnatp = new DefaultTimeBasedFileNamingAndTriggeringPolicy(); + + long MILLIS_IN_MINUTE = 60 * 1000; + long MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE; + long MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR; + long MILLIS_IN_MONTH = (long) ((365.242199 / 12) * MILLIS_IN_DAY); + int MONTHS_IN_YEAR = 12; + + int slashCount = 0; + + @Before + public void setUp() { + super.setUp(); + } + + private int computeSlashCount(String datePattern) { + if (datePattern == null) + return 0; + else { + int count = 0; + for (int i = 0; i < datePattern.length(); i++) { + char c = datePattern.charAt(i); + if (c == '/') + count++; + } + return count; + } + } + + // test that the number of files at the end of the test is same as the expected number taking into account end dates + // near the beginning of a new year. This test has been run in a loop with start date varying over a two years + // with success. + @Test + public void monthlyRolloverOverManyPeriods() { + + slashCount = computeSlashCount(MONTHLY_CRONOLOG_DATE_PATTERN); + int numPeriods = 40; + int maxHistory = 2; + String fileNamePattern = randomOutputDir + "/%d{" + MONTHLY_CRONOLOG_DATE_PATTERN + "}/clean.txt.zip"; + + long startTime = currentTime; + long endTime = logOverMultiplePeriodsContinuously(currentTime, fileNamePattern, MILLIS_IN_MONTH, maxHistory, numPeriods); + System.out.println("randomOutputDir:" + randomOutputDir); + System.out.println("start:" + startTime + ", end=" + endTime); + int differenceInMonths = RollingCalendar.diffInMonths(startTime, endTime); + System.out.println("differenceInMonths:" + differenceInMonths); + Calendar startTimeAsCalendar = Calendar.getInstance(); + startTimeAsCalendar.setTimeInMillis(startTime); + int indexOfStartPeriod = startTimeAsCalendar.get(Calendar.MONTH); + boolean withExtraFolder = extraFolder(differenceInMonths, MONTHS_IN_YEAR, indexOfStartPeriod, maxHistory); + + check(expectedCountWithFolders(maxHistory, withExtraFolder)); + } + + void generateDailyRollover(long now, int maxHistory, int simulatedNumberOfPeriods, int startInactivity, int numInactivityPeriods) { + slashCount = computeSlashCount(DAILY_DATE_PATTERN); + logOverMultiplePeriods(now, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", MILLIS_IN_DAY, maxHistory, simulatedNumberOfPeriods, + startInactivity, numInactivityPeriods); + check(expectedCountWithoutFoldersWithInactivity(maxHistory, simulatedNumberOfPeriods, startInactivity + numInactivityPeriods)); + } + + @Test + public void basicDailyRollover() { + int maxHistory = 20; + int simulatedNumberOfPeriods = 20 * 3; + int startInactivity = 0; + int numInactivityPeriods = 0; + generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); + } + + // Since the duration of a month (in seconds) varies from month to month, tests with inactivity period must + // be conducted with daily rollover not monthly + @Test + public void dailyRollover15() { + int maxHistory = 5; + int simulatedNumberOfPeriods = 15; + int startInactivity = 6; + int numInactivityPeriods = 3; + generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); + } + + @Test + public void dailyRolloverWithInactivity70() { + int maxHistory = 6; + int simulatedNumberOfPeriods = 70; + int startInactivity = 30; + int numInactivityPeriods = 1; + generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); + } + + @Test + public void dailyRolloverWithInactivity10() { + int maxHistory = 6; + int simulatedNumberOfPeriods = 10; + int startInactivity = 3; + int numInactivityPeriods = 4; + generateDailyRollover(currentTime, maxHistory, simulatedNumberOfPeriods, startInactivity, numInactivityPeriods); + } + + @Test + public void dailyRolloverWithSecondPhase() { + slashCount = computeSlashCount(DAILY_DATE_PATTERN); + int maxHistory = 5; + long endTime = logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", MILLIS_IN_DAY, maxHistory, + maxHistory * 2); + logOverMultiplePeriodsContinuously(endTime + MILLIS_IN_DAY * 10, randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt", MILLIS_IN_DAY, + maxHistory, maxHistory); + check(expectedCountWithoutFolders(maxHistory)); + } + + @Test + public void dailyCronologRollover() { + slashCount = computeSlashCount(DAILY_CRONOLOG_DATE_PATTERN); + logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_CRONOLOG_DATE_PATTERN + "}/clean.txt.zip", MILLIS_IN_DAY, 8, 8 * 3); + int expectedDirMin = 9 + slashCount; + int expectDirMax = expectedDirMin + 1 + 1; + expectedFileAndDirCount(9, expectedDirMin, expectDirMax); + } + + @Test + public void dailySizeBasedRollover() { + SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); + sizeAndTimeBasedFNATP.setMaxFileSize("10000"); + tbfnatp = sizeAndTimeBasedFNATP; + slashCount = computeSlashCount(DAILY_DATE_PATTERN); + logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}-clean.%i.zip", MILLIS_IN_DAY, 5, 5 * 4); + checkPatternCompliance(5 + 1 + slashCount, "\\d{4}-\\d{2}-\\d{2}-clean(\\.\\d)(.zip)?"); + } + + @Test + public void dailyChronologSizeBasedRollover() { + SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); + sizeAndTimeBasedFNATP.setMaxFileSize("10000"); + tbfnatp = sizeAndTimeBasedFNATP; + slashCount = 1; + logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i.zip", MILLIS_IN_DAY, 5, 5 * 4); + checkDirPatternCompliance(6); + } + + @Test + public void dailyChronologSizeBasedRolloverWithSecondPhase() { + SizeAndTimeBasedFNATP sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP(); + sizeAndTimeBasedFNATP.setMaxFileSize("10000"); + tbfnatp = sizeAndTimeBasedFNATP; + slashCount = 1; + int maxHistory = 5; + int simulatedNumberOfPeriods = maxHistory * 4; + long endTime = logOverMultiplePeriodsContinuously(currentTime, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i", MILLIS_IN_DAY, maxHistory, + 3); + logOverMultiplePeriodsContinuously(endTime + MILLIS_IN_DAY * 7, randomOutputDir + "/%d{" + DAILY_DATE_PATTERN + "}/clean.%i", MILLIS_IN_DAY, + maxHistory, simulatedNumberOfPeriods); + checkDirPatternCompliance(maxHistory + 1); + } + + void logOncePeriod(long currentTime, String fileNamePattern, int maxHistory) { + buildRollingFileAppender(currentTime, fileNamePattern, maxHistory, DO_CLEAN_HISTORY_ON_START); + rfa.doAppend("Hello ----------------------------------------------------------" + new Date(currentTime)); + rfa.stop(); + } + + @Test + public void cleanHistoryOnStart() { + long now = this.currentTime; + String fileNamePattern = randomOutputDir + "clean-%d{" + DAILY_DATE_PATTERN + "}.txt"; + int maxHistory = 3; + for (int i = 0; i <= 5; i++) { + logOncePeriod(now, fileNamePattern, maxHistory); + now = now + MILLIS_IN_DAY; + } + // StatusPrinter.print(context); + check(expectedCountWithoutFolders(maxHistory)); + } + + @Test + public void cleanHistoryOnStartWithDayPattern() { + long now = this.currentTime; + String fileNamePattern = randomOutputDir + "clean-%d{yyyy-MM-dd}.txt"; + int maxHistory = 3; + for (int i = 0; i <= 5; i++) { + logOncePeriod(now, fileNamePattern, maxHistory); + now = now + MILLIS_IN_DAY; + } + StatusPrinter.print(context); + check(expectedCountWithoutFolders(maxHistory)); + } + + @Test + public void cleanHistoryOnStartWithHourPattern() { + long now = this.currentTime; + String fileNamePattern = randomOutputDir + "clean-%d{HH}.txt"; + int maxHistory = 3; + for (int i = 0; i <= 5; i++) { + logOncePeriod(now, fileNamePattern, maxHistory); + now = now + MILLIS_IN_HOUR; } - }); - for (File f : matchArray) { - if (f.isDirectory()) { - if (includeDirs) fileList.add(f); - genericFindMatching(matchFunc, f, fileList, pattern, includeDirs); - } else - fileList.add(f); - } - } - } - - private void findAllFoldersInFolderRecursively(File dir, List fileList) { - FileMatchFunction alwaysFalse = new FileMatchFunction() { - public boolean match(File f, String pattern) { - return false; - } - }; - genericFindMatching(alwaysFalse, dir, fileList, null, true); - } - - private void findAllDirsOrStringContainsFilesRecursively(File dir, List fileList, String pattern) { - FileMatchFunction matchFunction = new FileMatchFunction() { - public boolean match(File f, String pattern) { - return f.getName().contains(pattern); - } - }; - genericFindMatching(matchFunction, dir, fileList, pattern, true); - } - - void findFilesInFolderRecursivelyByPatterMatch(File dir, List fileList, String pattern) { - FileMatchFunction matchByPattern = new FileMatchFunction() { - public boolean match(File f, String pattern) { - return f.getName().matches(pattern); - } - }; - genericFindMatching(matchByPattern, dir, fileList, pattern, false); - } - - Set groupByClass(List fileList, String regex) { - Pattern p = Pattern.compile(regex); - Set set = new HashSet(); - for (File f : fileList) { - String n = f.getName(); - Matcher m = p.matcher(n); - m.matches(); - int begin = m.start(1); - String reduced = n.substring(0, begin); - set.add(reduced); - } - return set; - } - - - void checkPatternCompliance(int expectedClassCount, String regex) { - File dir = new File(randomOutputDir); - List fileList = new ArrayList(); - findFilesInFolderRecursivelyByPatterMatch(dir, fileList, regex); - Set set = groupByClass(fileList, regex); - assertEquals(expectedClassCount, set.size()); - } - - void checkDirPatternCompliance(int expectedClassCount) { - File dir = new File(randomOutputDir); - List fileList = new ArrayList(); - findAllFoldersInFolderRecursively(dir, fileList); - for (File f : fileList) { - assertTrue(f.list().length >= 1); - } - assertEquals(expectedClassCount, fileList.size()); - } + // StatusPrinter.print(context); + check(expectedCountWithoutFolders(maxHistory)); + } + + int expectedCountWithoutFolders(int maxHistory) { + return maxHistory + 1; + } + + int expectedCountWithFolders(int maxHistory, boolean withExtraFolder) { + int numLogFiles = (maxHistory + 1); + int numLogFilesAndFolders = numLogFiles * 2; + int result = numLogFilesAndFolders + slashCount; + if (withExtraFolder) + result += 1; + return result; + } + + void buildRollingFileAppender(long currentTime, String fileNamePattern, int maxHistory, boolean cleanHistoryOnStart) { + rfa.setContext(context); + rfa.setEncoder(encoder); + tbrp.setContext(context); + tbrp.setFileNamePattern(fileNamePattern); + tbrp.setMaxHistory(maxHistory); + tbrp.setParent(rfa); + tbrp.setCleanHistoryOnStart(cleanHistoryOnStart); + tbrp.timeBasedFileNamingAndTriggeringPolicy = tbfnatp; + tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + tbrp.start(); + rfa.setRollingPolicy(tbrp); + rfa.start(); + } + + boolean DO_CLEAN_HISTORY_ON_START = true; + boolean DO_NOT_CLEAN_HISTORY_ON_START = false; + + long logOverMultiplePeriodsContinuously(long simulatedTime, String fileNamePattern, long periodDurationInMillis, int maxHistory, + int simulatedNumberOfPeriods) { + return logOverMultiplePeriods(simulatedTime, fileNamePattern, periodDurationInMillis, maxHistory, simulatedNumberOfPeriods, 0, 0); + } + + long logOverMultiplePeriods(long simulatedTime, String fileNamePattern, long periodDurationInMillis, int maxHistory, int simulatedNumberOfPeriods, + int startInactivity, int numInactivityPeriods) { + buildRollingFileAppender(simulatedTime, fileNamePattern, maxHistory, DO_NOT_CLEAN_HISTORY_ON_START); + int ticksPerPeriod = 512; + int runLength = simulatedNumberOfPeriods * ticksPerPeriod; + int startInactivityIndex = 1 + startInactivity * ticksPerPeriod; + int endInactivityIndex = startInactivityIndex + numInactivityPeriods * ticksPerPeriod; + long tickDuration = periodDurationInMillis / ticksPerPeriod; + + for (int i = 0; i <= runLength; i++) { + if (i < startInactivityIndex || i > endInactivityIndex) { + rfa.doAppend("Hello ----------------------------------------------------------" + i); + } + tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(addTime(tbrp.timeBasedFileNamingAndTriggeringPolicy.getCurrentTime(), tickDuration)); + add(tbrp.future); + waitForJobsToComplete(); + } + rfa.stop(); + return tbrp.timeBasedFileNamingAndTriggeringPolicy.getCurrentTime(); + } + + boolean extraFolder(int numPeriods, int periodsPerEra, int beginPeriod, int maxHistory) { + int valueOfLastMonth = ((beginPeriod) + numPeriods) % periodsPerEra; + return (valueOfLastMonth < maxHistory); + } + + long addTime(long time, long timeToWait) { + return time + timeToWait; + } + + void expectedFileAndDirCount(int expectedFileAndDirCount, int expectedDirCountMin, int expectedDirCountMax) { + File dir = new File(randomOutputDir); + List fileList = new ArrayList(); + findFilesInFolderRecursivelyByPatterMatch(dir, fileList, "clean"); + List dirList = new ArrayList(); + findAllFoldersInFolderRecursively(dir, dirList); + String msg = "expectedDirCountMin=" + expectedDirCountMin + ", expectedDirCountMax=" + expectedDirCountMax + " actual value=" + dirList.size(); + assertTrue(msg, expectedDirCountMin <= dirList.size() && dirList.size() <= expectedDirCountMax); + } + + void check(int expectedCount) { + File dir = new File(randomOutputDir); + List fileList = new ArrayList(); + findAllDirsOrStringContainsFilesRecursively(dir, fileList, "clean"); + assertEquals(expectedCount, fileList.size()); + } + + int expectedCountWithoutFoldersWithInactivity(int maxHistory, int totalPeriods, int endOfInactivity) { + int availableHistory = (totalPeriods + 1) - endOfInactivity; + int actualHistory = Math.min(availableHistory, maxHistory + 1); + return actualHistory; + } + + void genericFindMatching(final FileMatchFunction matchFunc, File dir, List fileList, final String pattern, boolean includeDirs) { + if (dir.isDirectory()) { + File[] matchArray = dir.listFiles(new FileFilter() { + public boolean accept(File f) { + return f.isDirectory() || matchFunc.match(f, pattern); + } + }); + for (File f : matchArray) { + if (f.isDirectory()) { + if (includeDirs) + fileList.add(f); + genericFindMatching(matchFunc, f, fileList, pattern, includeDirs); + } else + fileList.add(f); + } + } + } + + private void findAllFoldersInFolderRecursively(File dir, List fileList) { + FileMatchFunction alwaysFalse = new FileMatchFunction() { + public boolean match(File f, String pattern) { + return false; + } + }; + genericFindMatching(alwaysFalse, dir, fileList, null, true); + } + + private void findAllDirsOrStringContainsFilesRecursively(File dir, List fileList, String pattern) { + FileMatchFunction matchFunction = new FileMatchFunction() { + public boolean match(File f, String pattern) { + return f.getName().contains(pattern); + } + }; + genericFindMatching(matchFunction, dir, fileList, pattern, true); + } + + void findFilesInFolderRecursivelyByPatterMatch(File dir, List fileList, String pattern) { + FileMatchFunction matchByPattern = new FileMatchFunction() { + public boolean match(File f, String pattern) { + return f.getName().matches(pattern); + } + }; + genericFindMatching(matchByPattern, dir, fileList, pattern, false); + } + + Set groupByClass(List fileList, String regex) { + Pattern p = Pattern.compile(regex); + Set set = new HashSet(); + for (File f : fileList) { + String n = f.getName(); + Matcher m = p.matcher(n); + m.matches(); + int begin = m.start(1); + String reduced = n.substring(0, begin); + set.add(reduced); + } + return set; + } + + void checkPatternCompliance(int expectedClassCount, String regex) { + File dir = new File(randomOutputDir); + List fileList = new ArrayList(); + findFilesInFolderRecursivelyByPatterMatch(dir, fileList, regex); + Set set = groupByClass(fileList, regex); + assertEquals(expectedClassCount, set.size()); + } + + void checkDirPatternCompliance(int expectedClassCount) { + File dir = new File(randomOutputDir); + List fileList = new ArrayList(); + findAllFoldersInFolderRecursively(dir, fileList); + for (File f : fileList) { + assertTrue(f.list().length >= 1); + } + assertEquals(expectedClassCount, fileList.size()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/ZRolloverChecker.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/ZRolloverChecker.java index ca6d5f02a28a0ae96469ec890ae30959ab49143e..c758aaa2973a6c3ade605485a75946b081e93cd3 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/ZRolloverChecker.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/ZRolloverChecker.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.rolling; - import ch.qos.logback.core.util.Compare; import ch.qos.logback.core.util.CoreTestConstants; @@ -24,16 +23,16 @@ import static org.junit.Assert.assertTrue; public class ZRolloverChecker implements RolloverChecker { - String testId; + String testId; - public ZRolloverChecker(String testId) { - this.testId = testId; - } + public ZRolloverChecker(String testId) { + this.testId = testId; + } - public void check(List expectedFilenameList) throws IOException { - int lastIndex = expectedFilenameList.size() - 1; - String lastFile = expectedFilenameList.get(lastIndex); - String witnessFileName = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId; - assertTrue(Compare.compare(lastFile, witnessFileName)); - } + public void check(List expectedFilenameList) throws IOException { + int lastIndex = expectedFilenameList.size() - 1; + String lastFile = expectedFilenameList.get(lastIndex); + String witnessFileName = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId; + assertTrue(Compare.compare(lastFile, witnessFileName)); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/CompressTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/CompressTest.java index a10cc1ad6681ad5f6f301cf7fdc929a6bf34158c..1e70893e8dc00d44dabd55b5651d91c6e07b870b 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/CompressTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/CompressTest.java @@ -36,105 +36,86 @@ import ch.qos.logback.core.util.CoreTestConstants; */ public class CompressTest { - Context context = new ContextBase(); - - @Before - public void setUp() throws IOException { - // Copy source files - // Delete output files - { - File source = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress1.copy"); - File dest = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress1.txt"); - - copy(source, dest); - File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress1.txt.gz"); - target.mkdirs(); - target.delete(); + Context context = new ContextBase(); + + @Before + public void setUp() throws IOException { + // Copy source files + // Delete output files + { + File source = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress1.copy"); + File dest = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress1.txt"); + + copy(source, dest); + File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "compress1.txt.gz"); + target.mkdirs(); + target.delete(); + } + { + File source = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress2.copy"); + File dest = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress2.txt"); + copy(source, dest); + File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "compress2.txt.gz"); + target.mkdirs(); + target.delete(); + } + { + File source = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress3.copy"); + File dest = new File(CoreTestConstants.TEST_SRC_PREFIX + "input/compress3.txt"); + copy(source, dest); + File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "compress3.txt.zip"); + target.mkdirs(); + target.delete(); + } } - { - File source = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress2.copy"); - File dest = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress2.txt"); - copy(source, dest); - File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress2.txt.gz"); - target.mkdirs(); - target.delete(); + + @Test + public void test1() throws Exception { + Compressor compressor = new Compressor(CompressionMode.GZ); + compressor.setContext(context); + compressor.compress(CoreTestConstants.TEST_SRC_PREFIX + "input/compress1.txt", CoreTestConstants.OUTPUT_DIR_PREFIX + "compress1.txt.gz", null); + + StatusChecker checker = new StatusChecker(context); + assertTrue(checker.isErrorFree(0)); + assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX + "compress1.txt.gz", CoreTestConstants.TEST_SRC_PREFIX + "witness/compress1.txt.gz")); + } + + @Test + public void test2() throws Exception { + Compressor compressor = new Compressor(CompressionMode.GZ); + compressor.setContext(context); + compressor.compress(CoreTestConstants.TEST_SRC_PREFIX + "input/compress2.txt", CoreTestConstants.OUTPUT_DIR_PREFIX + "compress2.txt", null); + + StatusChecker checker = new StatusChecker(context); + assertTrue(checker.isErrorFree(0)); + + assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX + "compress2.txt.gz", CoreTestConstants.TEST_SRC_PREFIX + "witness/compress2.txt.gz")); } - { - File source = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress3.copy"); - File dest = new File(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress3.txt"); - copy(source, dest); - File target = new File(CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress3.txt.zip"); - target.mkdirs(); - target.delete(); + + @Test + public void test3() throws Exception { + Compressor compressor = new Compressor(CompressionMode.ZIP); + compressor.setContext(context); + compressor.compress(CoreTestConstants.TEST_SRC_PREFIX + "input/compress3.txt", CoreTestConstants.OUTPUT_DIR_PREFIX + "compress3.txt", "compress3.txt"); + StatusChecker checker = new StatusChecker(context); + assertTrue(checker.isErrorFree(0)); + + // we don't know how to compare .zip files + // assertTrue(Compare.compare(CoreTestConstants.OUTPUT_DIR_PREFIX + // + "compress3.txt.zip", CoreTestConstants.TEST_SRC_PREFIX + // + "witness/compress3.txt.zip")); } - } - - @Test - public void test1() throws Exception { - Compressor compressor = new Compressor(CompressionMode.GZ); - compressor.setContext(context); - compressor.compress(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress1.txt", CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress1.txt.gz", null); - - StatusChecker checker = new StatusChecker(context); - assertTrue(checker.isErrorFree(0)); - assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress1.txt.gz", CoreTestConstants.TEST_SRC_PREFIX - + "witness/compress1.txt.gz")); - } - - @Test - public void test2() throws Exception { - Compressor compressor = new Compressor(CompressionMode.GZ); - compressor.setContext(context); - compressor.compress(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress2.txt", CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress2.txt", null); - - StatusChecker checker = new StatusChecker(context); - assertTrue(checker.isErrorFree(0)); - - assertTrue(Compare.gzCompare(CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress2.txt.gz", CoreTestConstants.TEST_SRC_PREFIX - + "witness/compress2.txt.gz")); - } - - @Test - public void test3() throws Exception { - Compressor compressor = new Compressor(CompressionMode.ZIP); - compressor.setContext(context); - compressor.compress(CoreTestConstants.TEST_SRC_PREFIX - + "input/compress3.txt", CoreTestConstants.OUTPUT_DIR_PREFIX - + "compress3.txt", "compress3.txt"); - StatusChecker checker = new StatusChecker(context); - assertTrue(checker.isErrorFree(0)); - - // we don't know how to compare .zip files - // assertTrue(Compare.compare(CoreTestConstants.OUTPUT_DIR_PREFIX - // + "compress3.txt.zip", CoreTestConstants.TEST_SRC_PREFIX - // + "witness/compress3.txt.zip")); - } - - private void copy(File src, File dst) throws IOException { - InputStream in = new FileInputStream(src); - OutputStream out = new FileOutputStream(dst); - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); + + private void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + in.close(); + out.close(); } - in.close(); - out.close(); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileNamePatternTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileNamePatternTest.java index ebd889d7e71f4deaf3b506c98a1a712b72683fc1..667e1ef21f938c62b7c69925de3ee3be83644521 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileNamePatternTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileNamePatternTest.java @@ -31,172 +31,162 @@ import ch.qos.logback.core.ContextBase; */ public class FileNamePatternTest { - Context context = new ContextBase(); + Context context = new ContextBase(); - @Test - public void testSmoke() { - FileNamePattern pp = new FileNamePattern("t", context); - assertEquals("t", pp.convertInt(3)); + @Test + public void testSmoke() { + FileNamePattern pp = new FileNamePattern("t", context); + assertEquals("t", pp.convertInt(3)); - pp = new FileNamePattern("foo", context); - assertEquals("foo", pp.convertInt(3)); + pp = new FileNamePattern("foo", context); + assertEquals("foo", pp.convertInt(3)); - pp = new FileNamePattern("%i foo", context); + pp = new FileNamePattern("%i foo", context); - assertEquals("3 foo", pp.convertInt(3)); + assertEquals("3 foo", pp.convertInt(3)); - pp = new FileNamePattern("foo%i.xixo", context); - assertEquals("foo3.xixo", pp.convertInt(3)); + pp = new FileNamePattern("foo%i.xixo", context); + assertEquals("foo3.xixo", pp.convertInt(3)); - pp = new FileNamePattern("foo%i.log", context); - assertEquals("foo3.log", pp.convertInt(3)); + pp = new FileNamePattern("foo%i.log", context); + assertEquals("foo3.log", pp.convertInt(3)); - pp = new FileNamePattern("foo.%i.log", context); - assertEquals("foo.3.log", pp.convertInt(3)); + pp = new FileNamePattern("foo.%i.log", context); + assertEquals("foo.3.log", pp.convertInt(3)); - //pp = new FileNamePattern("%i.foo\\%", context); - //assertEquals("3.foo%", pp.convertInt(3)); + // pp = new FileNamePattern("%i.foo\\%", context); + // assertEquals("3.foo%", pp.convertInt(3)); - //pp = new FileNamePattern("\\%foo", context); - //assertEquals("%foo", pp.convertInt(3)); - } - - @Test - // test ways for dealing with flowing i converter, as in "foo%ix" - public void flowingI() { - { - FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); - assertEquals("foo3bar3", pp.convertInt(3)); + // pp = new FileNamePattern("\\%foo", context); + // assertEquals("%foo", pp.convertInt(3)); } - { - FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); - assertEquals("foo3bar3", pp.convertInt(3)); + + @Test + // test ways for dealing with flowing i converter, as in "foo%ix" + public void flowingI() { + { + FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); + assertEquals("foo3bar3", pp.convertInt(3)); + } + { + FileNamePattern pp = new FileNamePattern("foo%i{}bar%i", context); + assertEquals("foo3bar3", pp.convertInt(3)); + } } - } - @Test - public void date() { - Calendar cal = Calendar.getInstance(); - cal.set(2003, 4, 20, 17, 55); + @Test + public void date() { + Calendar cal = Calendar.getInstance(); + cal.set(2003, 4, 20, 17, 55); + + FileNamePattern pp = new FileNamePattern("foo%d{yyyy.MM.dd}", context); - FileNamePattern pp = new FileNamePattern("foo%d{yyyy.MM.dd}", context); + assertEquals("foo2003.05.20", pp.convert(cal.getTime())); - assertEquals("foo2003.05.20", pp.convert(cal.getTime())); + pp = new FileNamePattern("foo%d{yyyy.MM.dd HH:mm}", context); + assertEquals("foo2003.05.20 17:55", pp.convert(cal.getTime())); - pp = new FileNamePattern("foo%d{yyyy.MM.dd HH:mm}", context); - assertEquals("foo2003.05.20 17:55", pp.convert(cal.getTime())); + pp = new FileNamePattern("%d{yyyy.MM.dd HH:mm} foo", context); + assertEquals("2003.05.20 17:55 foo", pp.convert(cal.getTime())); - pp = new FileNamePattern("%d{yyyy.MM.dd HH:mm} foo", context); - assertEquals("2003.05.20 17:55 foo", pp.convert(cal.getTime())); + } - } + @Test + public void dateWithTimeZone() { + TimeZone utc = TimeZone.getTimeZone("UTC"); + Calendar cal = Calendar.getInstance(utc); + cal.set(2003, 4, 20, 10, 55); - - @Test - public void dateWithTimeZone() { - TimeZone utc = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(utc); - cal.set(2003, 4, 20, 10, 55); + FileNamePattern fnp = new FileNamePattern("foo%d{yyyy-MM-dd'T'HH:mm, Australia/Perth}", context); + // Perth is 8 hours ahead of UTC + assertEquals("foo2003-05-20T18:55", fnp.convert(cal.getTime())); + } - FileNamePattern fnp = new FileNamePattern("foo%d{yyyy-MM-dd'T'HH:mm, Australia/Perth}", context); - // Perth is 8 hours ahead of UTC - assertEquals("foo2003-05-20T18:55", fnp.convert(cal.getTime())); - } + @Test + public void auxAndTimeZoneShouldNotConflict() { + TimeZone utc = TimeZone.getTimeZone("UTC"); + Calendar cal = Calendar.getInstance(utc); + cal.set(2003, 4, 20, 10, 55); + + { + FileNamePattern fnp = new FileNamePattern("foo%d{yyyy-MM-dd'T'HH:mm, aux, Australia/Perth}", context); + // Perth is 8 hours ahead of UTC + assertEquals("foo2003-05-20T18:55", fnp.convert(cal.getTime())); + assertNull(fnp.getPrimaryDateTokenConverter()); + } + + { + FileNamePattern fnp = new FileNamePattern("folder/%d{yyyy/MM, aux, Australia/Perth}/test.%d{yyyy-MM-dd'T'HHmm, Australia/Perth}.log", context); + assertEquals("folder/2003/05/test.2003-05-20T1855.log", fnp.convert(cal.getTime())); + assertNotNull(fnp.getPrimaryDateTokenConverter()); + } + } - @Test - public void auxAndTimeZoneShouldNotConflict() { - TimeZone utc = TimeZone.getTimeZone("UTC"); - Calendar cal = Calendar.getInstance(utc); - cal.set(2003, 4, 20, 10, 55); + @Test + public void withBackslash() { + FileNamePattern pp = new FileNamePattern("c:\\foo\\bar.%i", context); + assertEquals("c:/foo/bar.3", pp.convertInt(3)); + } - { - FileNamePattern fnp = new FileNamePattern("foo%d{yyyy-MM-dd'T'HH:mm, aux, Australia/Perth}", context); - // Perth is 8 hours ahead of UTC - assertEquals("foo2003-05-20T18:55", fnp.convert(cal.getTime())); - assertNull(fnp.getPrimaryDateTokenConverter()); + @Test + public void objectListConverter() { + Calendar cal = Calendar.getInstance(); + cal.set(2003, 4, 20, 17, 55); + FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); + assertEquals("foo-2003.05.20-79.txt", fnp.convertMultipleArguments(cal.getTime(), 79)); } - { - FileNamePattern fnp = new FileNamePattern("folder/%d{yyyy/MM, aux, Australia/Perth}/test.%d{yyyy-MM-dd'T'HHmm, Australia/Perth}.log", context); - assertEquals("folder/2003/05/test.2003-05-20T1855.log", fnp.convert(cal.getTime())); - assertNotNull(fnp.getPrimaryDateTokenConverter()); + @Test + public void asRegexByDate() { + + Calendar cal = Calendar.getInstance(); + cal.set(2003, 4, 20, 17, 55); + + { + FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); + String regex = fnp.toRegexForFixedDate(cal.getTime()); + assertEquals("foo-2003.05.20-(\\d{1,3}).txt", regex); + } + { + FileNamePattern fnp = new FileNamePattern("\\toto\\foo-%d{yyyy\\MM\\dd}-%i.txt", context); + String regex = fnp.toRegexForFixedDate(cal.getTime()); + assertEquals("/toto/foo-2003/05/20-(\\d{1,3}).txt", regex); + } } - } - - - @Test - public void withBackslash() { - FileNamePattern pp = new FileNamePattern("c:\\foo\\bar.%i", context); - assertEquals("c:/foo/bar.3", pp.convertInt(3)); - } - - @Test - public void objectListConverter() { - Calendar cal = Calendar.getInstance(); - cal.set(2003, 4, 20, 17, 55); - FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", - context); - assertEquals("foo-2003.05.20-79.txt", fnp.convertMultipleArguments(cal - .getTime(), 79)); - } - - @Test - public void asRegexByDate() { - - Calendar cal = Calendar.getInstance(); - cal.set(2003, 4, 20, 17, 55); - - { - FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", - context); - String regex = fnp.toRegexForFixedDate(cal.getTime()); - assertEquals("foo-2003.05.20-(\\d{1,3}).txt", regex); + + @Test + public void asRegex() { + { + FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", context); + String regex = fnp.toRegex(); + assertEquals("foo-\\d{4}\\.\\d{2}\\.\\d{2}-\\d{1,2}.txt", regex); + } + { + FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd'T'}-%i.txt", context); + String regex = fnp.toRegex(); + assertEquals("foo-\\d{4}\\.\\d{2}\\.\\d{2}T-\\d{1,2}.txt", regex); + } } - { - FileNamePattern fnp = new FileNamePattern("\\toto\\foo-%d{yyyy\\MM\\dd}-%i.txt", - context); - String regex = fnp.toRegexForFixedDate(cal.getTime()); - assertEquals("/toto/foo-2003/05/20-(\\d{1,3}).txt", regex); + + @Test + public void convertMultipleDates() { + Calendar cal = Calendar.getInstance(); + cal.set(2003, 4, 20, 17, 55); + FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM, aux}/%d{yyyy.MM.dd}.txt", context); + assertEquals("foo-2003.05/2003.05.20.txt", fnp.convert(cal.getTime())); } - } - - @Test - public void asRegex() { - { - FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd}-%i.txt", - context); - String regex = fnp.toRegex(); - assertEquals("foo-\\d{4}\\.\\d{2}\\.\\d{2}-\\d{1,2}.txt", regex); + + @Test + public void nullTimeZoneByDefault() { + FileNamePattern fnp = new FileNamePattern("%d{hh}", context); + assertNull(fnp.getPrimaryDateTokenConverter().getTimeZone()); } - { - FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM.dd'T'}-%i.txt", - context); - String regex = fnp.toRegex(); - assertEquals("foo-\\d{4}\\.\\d{2}\\.\\d{2}T-\\d{1,2}.txt", regex); + + @Test + public void settingTimeZoneOptionHasAnEffect() { + TimeZone tz = TimeZone.getTimeZone("Australia/Perth"); + + FileNamePattern fnp = new FileNamePattern("%d{hh, " + tz.getID() + "}", context); + assertEquals(tz, fnp.getPrimaryDateTokenConverter().getTimeZone()); } - } - - @Test - public void convertMultipleDates() { - Calendar cal = Calendar.getInstance(); - cal.set(2003, 4, 20, 17, 55); - FileNamePattern fnp = new FileNamePattern("foo-%d{yyyy.MM, aux}/%d{yyyy.MM.dd}.txt", context); - assertEquals("foo-2003.05/2003.05.20.txt", fnp.convert(cal.getTime())); - } - - - @Test - public void nullTimeZoneByDefault() { - FileNamePattern fnp = new FileNamePattern("%d{hh}", context); - assertNull(fnp.getPrimaryDateTokenConverter().getTimeZone()); - } - - - @Test - public void settingTimeZoneOptionHasAnEffect() { - TimeZone tz = TimeZone.getTimeZone("Australia/Perth"); - - FileNamePattern fnp = new FileNamePattern("%d{hh, " + tz.getID() + "}", context); - assertEquals(tz, fnp.getPrimaryDateTokenConverter().getTimeZone()); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileStoreUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileStoreUtilTest.java index 08c49fce6a5c5d8b81a6e3a52028598edaf227ca..c980e8cf6573db0e36078959d05255b44d2d3be2 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileStoreUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/FileStoreUtilTest.java @@ -29,33 +29,31 @@ import static org.junit.Assert.assertTrue; public class FileStoreUtilTest { - - int diff = RandomUtil.getPositiveInt(); - String pathPrefix = CoreTestConstants.OUTPUT_DIR_PREFIX+"fs"+diff+"/"; - - @Test - public void filesOnSameFolderShouldBeOnTheSameFileStore() throws RolloverFailure, IOException { - if(!EnvUtil.isJDK7OrHigher()) - return; - - File parent = new File(pathPrefix); - File file = new File(pathPrefix+"filesOnSameFolderShouldBeOnTheSameFileStore"); - FileUtil.createMissingParentDirectories(file); - file.createNewFile(); - assertTrue(FileStoreUtil.areOnSameFileStore(parent, file)); - } - - - // test should be run manually - @Ignore - @Test - public void manual_filesOnDifferentVolumesShouldBeDetectedAsSuch() throws RolloverFailure { - if(!EnvUtil.isJDK7OrHigher()) - return; - - // author's computer has two volumes - File c = new File("c:/tmp/"); - File d = new File("d:/"); - assertFalse(FileStoreUtil.areOnSameFileStore(c, d)); - } + int diff = RandomUtil.getPositiveInt(); + String pathPrefix = CoreTestConstants.OUTPUT_DIR_PREFIX + "fs" + diff + "/"; + + @Test + public void filesOnSameFolderShouldBeOnTheSameFileStore() throws RolloverFailure, IOException { + if (!EnvUtil.isJDK7OrHigher()) + return; + + File parent = new File(pathPrefix); + File file = new File(pathPrefix + "filesOnSameFolderShouldBeOnTheSameFileStore"); + FileUtil.createMissingParentDirectories(file); + file.createNewFile(); + assertTrue(FileStoreUtil.areOnSameFileStore(parent, file)); + } + + // test should be run manually + @Ignore + @Test + public void manual_filesOnDifferentVolumesShouldBeDetectedAsSuch() throws RolloverFailure { + if (!EnvUtil.isJDK7OrHigher()) + return; + + // author's computer has two volumes + File c = new File("c:/tmp/"); + File d = new File("d:/"); + assertFalse(FileStoreUtil.areOnSameFileStore(c, d)); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/PackageTest.java index 8dcd89c0b75c0f91626ad54387c44efe94698df4..553fab438afaea58333248cf7bc6ca1a74b51a70 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/PackageTest.java @@ -20,8 +20,7 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses( { CompressTest.class, FileNamePatternTest.class, - RollingCalendarTest.class, DatePatternToRegexTest.class }) +@Suite.SuiteClasses({ CompressTest.class, FileNamePatternTest.class, RollingCalendarTest.class, DatePatternToRegexTest.class }) public class PackageTest extends TestCase { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java index d8b5ecb8927a68554a45d5f1c2752b4fbbe17a65..6bf9a3b17f9aac0b9a2b19a67deafb85daf9e5c8 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/rolling/helper/RollingCalendarTest.java @@ -94,10 +94,10 @@ public class RollingCalendarTest { checkCollisionFreeness("yyyy-MM-dd HH", true); checkCollisionFreeness("yyyy-MM-dd kk", true); - + checkCollisionFreeness("yyyy-MM-dd KK", false); checkCollisionFreeness("yyyy-MM-dd KK a", true); - + // daily checkCollisionFreeness("yyyy-MM-dd", true); checkCollisionFreeness("yyyy-dd", false); @@ -109,7 +109,7 @@ public class RollingCalendarTest { checkCollisionFreeness("yyyy-MM-dd-uu", true); checkCollisionFreeness("yyyy-MM-uu", false); - + // weekly checkCollisionFreeness("yyyy-MM-WW", true); checkCollisionFreeness("yyyy-WW", false); diff --git a/logback-core/src/test/java/ch/qos/logback/core/sift/AppenderTrackerTest.java b/logback-core/src/test/java/ch/qos/logback/core/sift/AppenderTrackerTest.java index 51d3885210abe9a555337edd8fd57dd81a5e8eed..5c23a096197de5d66dc39d76d53be671bc2e57e4 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/sift/AppenderTrackerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/sift/AppenderTrackerTest.java @@ -32,122 +32,121 @@ import static org.junit.Assert.*; */ public class AppenderTrackerTest { - Context context = new ContextBase(); - ListAppenderFactory listAppenderFactory = new ListAppenderFactory(); - int diff = RandomUtil.getPositiveInt(); - AppenderTracker appenderTracker = new AppenderTracker(context, listAppenderFactory); - String key = "k-" + diff; - long now = 3000; - - @Before - public void setUp() { - } - - @Test - public void removeStaleComponentsShouldNotBomb() { - appenderTracker.removeStaleComponents(now); - assertEquals(0, appenderTracker.getComponentCount()); - } - - @Test - public void findingTheInexistentShouldNotBomb() { - assertNull(appenderTracker.find(key)); - now += AppenderTracker.DEFAULT_TIMEOUT + 1; - appenderTracker.removeStaleComponents(now); - assertNull(appenderTracker.find(key)); - } - - @Test - public void smoke() { - Appender a = appenderTracker.getOrCreate(key, now); - assertTrue(a.isStarted()); - now += AppenderTracker.DEFAULT_TIMEOUT + 1; - appenderTracker.removeStaleComponents(now); - assertFalse(a.isStarted()); - assertNull(appenderTracker.find(key)); - } - - @Test - public void endOfLivedAppendersShouldBeRemovedAfterLingeringTimeout() { - Appender a = appenderTracker.getOrCreate(key, now); - appenderTracker.endOfLife(key); - now += AppenderTracker.LINGERING_TIMEOUT + 1; - appenderTracker.removeStaleComponents(now); - assertFalse(a.isStarted()); - a = appenderTracker.find(key); - assertNull(a); - } - - @Test - public void endOfLivedAppenderShouldBeAvailableDuringLingeringPeriod() { - Appender a = appenderTracker.getOrCreate(key, now); - appenderTracker.endOfLife(key); - // clean - appenderTracker.removeStaleComponents(now); - Appender lingering = appenderTracker.getOrCreate(key, now); - assertTrue(lingering.isStarted()); - assertTrue(a == lingering); - now += AppenderTracker.LINGERING_TIMEOUT + 1; - appenderTracker.removeStaleComponents(now); - assertFalse(a.isStarted()); - a = appenderTracker.find(key); - assertNull(a); - } - - - @Test - public void trackerShouldHonorMaxComponentsParameter() { - List> appenderList = new ArrayList>(); - int max = 10; - appenderTracker.setMaxComponents(max); - for (int i = 0; i < (max + 1); i++) { - Appender a = appenderTracker.getOrCreate(key + "-" + i, now++); - appenderList.add(a); + Context context = new ContextBase(); + ListAppenderFactory listAppenderFactory = new ListAppenderFactory(); + int diff = RandomUtil.getPositiveInt(); + AppenderTracker appenderTracker = new AppenderTracker(context, listAppenderFactory); + String key = "k-" + diff; + long now = 3000; + + @Before + public void setUp() { } - // cleaning only happens in removeStaleComponents - appenderTracker.removeStaleComponents(now++); - assertEquals(max, appenderTracker.allKeys().size()); - assertNull(appenderTracker.find(key + "-" + 0)); - assertFalse(appenderList.get(0).isStarted()); - } - - @Test - public void trackerShouldHonorTimeoutParameter() { - List> appenderList = new ArrayList>(); - int timeout = 2; - appenderTracker.setTimeout(timeout); - for (int i = 0; i <= timeout; i++) { - Appender a = appenderTracker.getOrCreate(key + "-" + i, now++); - appenderList.add(a); + + @Test + public void removeStaleComponentsShouldNotBomb() { + appenderTracker.removeStaleComponents(now); + assertEquals(0, appenderTracker.getComponentCount()); + } + + @Test + public void findingTheInexistentShouldNotBomb() { + assertNull(appenderTracker.find(key)); + now += AppenderTracker.DEFAULT_TIMEOUT + 1; + appenderTracker.removeStaleComponents(now); + assertNull(appenderTracker.find(key)); + } + + @Test + public void smoke() { + Appender a = appenderTracker.getOrCreate(key, now); + assertTrue(a.isStarted()); + now += AppenderTracker.DEFAULT_TIMEOUT + 1; + appenderTracker.removeStaleComponents(now); + assertFalse(a.isStarted()); + assertNull(appenderTracker.find(key)); } - long numComponentsCreated = timeout + 1; - assertEquals(numComponentsCreated, appenderTracker.allKeys().size()); + @Test + public void endOfLivedAppendersShouldBeRemovedAfterLingeringTimeout() { + Appender a = appenderTracker.getOrCreate(key, now); + appenderTracker.endOfLife(key); + now += AppenderTracker.LINGERING_TIMEOUT + 1; + appenderTracker.removeStaleComponents(now); + assertFalse(a.isStarted()); + a = appenderTracker.find(key); + assertNull(a); + } - // cleaning only happens in removeStaleComponents. The first appender should timeout - appenderTracker.removeStaleComponents(now++); + @Test + public void endOfLivedAppenderShouldBeAvailableDuringLingeringPeriod() { + Appender a = appenderTracker.getOrCreate(key, now); + appenderTracker.endOfLife(key); + // clean + appenderTracker.removeStaleComponents(now); + Appender lingering = appenderTracker.getOrCreate(key, now); + assertTrue(lingering.isStarted()); + assertTrue(a == lingering); + now += AppenderTracker.LINGERING_TIMEOUT + 1; + appenderTracker.removeStaleComponents(now); + assertFalse(a.isStarted()); + a = appenderTracker.find(key); + assertNull(a); + } - // the first appender should have been removed - assertEquals(numComponentsCreated - 1, appenderTracker.allKeys().size()); - assertNull(appenderTracker.find(key + "-" + 0)); - assertFalse(appenderList.get(0).isStarted()); + @Test + public void trackerShouldHonorMaxComponentsParameter() { + List> appenderList = new ArrayList>(); + int max = 10; + appenderTracker.setMaxComponents(max); + for (int i = 0; i < (max + 1); i++) { + Appender a = appenderTracker.getOrCreate(key + "-" + i, now++); + appenderList.add(a); + } + // cleaning only happens in removeStaleComponents + appenderTracker.removeStaleComponents(now++); + assertEquals(max, appenderTracker.allKeys().size()); + assertNull(appenderTracker.find(key + "-" + 0)); + assertFalse(appenderList.get(0).isStarted()); + } - // the other appenders should be in the tracker - for (int i = 1; i <= timeout; i++) { - assertNotNull(appenderTracker.find(key + "-" + i)); - assertTrue(appenderList.get(i).isStarted()); + @Test + public void trackerShouldHonorTimeoutParameter() { + List> appenderList = new ArrayList>(); + int timeout = 2; + appenderTracker.setTimeout(timeout); + for (int i = 0; i <= timeout; i++) { + Appender a = appenderTracker.getOrCreate(key + "-" + i, now++); + appenderList.add(a); + } + + long numComponentsCreated = timeout + 1; + assertEquals(numComponentsCreated, appenderTracker.allKeys().size()); + + // cleaning only happens in removeStaleComponents. The first appender should timeout + appenderTracker.removeStaleComponents(now++); + + // the first appender should have been removed + assertEquals(numComponentsCreated - 1, appenderTracker.allKeys().size()); + assertNull(appenderTracker.find(key + "-" + 0)); + assertFalse(appenderList.get(0).isStarted()); + + // the other appenders should be in the tracker + for (int i = 1; i <= timeout; i++) { + assertNotNull(appenderTracker.find(key + "-" + i)); + assertTrue(appenderList.get(i).isStarted()); + } } - } - // ====================================================================== - static class ListAppenderFactory implements AppenderFactory { + // ====================================================================== + static class ListAppenderFactory implements AppenderFactory { - public Appender buildAppender(Context context, String discriminatingValue) throws JoranException { - ListAppender la = new ListAppender(); - la.setContext(context); - la.setName(discriminatingValue); - la.start(); - return la; + public Appender buildAppender(Context context, String discriminatingValue) throws JoranException { + ListAppender la = new ListAppender(); + la.setContext(context); + la.setName(discriminatingValue); + la.start(); + return la; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/sift/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/sift/PackageTest.java index 01b576f161bb5544c4a7cd4aff99c99024704b82..e641974dda3244894dbf005ab92758ec876b609d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/sift/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/sift/PackageTest.java @@ -18,6 +18,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({AppenderTrackerTest.class}) -public class PackageTest { +@SuiteClasses({ AppenderTrackerTest.class }) +public class PackageTest { } \ No newline at end of file diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplLockTest.java b/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplLockTest.java index 52100004637b0cab6db34833b28d4ab970035c0d..2031848faf356d6aeafa314761e749d2828a4a62 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplLockTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplLockTest.java @@ -47,52 +47,52 @@ import static org.mockito.Mockito.when; */ public class AppenderAttachableImplLockTest { - private AppenderAttachableImpl aai = new AppenderAttachableImpl(); + private AppenderAttachableImpl aai = new AppenderAttachableImpl(); - @SuppressWarnings("unchecked") - @Test(timeout = 5000) - public void getAppenderBoom() { - Appender mockAppender1 = mock(Appender.class); + @SuppressWarnings("unchecked") + @Test(timeout = 5000) + public void getAppenderBoom() { + Appender mockAppender1 = mock(Appender.class); - when(mockAppender1.getName()).thenThrow(new OutOfMemoryError("oops")); - aai.addAppender(mockAppender1); - try { - // appender.getName called as a result of next statement - aai.getAppender("foo"); - } catch (OutOfMemoryError e) { - // this leaves the read lock locked. + when(mockAppender1.getName()).thenThrow(new OutOfMemoryError("oops")); + aai.addAppender(mockAppender1); + try { + // appender.getName called as a result of next statement + aai.getAppender("foo"); + } catch (OutOfMemoryError e) { + // this leaves the read lock locked. + } + + Appender mockAppender2 = mock(Appender.class); + // the next call used to freeze with the earlier ReadWriteLock lock + // implementation + aai.addAppender(mockAppender2); } - Appender mockAppender2=mock(Appender.class); - // the next call used to freeze with the earlier ReadWriteLock lock - // implementation - aai.addAppender(mockAppender2); - } + @SuppressWarnings("unchecked") + @Test(timeout = 5000) + public void detachAppenderBoom() throws InterruptedException { + Appender mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenThrow(new OutOfMemoryError("oops")); + mockAppender.doAppend(17); - @SuppressWarnings("unchecked") - @Test(timeout = 5000) - public void detachAppenderBoom() throws InterruptedException { - Appender mockAppender = mock(Appender.class); - when(mockAppender.getName()).thenThrow(new OutOfMemoryError("oops")); - mockAppender.doAppend(17); + aai.addAppender(mockAppender); + Thread t = new Thread(new Runnable() { - aai.addAppender(mockAppender); - Thread t = new Thread(new Runnable() { + public void run() { + try { + // appender.getName called as a result of next statement + aai.detachAppender("foo"); + } catch (OutOfMemoryError e) { + // this leaves the write lock locked. + } + } + }); + t.start(); + t.join(); - public void run() { - try { - // appender.getName called as a result of next statement - aai.detachAppender("foo"); - } catch (OutOfMemoryError e) { - // this leaves the write lock locked. - } - } - }); - t.start(); - t.join(); - - // the next call used to freeze with the earlier ReadWriteLock lock - // implementation - aai.appendLoopOnAppenders(17); - } + // the next call used to freeze with the earlier ReadWriteLock lock + // implementation + aai.appendLoopOnAppenders(17); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplTest.java b/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplTest.java index 860d8bfb173ff3bc521b66a7c7f62fe39f46bf1b..682ab420c856016440e16aea5babf99156367284 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/AppenderAttachableImplTest.java @@ -13,7 +13,6 @@ */ package ch.qos.logback.core.spi; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -35,136 +34,134 @@ import ch.qos.logback.core.helpers.NOPAppender; */ public class AppenderAttachableImplTest { - - private AppenderAttachableImpl aai; - - @Before - public void setUp() throws Exception { - aai = new AppenderAttachableImpl(); - } - - @After - public void tearDown() throws Exception { - aai = null; - } - - @Test - public void testAddAppender() throws Exception { - TestEvent event = new TestEvent(); - NOPAppender ta = new NOPAppender(); - ta.start(); - aai.addAppender(ta); - ta = new NOPAppender(); - ta.setName("test"); - ta.start(); - aai.addAppender(ta); - int size = aai.appendLoopOnAppenders(event); - assertTrue("Incorrect number of appenders", size == 2); - } - - @Test - public void testIteratorForAppenders() throws Exception { - NOPAppender ta = new NOPAppender(); - ta.start(); - aai.addAppender(ta); - NOPAppender tab = new NOPAppender(); - tab.setName("test"); - tab.start(); - aai.addAppender(tab); - Iterator> iter = aai.iteratorForAppenders(); - int size = 0; - while (iter.hasNext()) { - ++size; - Appender app = iter.next(); - assertTrue("Bad Appender", app == ta || app == tab); + private AppenderAttachableImpl aai; + + @Before + public void setUp() throws Exception { + aai = new AppenderAttachableImpl(); } - assertTrue("Incorrect number of appenders", size == 2); - } - - @Test - public void getGetAppender() throws Exception { - NOPAppender test = new NOPAppender(); - test.setName("test"); - test.start(); - aai.addAppender(test); - - NOPAppender testOther = new NOPAppender(); - testOther.setName("testOther"); - testOther.start(); - aai.addAppender(testOther); - - Appender a = aai.getAppender("testOther"); - assertNotNull("Could not find appender", a); - assertTrue("Wrong appender", a == testOther); - - a = aai.getAppender("test"); - assertNotNull("Could not find appender", a); - assertTrue("Wrong appender", a == test); - a = aai.getAppender("NotThere"); - assertNull("Appender was returned", a); - } - - @Test - public void testIsAttached() throws Exception { - NOPAppender ta = new NOPAppender(); - ta.start(); - aai.addAppender(ta); - NOPAppender tab = new NOPAppender(); - tab.setName("test"); - tab.start(); - aai.addAppender(tab); - assertTrue("Appender is not attached", aai.isAttached(ta)); - assertTrue("Appender is not attached", aai.isAttached(tab)); - } - - @Test - public void testDetachAndStopAllAppenders() throws Exception { - NOPAppender ta = new NOPAppender(); - ta.start(); - aai.addAppender(ta); - NOPAppender tab = new NOPAppender(); - tab.setName("test"); - tab.start(); - aai.addAppender(tab); - assertTrue("Appender was not started", tab.isStarted()); - aai.detachAndStopAllAppenders(); - assertNull("Appender was not removed", aai.getAppender("test")); - assertFalse("Appender was not stopped", tab.isStarted()); - } - - @Test - public void testDetachAppender() throws Exception { - NOPAppender ta = new NOPAppender(); - ta.start(); - aai.addAppender(ta); - NOPAppender tab = new NOPAppender(); - tab.setName("test"); - tab.start(); - aai.addAppender(tab); - assertTrue("Appender not detached", aai.detachAppender(tab)); - assertNull("Appender was not removed", aai.getAppender("test")); - assertFalse("Appender detach error", aai.detachAppender(tab)); - } - - @Test - public void testDetachAppenderByName() throws Exception { - NOPAppender ta = new NOPAppender(); - ta.setName("test1"); - ta.start(); - aai.addAppender(ta); - NOPAppender tab = new NOPAppender(); - tab.setName("test"); - tab.start(); - aai.addAppender(tab); - - assertTrue(aai.detachAppender("test")); - assertTrue(aai.detachAppender("test1")); - assertFalse( aai.detachAppender("test1")); - } - - private static class TestEvent { - - } -} + @After + public void tearDown() throws Exception { + aai = null; + } + + @Test + public void testAddAppender() throws Exception { + TestEvent event = new TestEvent(); + NOPAppender ta = new NOPAppender(); + ta.start(); + aai.addAppender(ta); + ta = new NOPAppender(); + ta.setName("test"); + ta.start(); + aai.addAppender(ta); + int size = aai.appendLoopOnAppenders(event); + assertTrue("Incorrect number of appenders", size == 2); + } + + @Test + public void testIteratorForAppenders() throws Exception { + NOPAppender ta = new NOPAppender(); + ta.start(); + aai.addAppender(ta); + NOPAppender tab = new NOPAppender(); + tab.setName("test"); + tab.start(); + aai.addAppender(tab); + Iterator> iter = aai.iteratorForAppenders(); + int size = 0; + while (iter.hasNext()) { + ++size; + Appender app = iter.next(); + assertTrue("Bad Appender", app == ta || app == tab); + } + assertTrue("Incorrect number of appenders", size == 2); + } + + @Test + public void getGetAppender() throws Exception { + NOPAppender test = new NOPAppender(); + test.setName("test"); + test.start(); + aai.addAppender(test); + + NOPAppender testOther = new NOPAppender(); + testOther.setName("testOther"); + testOther.start(); + aai.addAppender(testOther); + + Appender a = aai.getAppender("testOther"); + assertNotNull("Could not find appender", a); + assertTrue("Wrong appender", a == testOther); + + a = aai.getAppender("test"); + assertNotNull("Could not find appender", a); + assertTrue("Wrong appender", a == test); + a = aai.getAppender("NotThere"); + assertNull("Appender was returned", a); + } + + @Test + public void testIsAttached() throws Exception { + NOPAppender ta = new NOPAppender(); + ta.start(); + aai.addAppender(ta); + NOPAppender tab = new NOPAppender(); + tab.setName("test"); + tab.start(); + aai.addAppender(tab); + assertTrue("Appender is not attached", aai.isAttached(ta)); + assertTrue("Appender is not attached", aai.isAttached(tab)); + } + + @Test + public void testDetachAndStopAllAppenders() throws Exception { + NOPAppender ta = new NOPAppender(); + ta.start(); + aai.addAppender(ta); + NOPAppender tab = new NOPAppender(); + tab.setName("test"); + tab.start(); + aai.addAppender(tab); + assertTrue("Appender was not started", tab.isStarted()); + aai.detachAndStopAllAppenders(); + assertNull("Appender was not removed", aai.getAppender("test")); + assertFalse("Appender was not stopped", tab.isStarted()); + } + @Test + public void testDetachAppender() throws Exception { + NOPAppender ta = new NOPAppender(); + ta.start(); + aai.addAppender(ta); + NOPAppender tab = new NOPAppender(); + tab.setName("test"); + tab.start(); + aai.addAppender(tab); + assertTrue("Appender not detached", aai.detachAppender(tab)); + assertNull("Appender was not removed", aai.getAppender("test")); + assertFalse("Appender detach error", aai.detachAppender(tab)); + } + + @Test + public void testDetachAppenderByName() throws Exception { + NOPAppender ta = new NOPAppender(); + ta.setName("test1"); + ta.start(); + aai.addAppender(ta); + NOPAppender tab = new NOPAppender(); + tab.setName("test"); + tab.start(); + aai.addAppender(tab); + + assertTrue(aai.detachAppender("test")); + assertTrue(aai.detachAppender("test1")); + assertFalse(aai.detachAppender("test1")); + } + + private static class TestEvent { + + } + +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerSimulator.java b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerSimulator.java index b9439c0dae12651d3e3d680bd34007792ca9f535..ba020db53c8d7feba9abab4652ecc4046f94b55e 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerSimulator.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerSimulator.java @@ -22,113 +22,107 @@ import java.util.*; */ public class CyclicBufferTrackerSimulator { - static class Parameters { - public int keySpaceLen; - public int maxTimestampInc; - public int simulationLength; - } - - CyclicBufferTracker realCBTracker = new CyclicBufferTracker(); - CyclicBufferTrackerT t_CBTracker = new CyclicBufferTrackerT(); - - List scenario = new ArrayList(); - List keySpace = new ArrayList(); - Random randomKeyGen = new Random(100); - Random simulatorRandom = new Random(11234); - Parameters params; - - int getToEndOfLifeRatio = 10; - - CyclicBufferTrackerSimulator(Parameters params) { - this.params = params; - Map checkMap = new HashMap(); - for (int i = 0; i < params.keySpaceLen; i++) { - String k = getRandomKeyStr(); - if (checkMap.containsKey(k)) { - System.out.println("random key collision occurred"); - k += "" + i; - } - keySpace.add(k); - checkMap.put(k, k); + static class Parameters { + public int keySpaceLen; + public int maxTimestampInc; + public int simulationLength; } - } - - private String getRandomKeyStr() { - int ri = randomKeyGen.nextInt(); - return String.format("%X", ri); - } - - void buildScenario() { - long timestamp = 30000; - int keySpaceLen = keySpace.size(); - for (int i = 0; i < params.simulationLength; i++) { - int keyIndex = simulatorRandom.nextInt(keySpaceLen); - timestamp += simulatorRandom.nextInt(params.maxTimestampInc); - String key = keySpace.get(keyIndex); - scenario.add(new SimulationEvent(EventType.INSERT, key, timestamp)); - if (simulatorRandom.nextInt(getToEndOfLifeRatio) == 0) { - scenario.add(new SimulationEvent(EventType.END_OF_LIFE, key, timestamp)); - } - scenario.add(new SimulationEvent(EventType.REMOVE_STALE, key, timestamp)); + CyclicBufferTracker realCBTracker = new CyclicBufferTracker(); + CyclicBufferTrackerT t_CBTracker = new CyclicBufferTrackerT(); + + List scenario = new ArrayList(); + List keySpace = new ArrayList(); + Random randomKeyGen = new Random(100); + Random simulatorRandom = new Random(11234); + Parameters params; + + int getToEndOfLifeRatio = 10; + + CyclicBufferTrackerSimulator(Parameters params) { + this.params = params; + Map checkMap = new HashMap(); + for (int i = 0; i < params.keySpaceLen; i++) { + String k = getRandomKeyStr(); + if (checkMap.containsKey(k)) { + System.out.println("random key collision occurred"); + k += "" + i; + } + keySpace.add(k); + checkMap.put(k, k); + } + + } + + private String getRandomKeyStr() { + int ri = randomKeyGen.nextInt(); + return String.format("%X", ri); } - } - public void dump() { - for (SimulationEvent simeEvent : scenario) { - System.out.println(simeEvent); + void buildScenario() { + long timestamp = 30000; + int keySpaceLen = keySpace.size(); + for (int i = 0; i < params.simulationLength; i++) { + int keyIndex = simulatorRandom.nextInt(keySpaceLen); + timestamp += simulatorRandom.nextInt(params.maxTimestampInc); + String key = keySpace.get(keyIndex); + scenario.add(new SimulationEvent(EventType.INSERT, key, timestamp)); + if (simulatorRandom.nextInt(getToEndOfLifeRatio) == 0) { + scenario.add(new SimulationEvent(EventType.END_OF_LIFE, key, timestamp)); + } + scenario.add(new SimulationEvent(EventType.REMOVE_STALE, key, timestamp)); + } } - } - - - void play(SimulationEvent simulationEvent, - ComponentTracker> tracker) { - String key = simulationEvent.key; - long timestamp = simulationEvent.timestamp; - EventType eventType = simulationEvent.eventType; - switch (eventType) { - case INSERT: - tracker.getOrCreate(key, timestamp); - break; - case END_OF_LIFE: - tracker.endOfLife(key); - break; - case REMOVE_STALE: - tracker.removeStaleComponents(timestamp); - break; + + public void dump() { + for (SimulationEvent simeEvent : scenario) { + System.out.println(simeEvent); + } } - } - public void simulate() { - for (SimulationEvent simeEvent : scenario) { - play(simeEvent, realCBTracker); - play(simeEvent, t_CBTracker); + void play(SimulationEvent simulationEvent, ComponentTracker> tracker) { + String key = simulationEvent.key; + long timestamp = simulationEvent.timestamp; + EventType eventType = simulationEvent.eventType; + switch (eventType) { + case INSERT: + tracker.getOrCreate(key, timestamp); + break; + case END_OF_LIFE: + tracker.endOfLife(key); + break; + case REMOVE_STALE: + tracker.removeStaleComponents(timestamp); + break; + } } - } - - // ========================================================================= - enum EventType { - INSERT, END_OF_LIFE, REMOVE_STALE; - } - - class SimulationEvent { - final public String key; - final public long timestamp; - final EventType eventType; - - public SimulationEvent(EventType eventType, String key, long timestamp) { - this.eventType = eventType; - this.key = key; - this.timestamp = timestamp; + + public void simulate() { + for (SimulationEvent simeEvent : scenario) { + play(simeEvent, realCBTracker); + play(simeEvent, t_CBTracker); + } + } + + // ========================================================================= + enum EventType { + INSERT, END_OF_LIFE, REMOVE_STALE; } - @Override - public String toString() { - return "SimulationEvent{" + - "eventType=" + eventType + - ", key='" + key + '\'' + - ", timestamp=" + timestamp + - '}'; + class SimulationEvent { + final public String key; + final public long timestamp; + final EventType eventType; + + public SimulationEvent(EventType eventType, String key, long timestamp) { + this.eventType = eventType; + this.key = key; + this.timestamp = timestamp; + } + + @Override + public String toString() { + return "SimulationEvent{" + "eventType=" + eventType + ", key='" + key + '\'' + ", timestamp=" + timestamp + '}'; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerT.java b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerT.java index 64223b63192136c1a1eb59cf0d40e27a58147cf0..8f05c946259682b9005653559efd2c5f2677e755 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerT.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerT.java @@ -25,222 +25,223 @@ import java.util.*; */ public class CyclicBufferTrackerT implements ComponentTracker> { - int bufferSize = CyclicBufferTracker.DEFAULT_BUFFER_SIZE; - int maxComponents = CyclicBufferTracker.DEFAULT_NUMBER_OF_BUFFERS; - - List> liveList = new LinkedList>(); - List> lingererList = new LinkedList>(); - - long lastCheck = 0; - - - private TEntry getEntry(List> list,String k) { - for (int i = 0; i < list.size(); i++) { - TEntry te = list.get(i); - if (te.key.equals(k)) { - return te; - } - } - return null; - } - - private TEntry getFromEitherList(String key) { - TEntry entry = getEntry(liveList, key); - if(entry != null) - return entry; - else { - return getEntry(lingererList, key); - } - } - - private List keysAsOrderedList(List> list) { - Collections.sort(list); - List result = new LinkedList(); - for (int i = 0; i < list.size(); i++) { - TEntry te = list.get(i); - result.add(te.key); - } - return result; - } - - List liveKeysAsOrderedList() { - return keysAsOrderedList(liveList); - } - List lingererKeysAsOrderedList() { - return keysAsOrderedList(lingererList); - } - - - public Set allKeys() { - HashSet allKeys = new HashSet(); - for (TEntry e : liveList) - allKeys.add(e.key); - for (TEntry e : lingererList) - allKeys.add(e.key); - return allKeys; - } - - - public Collection> allComponents() { - List> allComponents = new ArrayList>(); - for (TEntry e : liveList) - allComponents.add(e.value); - for (TEntry e : lingererList) - allComponents.add(e.value); - - return allComponents; - } - - public CyclicBuffer find(String key) { - TEntry te = getFromEitherList(key); - if(te == null) return null; - else return te.value; - } - - public CyclicBuffer getOrCreate(String key, long timestamp) { - TEntry te = getFromEitherList(key); - if (te == null) { - CyclicBuffer cb = new CyclicBuffer(bufferSize); - te = new TEntry(key, cb, timestamp); - liveList.add(te); - if (liveList.size() > maxComponents) { + int bufferSize = CyclicBufferTracker.DEFAULT_BUFFER_SIZE; + int maxComponents = CyclicBufferTracker.DEFAULT_NUMBER_OF_BUFFERS; + + List> liveList = new LinkedList>(); + List> lingererList = new LinkedList>(); + + long lastCheck = 0; + + private TEntry getEntry(List> list, String k) { + for (int i = 0; i < list.size(); i++) { + TEntry te = list.get(i); + if (te.key.equals(k)) { + return te; + } + } + return null; + } + + private TEntry getFromEitherList(String key) { + TEntry entry = getEntry(liveList, key); + if (entry != null) + return entry; + else { + return getEntry(lingererList, key); + } + } + + private List keysAsOrderedList(List> list) { + Collections.sort(list); + List result = new LinkedList(); + for (int i = 0; i < list.size(); i++) { + TEntry te = list.get(i); + result.add(te.key); + } + return result; + } + + List liveKeysAsOrderedList() { + return keysAsOrderedList(liveList); + } + + List lingererKeysAsOrderedList() { + return keysAsOrderedList(lingererList); + } + + public Set allKeys() { + HashSet allKeys = new HashSet(); + for (TEntry e : liveList) + allKeys.add(e.key); + for (TEntry e : lingererList) + allKeys.add(e.key); + return allKeys; + } + + public Collection> allComponents() { + List> allComponents = new ArrayList>(); + for (TEntry e : liveList) + allComponents.add(e.value); + for (TEntry e : lingererList) + allComponents.add(e.value); + + return allComponents; + } + + public CyclicBuffer find(String key) { + TEntry te = getFromEitherList(key); + if (te == null) + return null; + else + return te.value; + } + + public CyclicBuffer getOrCreate(String key, long timestamp) { + TEntry te = getFromEitherList(key); + if (te == null) { + CyclicBuffer cb = new CyclicBuffer(bufferSize); + te = new TEntry(key, cb, timestamp); + liveList.add(te); + if (liveList.size() > maxComponents) { + Collections.sort(liveList); + liveList.remove(0); + } + } else { + te.timestamp = timestamp; + Collections.sort(liveList); + } + return te.value; + } + + public void endOfLife(String k) { + TEntry te = null; + boolean found = false; + for (int i = 0; i < liveList.size(); i++) { + te = liveList.get(i); + if (te.key.equals(k)) { + liveList.remove(i); + found = true; + break; + } + } + if (found) { + lingererList.add(te); + } + } + + private boolean isEntryStale(TEntry entry, long now) { + return ((entry.timestamp + DEFAULT_TIMEOUT) < now); + } + + private boolean isEntryDoneLingering(TEntry tEntry, long now) { + return ((tEntry.timestamp + AbstractComponentTracker.LINGERING_TIMEOUT) < now); + } + + public void removeStaleComponents(long now) { + if (isTooSoonForRemovalIteration(now)) + return; + // both list should be sorted before removal attempts Collections.sort(liveList); - liveList.remove(0); - } - } else { - te.timestamp = timestamp; - Collections.sort(liveList); - } - return te.value; - } - - public void endOfLife(String k) { - TEntry te = null; - boolean found = false; - for (int i = 0; i < liveList.size(); i++) { - te = liveList.get(i); - if (te.key.equals(k)) { - liveList.remove(i); - found = true; - break; - } - } - if(found) { - lingererList.add(te); - } - } - - private boolean isEntryStale(TEntry entry, long now) { - return ((entry.timestamp + DEFAULT_TIMEOUT) < now); - } - private boolean isEntryDoneLingering(TEntry tEntry, long now) { - return ((tEntry.timestamp + AbstractComponentTracker.LINGERING_TIMEOUT) < now); - } - - public void removeStaleComponents(long now) { - if (isTooSoonForRemovalIteration(now)) return; - // both list should be sorted before removal attempts - Collections.sort(liveList); - Collections.sort(lingererList); - removeComponentsInExcessFromMainList(); - removeStaleComponentsFromMainList(now); - removeStaleComponentsFromLingerersList(now); - } - - private void removeComponentsInExcessFromMainList() { - while (liveList.size() > maxComponents) { - liveList.remove(0); - } - } - - private void removeStaleComponentsFromMainList(long now) { - while (liveList.size() != 0 && isEntryStale(liveList.get(0), now)) { - liveList.remove(0); - } - } - - private void removeStaleComponentsFromLingerersList(long now) { - while (lingererList.size() != 0 && isEntryDoneLingering(lingererList.get(0), now)) { - lingererList.remove(0); - } - } - - private boolean isTooSoonForRemovalIteration(long now) { - if (lastCheck + CoreConstants.MILLIS_IN_ONE_SECOND > now) { - return true; - } - lastCheck = now; - return false; - } - - public int getComponentCount() { - return liveList.size() + lingererList.size(); - } - - - // ================================================================== - - private class TEntry implements Comparable> { - - String key; - CyclicBuffer value; - long timestamp; - - TEntry(String k, CyclicBuffer v, long timestamp) { - this.key = k; - this.value = v; - this.timestamp = timestamp; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - public int compareTo(TEntry o) { - if (!(o instanceof TEntry)) { - throw new IllegalArgumentException("arguments must be of type " + TEntry.class); - } - - TEntry other = (TEntry) o; - if (timestamp > other.timestamp) { - return 1; - } - if (timestamp == other.timestamp) { - return 0; - } - return -1; + Collections.sort(lingererList); + removeComponentsInExcessFromMainList(); + removeStaleComponentsFromMainList(now); + removeStaleComponentsFromLingerersList(now); } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - @SuppressWarnings("unchecked") - final TEntry other = (TEntry) obj; - if (key == null) { - if (other.key != null) - return false; - } else if (!key.equals(other.key)) - return false; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) + + private void removeComponentsInExcessFromMainList() { + while (liveList.size() > maxComponents) { + liveList.remove(0); + } + } + + private void removeStaleComponentsFromMainList(long now) { + while (liveList.size() != 0 && isEntryStale(liveList.get(0), now)) { + liveList.remove(0); + } + } + + private void removeStaleComponentsFromLingerersList(long now) { + while (lingererList.size() != 0 && isEntryDoneLingering(lingererList.get(0), now)) { + lingererList.remove(0); + } + } + + private boolean isTooSoonForRemovalIteration(long now) { + if (lastCheck + CoreConstants.MILLIS_IN_ONE_SECOND > now) { + return true; + } + lastCheck = now; return false; - return true; } - @Override - public String toString() { - return "(" + key + ", " + value + ")"; + public int getComponentCount() { + return liveList.size() + lingererList.size(); + } + + // ================================================================== + + private class TEntry implements Comparable> { + + String key; + CyclicBuffer value; + long timestamp; + + TEntry(String k, CyclicBuffer v, long timestamp) { + this.key = k; + this.value = v; + this.timestamp = timestamp; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + public int compareTo(TEntry o) { + if (!(o instanceof TEntry)) { + throw new IllegalArgumentException("arguments must be of type " + TEntry.class); + } + + TEntry other = (TEntry) o; + if (timestamp > other.timestamp) { + return 1; + } + if (timestamp == other.timestamp) { + return 0; + } + return -1; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + @SuppressWarnings("unchecked") + final TEntry other = (TEntry) obj; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + if (value == null) { + if (other.value != null) + return false; + } else if (!value.equals(other.value)) + return false; + return true; + } + + @Override + public String toString() { + return "(" + key + ", " + value + ")"; + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerTest.java b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerTest.java index eb9eb47278f920bd84fd1e82cf2702d7b0f78cb2..c5d4785abee41567b9dae320313d2c8b28d65378 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/CyclicBufferTrackerTest.java @@ -24,56 +24,52 @@ import static junit.framework.Assert.assertNotNull; */ public class CyclicBufferTrackerTest { + CyclicBufferTracker tracker = new CyclicBufferTracker(); + String key = "a"; - CyclicBufferTracker tracker = new CyclicBufferTracker(); - String key = "a"; + @Test + public void empty0() { + long now = 3000; + tracker.removeStaleComponents(now); + assertEquals(0, tracker.liveKeysAsOrderedList().size()); + assertEquals(0, tracker.getComponentCount()); + } - @Test - public void empty0() { - long now = 3000; - tracker.removeStaleComponents(now); - assertEquals(0, tracker.liveKeysAsOrderedList().size()); - assertEquals(0, tracker.getComponentCount()); - } - - @Test - public void empty1() { - long now = 3000; - assertNotNull(tracker.getOrCreate(key, now++)); - now += ComponentTracker.DEFAULT_TIMEOUT + 1000; - tracker.removeStaleComponents(now); - assertEquals(0, tracker.liveKeysAsOrderedList().size()); - assertEquals(0, tracker.getComponentCount()); - - assertNotNull(tracker.getOrCreate(key, now++)); - } - - @Test - public void smoke() { - long now = 3000; - CyclicBuffer cb = tracker.getOrCreate(key, now); - assertEquals(cb, tracker.getOrCreate(key, now++)); - now += CyclicBufferTracker.DEFAULT_TIMEOUT + 1000; - tracker.removeStaleComponents(now); - assertEquals(0, tracker.liveKeysAsOrderedList().size()); - assertEquals(0, tracker.getComponentCount()); - } - - @Test - public void destroy() { - long now = 3000; - CyclicBuffer cb = tracker.getOrCreate(key, now); - cb.add(new Object()); - assertEquals(1, cb.length()); - tracker.endOfLife(key); - now += CyclicBufferTracker.LINGERING_TIMEOUT + 10; - tracker.removeStaleComponents(now); - assertEquals(0, tracker.liveKeysAsOrderedList().size()); - assertEquals(0, tracker.getComponentCount()); - assertEquals(0, cb.length()); - } + @Test + public void empty1() { + long now = 3000; + assertNotNull(tracker.getOrCreate(key, now++)); + now += ComponentTracker.DEFAULT_TIMEOUT + 1000; + tracker.removeStaleComponents(now); + assertEquals(0, tracker.liveKeysAsOrderedList().size()); + assertEquals(0, tracker.getComponentCount()); + assertNotNull(tracker.getOrCreate(key, now++)); + } + @Test + public void smoke() { + long now = 3000; + CyclicBuffer cb = tracker.getOrCreate(key, now); + assertEquals(cb, tracker.getOrCreate(key, now++)); + now += CyclicBufferTracker.DEFAULT_TIMEOUT + 1000; + tracker.removeStaleComponents(now); + assertEquals(0, tracker.liveKeysAsOrderedList().size()); + assertEquals(0, tracker.getComponentCount()); + } + @Test + public void destroy() { + long now = 3000; + CyclicBuffer cb = tracker.getOrCreate(key, now); + cb.add(new Object()); + assertEquals(1, cb.length()); + tracker.endOfLife(key); + now += CyclicBufferTracker.LINGERING_TIMEOUT + 10; + tracker.removeStaleComponents(now); + assertEquals(0, tracker.liveKeysAsOrderedList().size()); + assertEquals(0, tracker.getComponentCount()); + assertEquals(0, cb.length()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/spi/PackageTest.java index 588e2c2bcad2b675b98315d24daed248bc6cd1f4..4cd173cefc07cca3c1003f82f788e10f8fb855fb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/PackageTest.java @@ -16,10 +16,8 @@ package ch.qos.logback.core.spi; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({AppenderAttachableImplTest.class, AppenderAttachableImplLockTest.class, - CyclicBufferTrackerTest.class, ScenarioBasedCyclicBufferTrackerTest.class}) - +@Suite.SuiteClasses({ AppenderAttachableImplTest.class, AppenderAttachableImplLockTest.class, CyclicBufferTrackerTest.class, + ScenarioBasedCyclicBufferTrackerTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/spi/ScenarioBasedCyclicBufferTrackerTest.java b/logback-core/src/test/java/ch/qos/logback/core/spi/ScenarioBasedCyclicBufferTrackerTest.java index da80b57b1236b2243687b35317a40872600da171..692c01949a79f581af51757f599fbd5c660b8e66 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/spi/ScenarioBasedCyclicBufferTrackerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/spi/ScenarioBasedCyclicBufferTrackerTest.java @@ -25,49 +25,50 @@ import static junit.framework.Assert.assertEquals; */ public class ScenarioBasedCyclicBufferTrackerTest { - CyclicBufferTrackerSimulator simulator; - CyclicBufferTrackerSimulator.Parameters parameters = new CyclicBufferTrackerSimulator.Parameters(); + CyclicBufferTrackerSimulator simulator; + CyclicBufferTrackerSimulator.Parameters parameters = new CyclicBufferTrackerSimulator.Parameters(); - void verify() { - CyclicBufferTracker at = simulator.realCBTracker; - CyclicBufferTrackerT t_at = simulator.t_CBTracker; - assertEquals(t_at.liveKeysAsOrderedList(), at.liveKeysAsOrderedList()); - assertEquals(t_at.lingererKeysAsOrderedList(), at.lingererKeysAsOrderedList()); - } + void verify() { + CyclicBufferTracker at = simulator.realCBTracker; + CyclicBufferTrackerT t_at = simulator.t_CBTracker; + assertEquals(t_at.liveKeysAsOrderedList(), at.liveKeysAsOrderedList()); + assertEquals(t_at.lingererKeysAsOrderedList(), at.lingererKeysAsOrderedList()); + } - @Before public void setUp() { - parameters.keySpaceLen = 128; - parameters.maxTimestampInc = ComponentTracker.DEFAULT_TIMEOUT / 2; - } + @Before + public void setUp() { + parameters.keySpaceLen = 128; + parameters.maxTimestampInc = ComponentTracker.DEFAULT_TIMEOUT / 2; + } - @Test - public void shortTest() { - parameters.keySpaceLen = 64; - parameters.maxTimestampInc = 500; - parameters.simulationLength = 70; + @Test + public void shortTest() { + parameters.keySpaceLen = 64; + parameters.maxTimestampInc = 500; + parameters.simulationLength = 70; - simulator = new CyclicBufferTrackerSimulator(parameters); - simulator.buildScenario(); - simulator.simulate(); - verify(); - } + simulator = new CyclicBufferTrackerSimulator(parameters); + simulator.buildScenario(); + simulator.simulate(); + verify(); + } - @Test - public void mediumTest() { - parameters.simulationLength = 20000; + @Test + public void mediumTest() { + parameters.simulationLength = 20000; - simulator = new CyclicBufferTrackerSimulator(parameters); - simulator.buildScenario(); - simulator.simulate(); - verify(); - } + simulator = new CyclicBufferTrackerSimulator(parameters); + simulator.buildScenario(); + simulator.simulate(); + verify(); + } - @Test - public void longTest() { - parameters.simulationLength = 100*1000; - simulator = new CyclicBufferTrackerSimulator(parameters); - simulator.buildScenario(); - simulator.simulate(); - verify(); - } + @Test + public void longTest() { + parameters.simulationLength = 100 * 1000; + simulator = new CyclicBufferTrackerSimulator(parameters); + simulator.buildScenario(); + simulator.simulate(); + verify(); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/status/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/status/PackageTest.java index 25147c5eb778b4ef4e72fb7e13fd289b1065ca03..e54d9b09b5e4b409c84e03d3ef8dd6348e21d8c0 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/status/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/status/PackageTest.java @@ -16,9 +16,7 @@ package ch.qos.logback.core.status; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({StatusBaseTest.class, StatusUtilTest.class}) - +@Suite.SuiteClasses({ StatusBaseTest.class, StatusUtilTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/status/StatusBaseTest.java b/logback-core/src/test/java/ch/qos/logback/core/status/StatusBaseTest.java index ad73dbc3a9c0f6f3265cbbc2e1842c48fc59500f..6edc198be7a8c38545093c1bbdd81d43a9eab5cb 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/status/StatusBaseTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/status/StatusBaseTest.java @@ -19,75 +19,70 @@ import junit.framework.TestCase; public class StatusBaseTest extends TestCase { - public void testAddStatus() { - { - InfoStatus status = new InfoStatus("testing", this); - status.add(new ErrorStatus("error", this)); - Iterator it = status.iterator(); - assertTrue("No status was added", it.hasNext()); - assertTrue("hasChilden method reported wrong result", status - .hasChildren()); + public void testAddStatus() { + { + InfoStatus status = new InfoStatus("testing", this); + status.add(new ErrorStatus("error", this)); + Iterator it = status.iterator(); + assertTrue("No status was added", it.hasNext()); + assertTrue("hasChilden method reported wrong result", status.hasChildren()); + } + { + InfoStatus status = new InfoStatus("testing", this); + try { + status.add(null); + fail("method should have thrown an Exception"); + } catch (NullPointerException ex) { + } + } } - { - InfoStatus status = new InfoStatus("testing", this); - try { - status.add(null); - fail("method should have thrown an Exception"); - } catch (NullPointerException ex) { - } - } - } - public void testRemoveStatus() { - { - InfoStatus status = new InfoStatus("testing", this); - ErrorStatus error = new ErrorStatus("error", this); - status.add(error); - boolean result = status.remove(error); - Iterator it = status.iterator(); - assertTrue("Remove failed", result); - assertFalse("No status was removed", it.hasNext()); - assertFalse("hasChilden method reported wrong result", status - .hasChildren()); - } - { - InfoStatus status = new InfoStatus("testing", this); - ErrorStatus error = new ErrorStatus("error", this); - status.add(error); - boolean result = status.remove(null); - assertFalse("Remove result was not false", result); + public void testRemoveStatus() { + { + InfoStatus status = new InfoStatus("testing", this); + ErrorStatus error = new ErrorStatus("error", this); + status.add(error); + boolean result = status.remove(error); + Iterator it = status.iterator(); + assertTrue("Remove failed", result); + assertFalse("No status was removed", it.hasNext()); + assertFalse("hasChilden method reported wrong result", status.hasChildren()); + } + { + InfoStatus status = new InfoStatus("testing", this); + ErrorStatus error = new ErrorStatus("error", this); + status.add(error); + boolean result = status.remove(null); + assertFalse("Remove result was not false", result); + } } - } - public void testEffectiveLevel() { - { - // effective level = 0 level deep - ErrorStatus status = new ErrorStatus("error", this); - WarnStatus warn = new WarnStatus("warning", this); - status.add(warn); - assertEquals("effective level misevaluated", status.getEffectiveLevel(), - Status.ERROR); - } + public void testEffectiveLevel() { + { + // effective level = 0 level deep + ErrorStatus status = new ErrorStatus("error", this); + WarnStatus warn = new WarnStatus("warning", this); + status.add(warn); + assertEquals("effective level misevaluated", status.getEffectiveLevel(), Status.ERROR); + } - { - // effective level = 1 level deep - InfoStatus status = new InfoStatus("info", this); - WarnStatus warn = new WarnStatus("warning", this); - status.add(warn); - assertEquals("effective level misevaluated", status.getEffectiveLevel(), - Status.WARN); - } + { + // effective level = 1 level deep + InfoStatus status = new InfoStatus("info", this); + WarnStatus warn = new WarnStatus("warning", this); + status.add(warn); + assertEquals("effective level misevaluated", status.getEffectiveLevel(), Status.WARN); + } - { - // effective level = 2 levels deep - InfoStatus status = new InfoStatus("info", this); - WarnStatus warn = new WarnStatus("warning", this); - ErrorStatus error = new ErrorStatus("error", this); - status.add(warn); - warn.add(error); - assertEquals("effective level misevaluated", status.getEffectiveLevel(), - Status.ERROR); + { + // effective level = 2 levels deep + InfoStatus status = new InfoStatus("info", this); + WarnStatus warn = new WarnStatus("warning", this); + ErrorStatus error = new ErrorStatus("error", this); + status.add(warn); + warn.add(error); + assertEquals("effective level misevaluated", status.getEffectiveLevel(), Status.ERROR); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/status/StatusChecker.java b/logback-core/src/test/java/ch/qos/logback/core/status/StatusChecker.java index b3d1233ab7694b22631a41b06ec94cfaab33458c..ba9b1411370b018dc62c66535f649646986dea21 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/status/StatusChecker.java +++ b/logback-core/src/test/java/ch/qos/logback/core/status/StatusChecker.java @@ -22,29 +22,28 @@ import static org.junit.Assert.assertTrue; */ public class StatusChecker extends StatusUtil { - public StatusChecker(StatusManager sm) { - super(sm); - } + public StatusChecker(StatusManager sm) { + super(sm); + } - public StatusChecker(Context context) { - super(context); - } + public StatusChecker(Context context) { + super(context); + } - public void assertContainsMatch(int level, String regex) { - assertTrue(containsMatch(level, regex)); - } + public void assertContainsMatch(int level, String regex) { + assertTrue(containsMatch(level, regex)); + } - public void assertContainsMatch(String regex) { - assertTrue(containsMatch(regex)); - } + public void assertContainsMatch(String regex) { + assertTrue(containsMatch(regex)); + } - public void asssertContainsException(Class scanExceptionClass) { - assertTrue(containsException(scanExceptionClass)); - } - - public void assertIsErrorFree() { - assertTrue(isErrorFree(0)); - } + public void asssertContainsException(Class scanExceptionClass) { + assertTrue(containsException(scanExceptionClass)); + } + public void assertIsErrorFree() { + assertTrue(isErrorFree(0)); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/status/StatusUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/status/StatusUtilTest.java index db5f406aa5924825931f39588d8b8ded85ec422d..85109507d4f8d6d31c24768fb28e27f4196d183b 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/status/StatusUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/status/StatusUtilTest.java @@ -26,28 +26,27 @@ import static org.junit.Assert.assertTrue; */ public class StatusUtilTest { - Context context = new ContextBase(); - StatusUtil statusUtil = new StatusUtil(context); - - @Test - public void emptyStatusListShouldResultInNotFound() { - assertEquals(-1, statusUtil.timeOfLastReset()); - } - - @Test - public void withoutResetsStatusUtilShouldReturnNotFound() { - context.getStatusManager().add(new InfoStatus("test", this)); - assertEquals(-1, statusUtil.timeOfLastReset()); - } - - @Test - public void statusListShouldReturnLastResetTime() { - context.getStatusManager().add(new InfoStatus("test", this)); - long resetTime = System.currentTimeMillis(); - context.getStatusManager().add(new InfoStatus(CoreConstants.RESET_MSG_PREFIX, this)); - context.getStatusManager().add(new InfoStatus("bla", this)); - assertTrue(resetTime <= statusUtil.timeOfLastReset()); - } - + Context context = new ContextBase(); + StatusUtil statusUtil = new StatusUtil(context); + + @Test + public void emptyStatusListShouldResultInNotFound() { + assertEquals(-1, statusUtil.timeOfLastReset()); + } + + @Test + public void withoutResetsStatusUtilShouldReturnNotFound() { + context.getStatusManager().add(new InfoStatus("test", this)); + assertEquals(-1, statusUtil.timeOfLastReset()); + } + + @Test + public void statusListShouldReturnLastResetTime() { + context.getStatusManager().add(new InfoStatus("test", this)); + long resetTime = System.currentTimeMillis(); + context.getStatusManager().add(new InfoStatus(CoreConstants.RESET_MSG_PREFIX, this)); + context.getStatusManager().add(new InfoStatus("bla", this)); + assertTrue(resetTime <= statusUtil.timeOfLastReset()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/status/TrivialStatusListener.java b/logback-core/src/test/java/ch/qos/logback/core/status/TrivialStatusListener.java index 1151395bfb9b2f3d05d690594d24586b6583dc41..607bc02120a1a78fd1832338e12e36e8da7aaad6 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/status/TrivialStatusListener.java +++ b/logback-core/src/test/java/ch/qos/logback/core/status/TrivialStatusListener.java @@ -22,24 +22,24 @@ import ch.qos.logback.core.status.StatusListener; public class TrivialStatusListener implements StatusListener, LifeCycle { - public List list = new ArrayList(); - boolean start = false; - - public void addStatusEvent(Status status) { - if(!isStarted()) - return; - list.add(status); - } - - public void start() { - start = true; - } - - public void stop() { - start = false; - } - - public boolean isStarted() { - return start; - } + public List list = new ArrayList(); + boolean start = false; + + public void addStatusEvent(Status status) { + if (!isStarted()) + return; + list.add(status); + } + + public void start() { + start = true; + } + + public void stop() { + start = false; + } + + public boolean isStarted() { + return start; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/subst/NodeToStringTransformerTest.java b/logback-core/src/test/java/ch/qos/logback/core/subst/NodeToStringTransformerTest.java index d6ad47e05bf0fa09569d8e0054a87649e0bcb95c..04ff7e5f6d3537f86255ad2325e025d6982bc197 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/subst/NodeToStringTransformerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/subst/NodeToStringTransformerTest.java @@ -25,112 +25,108 @@ import static org.junit.Assert.assertEquals; */ public class NodeToStringTransformerTest { - ContextBase propertyContainer0 = new ContextBase(); - - - @Before - public void setUp() { - propertyContainer0.putProperty("k0", "v0"); - propertyContainer0.putProperty("zero", "0"); - propertyContainer0.putProperty("v0.jdbc.url", "http://.."); - propertyContainer0.putProperty("host", "local"); - - } - - private Node makeNode(String input) throws ScanException { - Tokenizer tokenizer = new Tokenizer(input); - Parser parser = new Parser(tokenizer.tokenize()); - return parser.parse(); - } - - @Test - public void literal() throws ScanException { - String input = "abv"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals(input, nodeToStringTransformer.transform()); - } - - - void checkInputEqualsOutput(String input) throws ScanException { - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals(input, nodeToStringTransformer.transform()); - } - - @Test - public void literalWithNestedAccolades() throws ScanException { - checkInputEqualsOutput("%logger{35}"); - checkInputEqualsOutput("%a{35} %b{35} c"); - checkInputEqualsOutput("%replace(%msg){'\\d{14,16}', 'XXXX'}"); - checkInputEqualsOutput("TEST %d{HHmmssSSS} [%thread] %-5level %logger{36} - %msg%n"); - } - - - @Test - public void variable() throws ScanException { - String input = "${k0}"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("v0", nodeToStringTransformer.transform()); - } - - @Test - public void literalVariableLiteral() throws ScanException { - String input = "a${k0}c"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("av0c", nodeToStringTransformer.transform()); - } - - @Test - public void nestedVariable() throws ScanException { - String input = "a${k${zero}}b"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("av0b", nodeToStringTransformer.transform()); - } - - @Test - public void LOGBACK729() throws ScanException { - String input = "${${k0}.jdbc.url}"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("http://..", nodeToStringTransformer.transform()); - } - - @Test - public void LOGBACK744_withColon() throws ScanException { - String input = "%d{HH:mm:ss.SSS} host:${host} %logger{36} - %msg%n"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - System.out.println(nodeToStringTransformer.transform()); - assertEquals("%d{HH:mm:ss.SSS} host:local %logger{36} - %msg%n", nodeToStringTransformer.transform()); - } - - @Test - public void loneColonShouldReadLikeAnyOtherCharacter() throws ScanException { - String input = "java:comp/env/jdbc/datasource"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals(input, nodeToStringTransformer.transform()); - } - - @Test - public void withDefaultValue() throws ScanException { - String input = "${k67:-b}c"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("bc", nodeToStringTransformer.transform()); - } - - @Test - public void defaultValueNestedAsVar() throws ScanException { - String input = "a${k67:-x${k0}}c"; - Node node = makeNode(input); - NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); - assertEquals("axv0c", nodeToStringTransformer.transform()); - } - + ContextBase propertyContainer0 = new ContextBase(); + + @Before + public void setUp() { + propertyContainer0.putProperty("k0", "v0"); + propertyContainer0.putProperty("zero", "0"); + propertyContainer0.putProperty("v0.jdbc.url", "http://.."); + propertyContainer0.putProperty("host", "local"); + + } + + private Node makeNode(String input) throws ScanException { + Tokenizer tokenizer = new Tokenizer(input); + Parser parser = new Parser(tokenizer.tokenize()); + return parser.parse(); + } + + @Test + public void literal() throws ScanException { + String input = "abv"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals(input, nodeToStringTransformer.transform()); + } + + void checkInputEqualsOutput(String input) throws ScanException { + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals(input, nodeToStringTransformer.transform()); + } + + @Test + public void literalWithNestedAccolades() throws ScanException { + checkInputEqualsOutput("%logger{35}"); + checkInputEqualsOutput("%a{35} %b{35} c"); + checkInputEqualsOutput("%replace(%msg){'\\d{14,16}', 'XXXX'}"); + checkInputEqualsOutput("TEST %d{HHmmssSSS} [%thread] %-5level %logger{36} - %msg%n"); + } + + @Test + public void variable() throws ScanException { + String input = "${k0}"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("v0", nodeToStringTransformer.transform()); + } + + @Test + public void literalVariableLiteral() throws ScanException { + String input = "a${k0}c"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("av0c", nodeToStringTransformer.transform()); + } + + @Test + public void nestedVariable() throws ScanException { + String input = "a${k${zero}}b"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("av0b", nodeToStringTransformer.transform()); + } + + @Test + public void LOGBACK729() throws ScanException { + String input = "${${k0}.jdbc.url}"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("http://..", nodeToStringTransformer.transform()); + } + + @Test + public void LOGBACK744_withColon() throws ScanException { + String input = "%d{HH:mm:ss.SSS} host:${host} %logger{36} - %msg%n"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + System.out.println(nodeToStringTransformer.transform()); + assertEquals("%d{HH:mm:ss.SSS} host:local %logger{36} - %msg%n", nodeToStringTransformer.transform()); + } + + @Test + public void loneColonShouldReadLikeAnyOtherCharacter() throws ScanException { + String input = "java:comp/env/jdbc/datasource"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals(input, nodeToStringTransformer.transform()); + } + + @Test + public void withDefaultValue() throws ScanException { + String input = "${k67:-b}c"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("bc", nodeToStringTransformer.transform()); + } + + @Test + public void defaultValueNestedAsVar() throws ScanException { + String input = "a${k67:-x${k0}}c"; + Node node = makeNode(input); + NodeToStringTransformer nodeToStringTransformer = new NodeToStringTransformer(node, propertyContainer0); + assertEquals("axv0c", nodeToStringTransformer.transform()); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/subst/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/subst/PackageTest.java index 4b163e5e468d649dd5d871232bc9dcf0ea2f6f30..f50df44a39d497c5d6bba59e95d4e62383183de6 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/subst/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/subst/PackageTest.java @@ -16,9 +16,7 @@ package ch.qos.logback.core.subst; import org.junit.runner.RunWith; import org.junit.runners.Suite; - @RunWith(Suite.class) -@Suite.SuiteClasses({TokenizerTest.class, ParserTest.class, NodeToStringTransformerTest.class}) - +@Suite.SuiteClasses({ TokenizerTest.class, ParserTest.class, NodeToStringTransformerTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/subst/ParserTest.java b/logback-core/src/test/java/ch/qos/logback/core/subst/ParserTest.java index 4ab34324b740b3ecb9269b5915facff889873e4c..cbfbf1f9d73ad1993b32a21355026127ef367dd8 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/subst/ParserTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/subst/ParserTest.java @@ -30,170 +30,166 @@ import ch.qos.logback.core.spi.ScanException; */ public class ParserTest { + @Test + public void literal() throws ScanException { + Tokenizer tokenizer = new Tokenizer("abc"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "abc"); + assertEquals(witness, node); + } + + @Test + public void literalWithAccolade0() throws ScanException { + Tokenizer tokenizer = new Tokenizer("{}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "{"); + witness.next = new Node(Node.Type.LITERAL, "}"); + assertEquals(witness, node); + } + + @Test + public void literalWithAccolade1() throws ScanException { + Tokenizer tokenizer = new Tokenizer("%x{a}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "%x"); + Node t = witness.next = new Node(Node.Type.LITERAL, "{"); + t.next = new Node(Node.Type.LITERAL, "a"); + t = t.next; + t.next = new Node(Node.Type.LITERAL, "}"); + assertEquals(witness, node); + } + + @Test + public void literalWithTwoAccolades() throws ScanException { + Tokenizer tokenizer = new Tokenizer("%x{y} %a{b} c"); + + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "%x"); + + Node t = witness.next = new Node(Node.Type.LITERAL, "{"); + t.next = new Node(Node.Type.LITERAL, "y"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "}"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, " %a"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "{"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "b"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "}"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, " c"); + + node.dump(); + System.out.println(""); + assertEquals(witness, node); + } + + @Test + public void variable() throws ScanException { + Tokenizer tokenizer = new Tokenizer("${abc}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "abc")); + assertEquals(witness, node); + } + + @Test + public void literalVariableLiteral() throws ScanException { + Tokenizer tokenizer = new Tokenizer("a${b}c"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "a"); + witness.next = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); + witness.next.next = new Node(Node.Type.LITERAL, "c"); + assertEquals(witness, node); + } + + // /LOGBACK-744 + @Test + public void withColon() throws ScanException { + Tokenizer tokenizer = new Tokenizer("a:${b}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "a"); + Node t = witness.next = new Node(Node.Type.LITERAL, ":"); + t.next = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); + assertEquals(witness, node); + } - @Test - public void literal() throws ScanException { - Tokenizer tokenizer = new Tokenizer("abc"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "abc"); - assertEquals(witness, node); - } - - @Test - public void literalWithAccolade0() throws ScanException { - Tokenizer tokenizer = new Tokenizer("{}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "{"); - witness.next = new Node(Node.Type.LITERAL, "}"); - assertEquals(witness, node); - } - - @Test - public void literalWithAccolade1() throws ScanException { - Tokenizer tokenizer = new Tokenizer("%x{a}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "%x"); - Node t = witness.next = new Node(Node.Type.LITERAL, "{"); - t.next = new Node(Node.Type.LITERAL, "a"); - t = t.next; - t.next = new Node(Node.Type.LITERAL, "}"); - assertEquals(witness, node); - } - - @Test - public void literalWithTwoAccolades() throws ScanException { - Tokenizer tokenizer = new Tokenizer("%x{y} %a{b} c"); - - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "%x"); - - Node t = witness.next = new Node(Node.Type.LITERAL, "{"); - t.next = new Node(Node.Type.LITERAL, "y"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "}"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, " %a"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "{"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "b"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "}"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, " c"); - - node.dump(); - System.out.println(""); - assertEquals(witness, node); - } - - @Test - public void variable() throws ScanException { - Tokenizer tokenizer = new Tokenizer("${abc}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "abc")); - assertEquals(witness, node); - } - - @Test - public void literalVariableLiteral() throws ScanException { - Tokenizer tokenizer = new Tokenizer("a${b}c"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "a"); - witness.next = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); - witness.next.next = new Node(Node.Type.LITERAL, "c"); - assertEquals(witness, node); - } - - - // /LOGBACK-744 - @Test - public void withColon() throws ScanException { - Tokenizer tokenizer = new Tokenizer("a:${b}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "a"); - Node t = witness.next = new Node(Node.Type.LITERAL, ":"); - t.next = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); - assertEquals(witness, node); - } - - @Test - public void nested() throws ScanException { - Tokenizer tokenizer = new Tokenizer("a${b${c}}d"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.LITERAL, "a"); - Node bLiteralNode = new Node(Node.Type.LITERAL, "b"); - Node cLiteralNode = new Node(Node.Type.LITERAL, "c"); - Node bVariableNode = new Node(Node.Type.VARIABLE, bLiteralNode); - Node cVariableNode = new Node(Node.Type.VARIABLE, cLiteralNode); - bLiteralNode.next = cVariableNode; - - witness.next = bVariableNode; - witness.next.next = new Node(Node.Type.LITERAL, "d"); - assertEquals(witness, node); - } - - @Test - public void withDefault() throws ScanException { - Tokenizer tokenizer = new Tokenizer("${b:-c}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); - witness.defaultPart = new Node(Node.Type.LITERAL, "c"); - assertEquals(witness, node); - } - - @Test - public void defaultSeparatorOutsideOfAVariable() throws ScanException { - Tokenizer tokenizer = new Tokenizer("{a:-b}"); - Parser parser = new Parser(tokenizer.tokenize()); - Node node = parser.parse(); - - dump(node); - Node witness = new Node(Node.Type.LITERAL, "{"); - Node t = witness.next = new Node(Node.Type.LITERAL, "a"); - - - t.next = new Node(Node.Type.LITERAL, ":-"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "b"); - t = t.next; - - t.next = new Node(Node.Type.LITERAL, "}"); - - assertEquals(witness, node); - } - - @Test - public void emptyTokenListDoesNotThrowNullPointerException() throws ScanException { - // An empty token list would be returned from Tokenizer.tokenize() - // if it were constructed with an empty string. The parser should - // be able to handle this. - Parser parser = new Parser(new ArrayList()); - parser.parse(); - } - - private void dump(Node node) { - while (node != null) { - System.out.println(node.toString()); - node = node.next; + @Test + public void nested() throws ScanException { + Tokenizer tokenizer = new Tokenizer("a${b${c}}d"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.LITERAL, "a"); + Node bLiteralNode = new Node(Node.Type.LITERAL, "b"); + Node cLiteralNode = new Node(Node.Type.LITERAL, "c"); + Node bVariableNode = new Node(Node.Type.VARIABLE, bLiteralNode); + Node cVariableNode = new Node(Node.Type.VARIABLE, cLiteralNode); + bLiteralNode.next = cVariableNode; + + witness.next = bVariableNode; + witness.next.next = new Node(Node.Type.LITERAL, "d"); + assertEquals(witness, node); } - } + @Test + public void withDefault() throws ScanException { + Tokenizer tokenizer = new Tokenizer("${b:-c}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b")); + witness.defaultPart = new Node(Node.Type.LITERAL, "c"); + assertEquals(witness, node); + } + + @Test + public void defaultSeparatorOutsideOfAVariable() throws ScanException { + Tokenizer tokenizer = new Tokenizer("{a:-b}"); + Parser parser = new Parser(tokenizer.tokenize()); + Node node = parser.parse(); + + dump(node); + Node witness = new Node(Node.Type.LITERAL, "{"); + Node t = witness.next = new Node(Node.Type.LITERAL, "a"); + + t.next = new Node(Node.Type.LITERAL, ":-"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "b"); + t = t.next; + + t.next = new Node(Node.Type.LITERAL, "}"); + + assertEquals(witness, node); + } + + @Test + public void emptyTokenListDoesNotThrowNullPointerException() throws ScanException { + // An empty token list would be returned from Tokenizer.tokenize() + // if it were constructed with an empty string. The parser should + // be able to handle this. + Parser parser = new Parser(new ArrayList()); + parser.parse(); + } + + private void dump(Node node) { + while (node != null) { + System.out.println(node.toString()); + node = node.next; + } + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/subst/TokenizerTest.java b/logback-core/src/test/java/ch/qos/logback/core/subst/TokenizerTest.java index c6751ad54b7296f1352d6620008b2ee9aefebbc4..43e5f8d4b48bee44740689d24a24b065e3cc5986 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/subst/TokenizerTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/subst/TokenizerTest.java @@ -23,126 +23,122 @@ import static org.junit.Assert.assertEquals; public class TokenizerTest { - List witnessList = new ArrayList(); - - @Test - public void literalOnly() throws ScanException { - String input = "abc"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, input)); - assertEquals(witnessList, tokenList); - } - - @Test - public void literalWithAccolades() throws ScanException { - String input0 = "%logger"; - String input1 = "24"; - String input2 = " - %m"; - String input = input0+"{"+input1+"}"+input2; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, input0)); - witnessList.add(Token.CURLY_LEFT_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, input1)); - - witnessList.add(Token.CURLY_RIGHT_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, input2)); - assertEquals(witnessList, tokenList); - } - - - @Test - public void simleVariable() throws ScanException { - String input = "${abc}"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "abc")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - assertEquals(witnessList, tokenList); - } - - @Test - public void mix() throws ScanException { - String input = "a${b}c"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "b")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "c")); - assertEquals(witnessList, tokenList); - } - - @Test - public void nested() throws ScanException { - String input = "a${b${c}}"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "b")); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "c")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - assertEquals(witnessList, tokenList); - } - - - @Test - public void basicDefaultSeparator() throws ScanException { - String input = "${a:-b}"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(Token.DEFAULT_SEP_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "b")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - assertEquals(witnessList, tokenList); - } - - @Test - public void colon() throws ScanException { - String input = "a:b"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(new Token(Token.Type.LITERAL, ":b")); - assertEquals(witnessList, tokenList); - } - - - // /LOGBACK-744 - @Test - public void colonFollowedByDollar() throws ScanException { - String input = "a:${b}"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(new Token(Token.Type.LITERAL, ":")); - witnessList.add(Token.START_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "b")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - assertEquals(witnessList, tokenList); - } - - @Test - public void defaultSeparatorOutsideVariable() throws ScanException { - - String input = "{a:-b}"; - Tokenizer tokenizer = new Tokenizer(input); - List tokenList = tokenizer.tokenize(); - witnessList.add(Token.CURLY_LEFT_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "a")); - witnessList.add(Token.DEFAULT_SEP_TOKEN); - witnessList.add(new Token(Token.Type.LITERAL, "b")); - witnessList.add(Token.CURLY_RIGHT_TOKEN); - assertEquals(witnessList, tokenList); - } - - - } + List witnessList = new ArrayList(); + + @Test + public void literalOnly() throws ScanException { + String input = "abc"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, input)); + assertEquals(witnessList, tokenList); + } + + @Test + public void literalWithAccolades() throws ScanException { + String input0 = "%logger"; + String input1 = "24"; + String input2 = " - %m"; + String input = input0 + "{" + input1 + "}" + input2; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, input0)); + witnessList.add(Token.CURLY_LEFT_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, input1)); + + witnessList.add(Token.CURLY_RIGHT_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, input2)); + assertEquals(witnessList, tokenList); + } + + @Test + public void simleVariable() throws ScanException { + String input = "${abc}"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "abc")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + assertEquals(witnessList, tokenList); + } + + @Test + public void mix() throws ScanException { + String input = "a${b}c"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "b")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "c")); + assertEquals(witnessList, tokenList); + } + + @Test + public void nested() throws ScanException { + String input = "a${b${c}}"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "b")); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "c")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + assertEquals(witnessList, tokenList); + } + + @Test + public void basicDefaultSeparator() throws ScanException { + String input = "${a:-b}"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(Token.DEFAULT_SEP_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "b")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + assertEquals(witnessList, tokenList); + } + + @Test + public void colon() throws ScanException { + String input = "a:b"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(new Token(Token.Type.LITERAL, ":b")); + assertEquals(witnessList, tokenList); + } + + // /LOGBACK-744 + @Test + public void colonFollowedByDollar() throws ScanException { + String input = "a:${b}"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(new Token(Token.Type.LITERAL, ":")); + witnessList.add(Token.START_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "b")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + assertEquals(witnessList, tokenList); + } + + @Test + public void defaultSeparatorOutsideVariable() throws ScanException { + + String input = "{a:-b}"; + Tokenizer tokenizer = new Tokenizer(input); + List tokenList = tokenizer.tokenize(); + witnessList.add(Token.CURLY_LEFT_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "a")); + witnessList.add(Token.DEFAULT_SEP_TOKEN); + witnessList.add(new Token(Token.Type.LITERAL, "b")); + witnessList.add(Token.CURLY_RIGHT_TOKEN); + assertEquals(witnessList, tokenList); + } + +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/DelayingListAppender.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/DelayingListAppender.java index 4c24a206f51e4929feb8b10b48ce57c493684161..a60463bace805032c4c073b344daaf6a7d10e61b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/DelayingListAppender.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/DelayingListAppender.java @@ -17,23 +17,22 @@ import ch.qos.logback.core.read.ListAppender; public class DelayingListAppender extends ListAppender { - public int delay = 5; - public boolean interrupted = false; + public int delay = 5; + public boolean interrupted = false; - public void setDelay(int ms) { - delay = ms; - } + public void setDelay(int ms) { + delay = ms; + } - @Override - public void append(E e) { - try { - Thread.yield(); - Thread.sleep(delay); - Thread.yield(); - } catch (InterruptedException ie) { - interrupted = true; + @Override + public void append(E e) { + try { + Thread.yield(); + Thread.sleep(delay); + Thread.yield(); + } catch (InterruptedException ie) { + interrupted = true; + } + super.append(e); } - super.append(e); - } } - diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/EnvUtilForTests.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/EnvUtilForTests.java index beecd54ccd27cd9c48a5cf7376fce81777171201..16191242f3643aa625bf057f36e66d40984bc662 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/EnvUtilForTests.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/EnvUtilForTests.java @@ -22,55 +22,52 @@ import ch.qos.logback.core.util.CoreTestConstants; public class EnvUtilForTests { - static public boolean isWindows() { - return System.getProperty("os.name").indexOf("Windows") != -1; - } - - static public boolean isMac() { - return System.getProperty("os.name").indexOf("Mac") != -1; - } - - static public boolean isLinux() { - return System.getProperty("os.name").indexOf("Linux") != -1; - } - - - static public boolean isRunningOnSlowJenkins() { - return System.getProperty(CoreTestConstants.SLOW_JENKINS) != null; - } - + static public boolean isWindows() { + return System.getProperty("os.name").indexOf("Windows") != -1; + } - static public String getLocalHostName() { - InetAddress localhostIA; - try { - localhostIA = InetAddress.getLocalHost(); - return localhostIA.getHostName(); - } catch (UnknownHostException e) { - return null; + static public boolean isMac() { + return System.getProperty("os.name").indexOf("Mac") != -1; } - } - static public boolean isLocalHostNameInList(String[] hostList) { - String localHostName = getLocalHostName(); - if (localHostName == null) { - return false; + static public boolean isLinux() { + return System.getProperty("os.name").indexOf("Linux") != -1; } - for (String host : hostList) { - if (host.equalsIgnoreCase(localHostName)) { - return true; - } + + static public boolean isRunningOnSlowJenkins() { + return System.getProperty(CoreTestConstants.SLOW_JENKINS) != null; } - return false; - } + static public String getLocalHostName() { + InetAddress localhostIA; + try { + localhostIA = InetAddress.getLocalHost(); + return localhostIA.getHostName(); + } catch (UnknownHostException e) { + return null; + } + } - public static String getPathToBash() { - if (EnvUtilForTests.isLinux()) { - return CoreTestConstants.BASH_PATH_ON_LINUX; + static public boolean isLocalHostNameInList(String[] hostList) { + String localHostName = getLocalHostName(); + if (localHostName == null) { + return false; + } + for (String host : hostList) { + if (host.equalsIgnoreCase(localHostName)) { + return true; + } + } + return false; } - if (EnvUtilForTests.isLocalHostNameInList(new String[]{"hetz", "het"})) { - return CoreTestConstants.BASH_PATH_ON_CYGWIN; + + public static String getPathToBash() { + if (EnvUtilForTests.isLinux()) { + return CoreTestConstants.BASH_PATH_ON_LINUX; + } + if (EnvUtilForTests.isLocalHostNameInList(new String[] { "hetz", "het" })) { + return CoreTestConstants.BASH_PATH_ON_CYGWIN; + } + return null; } - return null; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileTestUtil.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileTestUtil.java index c7313a9610eeb29747d7e5fff412b8cebff5ec6e..2dc39fef2eb4e70be65f73dad14777f75d5415de 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileTestUtil.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileTestUtil.java @@ -24,14 +24,14 @@ import static junit.framework.Assert.assertTrue; */ public class FileTestUtil { - public static void makeTestOutputDir() { - File target = new File(CoreTestConstants.TARGET_DIR); - if(target.exists() && target.isDirectory()) { - File testoutput = new File(CoreTestConstants.OUTPUT_DIR_PREFIX); - if(!testoutput.exists()) - assertTrue(testoutput.mkdir()); - } else { - throw new IllegalStateException(CoreTestConstants.TARGET_DIR + " does not exist"); + public static void makeTestOutputDir() { + File target = new File(CoreTestConstants.TARGET_DIR); + if (target.exists() && target.isDirectory()) { + File testoutput = new File(CoreTestConstants.OUTPUT_DIR_PREFIX); + if (!testoutput.exists()) + assertTrue(testoutput.mkdir()); + } else { + throw new IllegalStateException(CoreTestConstants.TARGET_DIR + " does not exist"); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileToBufferUtil.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileToBufferUtil.java index f75b0b004676a69d5888b3fa5f83cfd451a6a646..1789e196d352d2ff60a8e8fbb0dc06478f6ccd77 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileToBufferUtil.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/FileToBufferUtil.java @@ -27,49 +27,48 @@ import java.util.zip.ZipFile; public class FileToBufferUtil { - static public void readIntoList(File file, List stringList) - throws IOException { + static public void readIntoList(File file, List stringList) throws IOException { - if (file.getName().endsWith(".gz")) { - gzFileReadIntoList(file, stringList); - } else if (file.getName().endsWith(".zip")) { - zipFileReadIntoList(file, stringList); - } else { - regularReadIntoList(file, stringList); + if (file.getName().endsWith(".gz")) { + gzFileReadIntoList(file, stringList); + } else if (file.getName().endsWith(".zip")) { + zipFileReadIntoList(file, stringList); + } else { + regularReadIntoList(file, stringList); + } } - } - private static void zipFileReadIntoList(File file, List stringList) throws IOException { - System.out.println("Reading zip file ["+file+"]"); - ZipFile zipFile = new ZipFile(file); - Enumeration entries = zipFile.entries(); - ZipEntry entry = (ZipEntry) entries.nextElement(); - readInputStream(zipFile.getInputStream(entry), stringList); - } + private static void zipFileReadIntoList(File file, List stringList) throws IOException { + System.out.println("Reading zip file [" + file + "]"); + ZipFile zipFile = new ZipFile(file); + Enumeration entries = zipFile.entries(); + ZipEntry entry = (ZipEntry) entries.nextElement(); + readInputStream(zipFile.getInputStream(entry), stringList); + } - static void readInputStream(InputStream is, List stringList) throws IOException { - BufferedReader in = new BufferedReader(new InputStreamReader(is)); - String line; - while ((line = in.readLine()) != null) { - stringList.add(line); + static void readInputStream(InputStream is, List stringList) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(is)); + String line; + while ((line = in.readLine()) != null) { + stringList.add(line); + } + in.close(); } - in.close(); - } - static public void regularReadIntoList(File file, List stringList) throws IOException { - FileInputStream fis = new FileInputStream(file); - BufferedReader in = new BufferedReader(new InputStreamReader(fis)); - String line; - while ((line = in.readLine()) != null) { - stringList.add(line); + static public void regularReadIntoList(File file, List stringList) throws IOException { + FileInputStream fis = new FileInputStream(file); + BufferedReader in = new BufferedReader(new InputStreamReader(fis)); + String line; + while ((line = in.readLine()) != null) { + stringList.add(line); + } + in.close(); } - in.close(); - } - static public void gzFileReadIntoList(File file, List stringList) throws IOException { - FileInputStream fis = new FileInputStream(file); - GZIPInputStream gzis = new GZIPInputStream(fis); - readInputStream(gzis, stringList); - } + static public void gzFileReadIntoList(File file, List stringList) throws IOException { + FileInputStream fis = new FileInputStream(file); + GZIPInputStream gzis = new GZIPInputStream(fis); + readInputStream(gzis, stringList); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/NPEAppender.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/NPEAppender.java index 643a6e6fa3d89b6e1af2786455e1110e66117ed7..defa6f94677572277e2bb2eaa22452382734523b 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/NPEAppender.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/NPEAppender.java @@ -16,8 +16,8 @@ package ch.qos.logback.core.testUtil; import ch.qos.logback.core.AppenderBase; public class NPEAppender extends AppenderBase { - @Override - protected void append(E eventObject) { - throw new NullPointerException(); - } + @Override + protected void append(E eventObject) { + throw new NullPointerException(); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/RandomUtil.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/RandomUtil.java index 162aa531ff267c56cba96307b82bd0ad9a17b556..9bdff9d2002dc6411a6d28c3f5b1b034ebc7728f 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/RandomUtil.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/RandomUtil.java @@ -17,19 +17,19 @@ import java.util.Random; public class RandomUtil { - private static Random random = new Random(); + private static Random random = new Random(); - public static int getRandomServerPort() { - int r = random.nextInt(20000); - // the first 1024 ports are usually reserved for the OS - return r + 1024; - } + public static int getRandomServerPort() { + int r = random.nextInt(20000); + // the first 1024 ports are usually reserved for the OS + return r + 1024; + } - public static int getPositiveInt() { - int r = random.nextInt(); - if (r < 0) { - r = -r; + public static int getPositiveInt() { + int r = random.nextInt(); + if (r < 0) { + r = -r; + } + return r; } - return r; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/testUtil/StringListAppender.java b/logback-core/src/test/java/ch/qos/logback/core/testUtil/StringListAppender.java index 6f959863f0593f8d8d37c211bd70405a19c41244..0a6640abbba8bb51610950cdba370a6d68d9c630 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/testUtil/StringListAppender.java +++ b/logback-core/src/test/java/ch/qos/logback/core/testUtil/StringListAppender.java @@ -21,33 +21,33 @@ import ch.qos.logback.core.Layout; public class StringListAppender extends AppenderBase { - Layout layout; - public List strList = new ArrayList(); + Layout layout; + public List strList = new ArrayList(); - public void start() { - strList.clear(); + public void start() { + strList.clear(); - if (layout == null || !layout.isStarted()) { - return; + if (layout == null || !layout.isStarted()) { + return; + } + super.start(); + } + + public void stop() { + super.stop(); + } + + @Override + protected void append(E eventObject) { + String res = layout.doLayout(eventObject); + strList.add(res); + } + + public Layout getLayout() { + return layout; + } + + public void setLayout(Layout layout) { + this.layout = layout; } - super.start(); - } - - public void stop() { - super.stop(); - } - - @Override - protected void append(E eventObject) { - String res = layout.doLayout(eventObject); - strList.add(res); - } - - public Layout getLayout() { - return layout; - } - - public void setLayout(Layout layout) { - this.layout = layout; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/CachingFotmatterTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/CachingFotmatterTest.java index b0b246e1f60a5c9ee35d19414865dcede04af67e..16c62c182d8f4f05e7b62d8f915ea2a4e6070570 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/CachingFotmatterTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/CachingFotmatterTest.java @@ -12,29 +12,29 @@ import org.junit.Test; public class CachingFotmatterTest { - final static String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm"; - - SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN); - TimeZone perthTZ = TimeZone.getTimeZone("Australia/Perth"); - TimeZone utcTZ = TimeZone.getTimeZone("UTC"); - - @Before - public void setUp() { - sdf.setTimeZone(utcTZ); - } - - @Test - public void timeZoneIsTakenIntoAccount() throws ParseException { - - CachingDateFormatter cdf = new CachingDateFormatter(DATE_PATTERN); + final static String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm"; + + SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN); TimeZone perthTZ = TimeZone.getTimeZone("Australia/Perth"); - cdf.setTimeZone(perthTZ); - - Date march26_2015_0949_UTC = sdf.parse("2015-03-26T09:49"); - System.out.print(march26_2015_0949_UTC); - - String result = cdf.format(march26_2015_0949_UTC.getTime()); - // AWST (Perth) is 8 hours ahead of UTC - assertEquals("2015-03-26T17:49", result); - } + TimeZone utcTZ = TimeZone.getTimeZone("UTC"); + + @Before + public void setUp() { + sdf.setTimeZone(utcTZ); + } + + @Test + public void timeZoneIsTakenIntoAccount() throws ParseException { + + CachingDateFormatter cdf = new CachingDateFormatter(DATE_PATTERN); + TimeZone perthTZ = TimeZone.getTimeZone("Australia/Perth"); + cdf.setTimeZone(perthTZ); + + Date march26_2015_0949_UTC = sdf.parse("2015-03-26T09:49"); + System.out.print(march26_2015_0949_UTC); + + String result = cdf.format(march26_2015_0949_UTC.getTime()); + // AWST (Perth) is 8 hours ahead of UTC + assertEquals("2015-03-26T17:49", result); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/CharSequenceToRegexMapperTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/CharSequenceToRegexMapperTest.java index a4820892c69e7496669264b37992d60bcd11e98d..4c93c0801a40c38ec0356aa0b3ee97b8c2593627 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/CharSequenceToRegexMapperTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/CharSequenceToRegexMapperTest.java @@ -23,63 +23,60 @@ import java.util.Locale; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; - public class CharSequenceToRegexMapperTest { - static Locale KO_LOCALE = new Locale("ko", "KR"); - Locale oldLocale = Locale.getDefault(); - - @After - public void tearDown() { - Locale.setDefault(oldLocale); - } - - @Test - public void findMinMaxLengthsInSymbolsWithTrivialInputs() { - String[] symbols = new String[]{"a", "bb"}; - int[] results = CharSequenceToRegexMapper.findMinMaxLengthsInSymbols(symbols); - assertEquals(1, results[0]); - assertEquals(2, results[1]); - } + static Locale KO_LOCALE = new Locale("ko", "KR"); + Locale oldLocale = Locale.getDefault(); - @Test - public void emptyStringValuesShouldBeIgnoredByFindMinMaxLengthsInSymbols() { - String[] symbols = new String[]{"aaa", ""}; - int[] results = CharSequenceToRegexMapper.findMinMaxLengthsInSymbols(symbols); - assertEquals(3, results[0]); - assertEquals(3, results[1]); - } + @After + public void tearDown() { + Locale.setDefault(oldLocale); + } + @Test + public void findMinMaxLengthsInSymbolsWithTrivialInputs() { + String[] symbols = new String[] { "a", "bb" }; + int[] results = CharSequenceToRegexMapper.findMinMaxLengthsInSymbols(symbols); + assertEquals(1, results[0]); + assertEquals(2, results[1]); + } - @Test - @Ignore - public void noneOfTheSymbolsAreOfZeroLengthForKorean() { - Locale.setDefault(KO_LOCALE); - noneOfTheSymbolsAreOfZeroLength(); - } + @Test + public void emptyStringValuesShouldBeIgnoredByFindMinMaxLengthsInSymbols() { + String[] symbols = new String[] { "aaa", "" }; + int[] results = CharSequenceToRegexMapper.findMinMaxLengthsInSymbols(symbols); + assertEquals(3, results[0]); + assertEquals(3, results[1]); + } - @Test - @Ignore - public void noneOfTheSymbolsAreOfZeroLengthForSwiss() { - Locale.setDefault(new Locale("fr", "CH")); - noneOfTheSymbolsAreOfZeroLength(); - } + @Test + @Ignore + public void noneOfTheSymbolsAreOfZeroLengthForKorean() { + Locale.setDefault(KO_LOCALE); + noneOfTheSymbolsAreOfZeroLength(); + } - private void noneOfTheSymbolsAreOfZeroLength() { - DateFormatSymbols dateFormatSymbols = DateFormatSymbols.getInstance(); - //checkEmptyString(dateFormatSymbols.getShortMonths(), "ShortMonths"); - //checkEmptyString(dateFormatSymbols.getMonths(), "Months"); - checkEmptyString(dateFormatSymbols.getShortWeekdays(), "ShortWeekdays"); - checkEmptyString(dateFormatSymbols.getWeekdays(), "Weekdays"); - checkEmptyString(dateFormatSymbols.getAmPmStrings(), "AmPmStrings"); + @Test + @Ignore + public void noneOfTheSymbolsAreOfZeroLengthForSwiss() { + Locale.setDefault(new Locale("fr", "CH")); + noneOfTheSymbolsAreOfZeroLength(); + } - } + private void noneOfTheSymbolsAreOfZeroLength() { + DateFormatSymbols dateFormatSymbols = DateFormatSymbols.getInstance(); + // checkEmptyString(dateFormatSymbols.getShortMonths(), "ShortMonths"); + // checkEmptyString(dateFormatSymbols.getMonths(), "Months"); + checkEmptyString(dateFormatSymbols.getShortWeekdays(), "ShortWeekdays"); + checkEmptyString(dateFormatSymbols.getWeekdays(), "Weekdays"); + checkEmptyString(dateFormatSymbols.getAmPmStrings(), "AmPmStrings"); - private void checkEmptyString(String[] symbolArray, String category) { - for (String s : symbolArray) { - System.out.println(category + " [" + s + "]"); - assertTrue(category + " contains empty strings", s.length() > 0); } - } + private void checkEmptyString(String[] symbolArray, String category) { + for (String s : symbolArray) { + System.out.println(category + " [" + s + "]"); + assertTrue(category + " contains empty strings", s.length() > 0); + } + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/ContentTypeUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/ContentTypeUtilTest.java index 3c99cf5e110d91f66317774a847237b5a0098d3d..2750bab82a2eee8e97f84f28d943677ddbf190af 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/ContentTypeUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/ContentTypeUtilTest.java @@ -17,28 +17,26 @@ import static org.junit.Assert.*; import org.junit.Test; - public class ContentTypeUtilTest { - - @Test - public void smoke() { - String contextType = "text/html"; - assertTrue(ContentTypeUtil.isTextual(contextType)); - assertEquals("html", ContentTypeUtil.getSubType(contextType)); - } - - @Test - public void nullContext() { - String contextType = null; - assertFalse(ContentTypeUtil.isTextual(contextType)); - assertNull(ContentTypeUtil.getSubType(contextType)); - } - - @Test - public void emptySubtype() { - String contextType = "text/"; - assertTrue(ContentTypeUtil.isTextual(contextType)); - assertNull(ContentTypeUtil.getSubType(contextType)); - } + @Test + public void smoke() { + String contextType = "text/html"; + assertTrue(ContentTypeUtil.isTextual(contextType)); + assertEquals("html", ContentTypeUtil.getSubType(contextType)); + } + + @Test + public void nullContext() { + String contextType = null; + assertFalse(ContentTypeUtil.isTextual(contextType)); + assertNull(ContentTypeUtil.getSubType(contextType)); + } + + @Test + public void emptySubtype() { + String contextType = "text/"; + assertTrue(ContentTypeUtil.isTextual(contextType)); + assertNull(ContentTypeUtil.getSubType(contextType)); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/CoreTestConstants.java b/logback-core/src/test/java/ch/qos/logback/core/util/CoreTestConstants.java index c37c3a8277524aceec6bdcbfbd0b5968638c1ebb..1eb0aa69177c97584cc28be233aa8bfd0566a836 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/CoreTestConstants.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/CoreTestConstants.java @@ -15,20 +15,18 @@ package ch.qos.logback.core.util; public class CoreTestConstants { - public static final String TEST_SRC_PREFIX = "src/test/"; - public static final String TEST_INPUT_PREFIX = TEST_SRC_PREFIX + "input/"; - public static final String JORAN_INPUT_PREFIX = TEST_INPUT_PREFIX - + "joran/"; + public static final String TEST_SRC_PREFIX = "src/test/"; + public static final String TEST_INPUT_PREFIX = TEST_SRC_PREFIX + "input/"; + public static final String JORAN_INPUT_PREFIX = TEST_INPUT_PREFIX + "joran/"; - public static final String TARGET_DIR = "target/"; - public static final String OUTPUT_DIR_PREFIX = TARGET_DIR + "test-output/"; + public static final String TARGET_DIR = "target/"; + public static final String OUTPUT_DIR_PREFIX = TARGET_DIR + "test-output/"; - public static final int SUCCESSFUL_EXIT_CODE = 8; - public static final int FAILURE_EXIT_CODE = 1; + public static final int SUCCESSFUL_EXIT_CODE = 8; + public static final int FAILURE_EXIT_CODE = 1; - public static final String BASH_PATH_ON_CYGWIN = "c:/cygwin/bin/bash"; - public static final String BASH_PATH_ON_LINUX = "bash"; + public static final String BASH_PATH_ON_CYGWIN = "c:/cygwin/bin/bash"; + public static final String BASH_PATH_ON_LINUX = "bash"; - - public static final String SLOW_JENKINS = "slowJenkins"; + public static final String SLOW_JENKINS = "slowJenkins"; } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/DatePatternToRegexTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/DatePatternToRegexTest.java index 5c5e70fb6c4bb22154d8518e2bace82ba5315001..cd69d7a54347d16a248d9f842fbd663adbdb5bb5 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/DatePatternToRegexTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/DatePatternToRegexTest.java @@ -28,129 +28,126 @@ import org.junit.Test; import ch.qos.logback.core.CoreConstants; public class DatePatternToRegexTest { - static Calendar CAL_2009_08_3_NIGHT = Calendar.getInstance(); - static Calendar CAL_2009_08_3_MORNING = Calendar.getInstance(); - static Locale CZ_LOCALE = new Locale("cs", "CZ"); - static Locale KO_LOCALE = new Locale("ko", "KR"); - - - @BeforeClass - public static void setUpCalendars() { - CAL_2009_08_3_NIGHT.set(2009, 8, 3, 21, 57, 16); - CAL_2009_08_3_NIGHT.set(Calendar.MILLISECOND, 333); - - CAL_2009_08_3_MORNING.set(2009, 8, 3, 10, 24, 37); - CAL_2009_08_3_MORNING.set(Calendar.MILLISECOND, 333); - } - - @Test - public void ISO8601() { - doTest(CoreConstants.ISO8601_PATTERN, CAL_2009_08_3_NIGHT); - } - - @Test - public void withQuotes() { - doTest("yyyy-MM-dd'T'HH:mm:ss,SSS", CAL_2009_08_3_NIGHT); - - } - - @Test - public void month() { - doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT); - doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT, CZ_LOCALE); - doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT, KO_LOCALE); - - doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT); - doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT, CZ_LOCALE); - doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT, KO_LOCALE); - - } - - public void monthWithLocal() { - - } - - @Test - public void dot() { - doTest("yyyy.MMM.dd", CAL_2009_08_3_NIGHT); - ; - } - - @Test - public void timeZone() { - doTest("yyyy-MMM-dd HH:mm:ss z", CAL_2009_08_3_NIGHT); - doTest("yyyy-MMM-dd HH:mm:ss Z", CAL_2009_08_3_NIGHT); - } - - @Test - public void dayInWeek() { - doTest("EE", CAL_2009_08_3_NIGHT); - doTest("EE", CAL_2009_08_3_NIGHT, CZ_LOCALE); - doTest("EE", CAL_2009_08_3_NIGHT, KO_LOCALE); - - doTest("EEEE", CAL_2009_08_3_NIGHT); - doTest("EEEE", CAL_2009_08_3_NIGHT, CZ_LOCALE); - doTest("EEEE", CAL_2009_08_3_NIGHT, KO_LOCALE); - } - - @Test - public void amPm() { - doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT); - doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT, CZ_LOCALE); - doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT, KO_LOCALE); - - doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING); - doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING, CZ_LOCALE); - doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING, KO_LOCALE); - - } - - void doTest(String datePattern, Calendar calendar) { - doTest(datePattern, calendar, null); - } - - void doTest(String datePattern, Calendar calendar, Locale locale) { - Locale oldDefaultLocale = Locale.getDefault(); - if (locale != null) { - Locale.setDefault(locale); + static Calendar CAL_2009_08_3_NIGHT = Calendar.getInstance(); + static Calendar CAL_2009_08_3_MORNING = Calendar.getInstance(); + static Locale CZ_LOCALE = new Locale("cs", "CZ"); + static Locale KO_LOCALE = new Locale("ko", "KR"); + + @BeforeClass + public static void setUpCalendars() { + CAL_2009_08_3_NIGHT.set(2009, 8, 3, 21, 57, 16); + CAL_2009_08_3_NIGHT.set(Calendar.MILLISECOND, 333); + + CAL_2009_08_3_MORNING.set(2009, 8, 3, 10, 24, 37); + CAL_2009_08_3_MORNING.set(Calendar.MILLISECOND, 333); } - try { - SimpleDateFormat sdf = new SimpleDateFormat(datePattern); - DateTokenConverter dtc = makeDTC(datePattern); - verify(sdf, calendar, dtc); - } finally { - if (locale != null) - Locale.setDefault(oldDefaultLocale); + @Test + public void ISO8601() { + doTest(CoreConstants.ISO8601_PATTERN, CAL_2009_08_3_NIGHT); + } + + @Test + public void withQuotes() { + doTest("yyyy-MM-dd'T'HH:mm:ss,SSS", CAL_2009_08_3_NIGHT); + + } + + @Test + public void month() { + doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT); + doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT, CZ_LOCALE); + doTest("yyyy-MMM-dd", CAL_2009_08_3_NIGHT, KO_LOCALE); + + doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT); + doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT, CZ_LOCALE); + doTest("yyyy-MMMM-dd", CAL_2009_08_3_NIGHT, KO_LOCALE); + + } + + public void monthWithLocal() { + + } + + @Test + public void dot() { + doTest("yyyy.MMM.dd", CAL_2009_08_3_NIGHT); + ; + } + + @Test + public void timeZone() { + doTest("yyyy-MMM-dd HH:mm:ss z", CAL_2009_08_3_NIGHT); + doTest("yyyy-MMM-dd HH:mm:ss Z", CAL_2009_08_3_NIGHT); + } + + @Test + public void dayInWeek() { + doTest("EE", CAL_2009_08_3_NIGHT); + doTest("EE", CAL_2009_08_3_NIGHT, CZ_LOCALE); + doTest("EE", CAL_2009_08_3_NIGHT, KO_LOCALE); + + doTest("EEEE", CAL_2009_08_3_NIGHT); + doTest("EEEE", CAL_2009_08_3_NIGHT, CZ_LOCALE); + doTest("EEEE", CAL_2009_08_3_NIGHT, KO_LOCALE); + } + + @Test + public void amPm() { + doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT); + doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT, CZ_LOCALE); + doTest("yyyy-MM-dd a", CAL_2009_08_3_NIGHT, KO_LOCALE); + + doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING); + doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING, CZ_LOCALE); + doTest("yyyy-MM-dd a", CAL_2009_08_3_MORNING, KO_LOCALE); + + } + + void doTest(String datePattern, Calendar calendar) { + doTest(datePattern, calendar, null); + } + + void doTest(String datePattern, Calendar calendar, Locale locale) { + Locale oldDefaultLocale = Locale.getDefault(); + if (locale != null) { + Locale.setDefault(locale); + } + + try { + SimpleDateFormat sdf = new SimpleDateFormat(datePattern); + DateTokenConverter dtc = makeDTC(datePattern); + verify(sdf, calendar, dtc); + } finally { + if (locale != null) + Locale.setDefault(oldDefaultLocale); + + } + } + + Locale locale; + + // void doTest(String datePattern, Calendar calendar) { + // doTest(datePattern, calendar, false); + // } + + void verify(SimpleDateFormat sdf, Calendar calendar, DateTokenConverter dtc) { + String expected = sdf.format(calendar.getTime()); + // if (slashified) { + // expected = expected.replace('\\', '/'); + // } + String regex = dtc.toRegex(); + // System.out.println("expected="+expected); + // System.out.println(regex); + assertTrue("[" + expected + "] does not match regex [" + regex + "]", expected.matches(regex)); + } + private DateTokenConverter makeDTC(String datePattern) { + DateTokenConverter dtc = new DateTokenConverter(); + List optionList = new ArrayList(); + optionList.add(datePattern); + dtc.setOptionList(optionList); + dtc.start(); + return dtc; } - } - - Locale locale; - -// void doTest(String datePattern, Calendar calendar) { -// doTest(datePattern, calendar, false); -// } - - - void verify(SimpleDateFormat sdf, Calendar calendar, DateTokenConverter dtc) { - String expected = sdf.format(calendar.getTime()); -// if (slashified) { -// expected = expected.replace('\\', '/'); -// } - String regex = dtc.toRegex(); - //System.out.println("expected="+expected); - //System.out.println(regex); - assertTrue("[" + expected + "] does not match regex [" + regex + "]", - expected.matches(regex)); - } - - private DateTokenConverter makeDTC(String datePattern) { - DateTokenConverter dtc = new DateTokenConverter(); - List optionList = new ArrayList(); - optionList.add(datePattern); - dtc.setOptionList(optionList); - dtc.start(); - return dtc; - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/DurationTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/DurationTest.java index 1a57576ed514d50fb61cb2508775a6b64e8e2346..316675e94d4ea2a86e4055827e277c113ec29906 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/DurationTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/DurationTest.java @@ -17,88 +17,86 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; +public class DurationTest { -public class DurationTest { + static long HOURS_CO = 60 * 60; + static long DAYS_CO = 24 * 60 * 60; - static long HOURS_CO = 60*60; - static long DAYS_CO = 24*60*60; - + @Test + public void test() { + { + Duration d = Duration.valueOf("12"); + assertEquals(12, d.getMilliseconds()); + } - @Test - public void test() { - { - Duration d = Duration.valueOf("12"); - assertEquals(12, d.getMilliseconds()); - } + { + Duration d = Duration.valueOf("159 milli"); + assertEquals(159, d.getMilliseconds()); + } - { - Duration d = Duration.valueOf("159 milli"); - assertEquals(159, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("15 millis"); - assertEquals(15, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("8 milliseconds"); - assertEquals(8, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("10.7 millisecond"); - assertEquals(10, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("10 SECOnds"); - assertEquals(10 * 1000, d.getMilliseconds()); - } + { + Duration d = Duration.valueOf("15 millis"); + assertEquals(15, d.getMilliseconds()); + } - { - Duration d = Duration.valueOf("12seconde"); - assertEquals(12 * 1000, d.getMilliseconds()); - } + { + Duration d = Duration.valueOf("8 milliseconds"); + assertEquals(8, d.getMilliseconds()); + } - { - Duration d = Duration.valueOf("14 SECONDES"); - assertEquals(14 * 1000, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("12second"); - assertEquals(12 * 1000, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("10.7 seconds"); - assertEquals(10700, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("1 minute"); - assertEquals(1000*60, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("2.2 minutes"); - assertEquals(2200*60, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("1 hour"); - assertEquals(1000*HOURS_CO, d.getMilliseconds()); - } - - { - Duration d = Duration.valueOf("4.2 hours"); - assertEquals(4200*HOURS_CO, d.getMilliseconds()); - } + { + Duration d = Duration.valueOf("10.7 millisecond"); + assertEquals(10, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("10 SECOnds"); + assertEquals(10 * 1000, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("12seconde"); + assertEquals(12 * 1000, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("14 SECONDES"); + assertEquals(14 * 1000, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("12second"); + assertEquals(12 * 1000, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("10.7 seconds"); + assertEquals(10700, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("1 minute"); + assertEquals(1000 * 60, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("2.2 minutes"); + assertEquals(2200 * 60, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("1 hour"); + assertEquals(1000 * HOURS_CO, d.getMilliseconds()); + } + + { + Duration d = Duration.valueOf("4.2 hours"); + assertEquals(4200 * HOURS_CO, d.getMilliseconds()); + } - { - Duration d = Duration.valueOf("5 days"); - assertEquals(5000*DAYS_CO, d.getMilliseconds()); + { + Duration d = Duration.valueOf("5 days"); + assertEquals(5000 * DAYS_CO, d.getMilliseconds()); + } } - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/FileSizeTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/FileSizeTest.java index e8728a225263f88a9e73b75b9cb6f7d17afd83bd..7d0c95665c560bf5f2d55fb10b0c01c4be24af8d 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/FileSizeTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/FileSizeTest.java @@ -17,40 +17,38 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; +public class FileSizeTest { + + static long KB_CO = 1024; + static long MB_CO = 1024 * 1024; + static long GB_CO = 1024 * MB_CO; + + @Test + public void test() { + { + FileSize fs = FileSize.valueOf("8"); + assertEquals(8, fs.getSize()); + } + + { + FileSize fs = FileSize.valueOf("8 kbs"); + assertEquals(8 * KB_CO, fs.getSize()); + } + + { + FileSize fs = FileSize.valueOf("8 kb"); + assertEquals(8 * KB_CO, fs.getSize()); + } + + { + FileSize fs = FileSize.valueOf("12 mb"); + assertEquals(12 * MB_CO, fs.getSize()); + } + + { + FileSize fs = FileSize.valueOf("5 GBs"); + assertEquals(5 * GB_CO, fs.getSize()); + } -public class FileSizeTest{ - - static long KB_CO = 1024; - static long MB_CO = 1024*1024; - static long GB_CO = 1024*MB_CO; - - - @Test - public void test() { - { - FileSize fs = FileSize.valueOf("8"); - assertEquals(8, fs.getSize()); - } - - { - FileSize fs = FileSize.valueOf("8 kbs"); - assertEquals(8*KB_CO, fs.getSize()); - } - - { - FileSize fs = FileSize.valueOf("8 kb"); - assertEquals(8*KB_CO, fs.getSize()); } - - { - FileSize fs = FileSize.valueOf("12 mb"); - assertEquals(12*MB_CO, fs.getSize()); - } - - { - FileSize fs = FileSize.valueOf("5 GBs"); - assertEquals(5*GB_CO, fs.getSize()); - } - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/FileUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/FileUtilTest.java index ba4a8e7dda2f6e8b0b2f628c7db396062ca47615..901dfbb2d19ef6b70a5e7718a40197897c9cb0f1 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/FileUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/FileUtilTest.java @@ -30,77 +30,77 @@ import org.junit.Test; public class FileUtilTest { - Context context = new ContextBase(); - FileUtil fileUtil = new FileUtil(context); - List cleanupList = new ArrayList(); - // test-output folder is not always clean - int diff = new Random().nextInt(10000); - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - for(File f: cleanupList) { - f.delete(); + Context context = new ContextBase(); + FileUtil fileUtil = new FileUtil(context); + List cleanupList = new ArrayList(); + // test-output folder is not always clean + int diff = new Random().nextInt(10000); + + @Before + public void setUp() throws Exception { + + } + + @After + public void tearDown() throws Exception { + for (File f : cleanupList) { + f.delete(); + } + } + + @Test + public void checkParentCreationInquiryAndSubsequentCreation() { + File file = new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff + "/testing.txt"); + // these will be deleted later + cleanupList.add(file); + cleanupList.add(file.getParentFile()); + + assertFalse(file.getParentFile().exists()); + assertTrue(FileUtil.createMissingParentDirectories(file)); + assertTrue(file.getParentFile().exists()); + } + + @Test + public void checkDeeperParentCreationInquiryAndSubsequentCreation() { + + File file = new File(CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff + "/bla/testing.txt"); + // these will be deleted later + cleanupList.add(file); + cleanupList.add(file.getParentFile()); + cleanupList.add(file.getParentFile().getParentFile()); + + assertFalse(file.getParentFile().exists()); + assertTrue(FileUtil.createMissingParentDirectories(file)); + assertTrue(file.getParentFile().exists()); + } + + @Test + public void basicCopyingWorks() throws IOException { + String dir = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff; + + File dirFile = new File(dir); + dirFile.mkdir(); + + String src = CoreTestConstants.TEST_INPUT_PREFIX + "compress1.copy"; + String target = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff + "/copyingWorks.txt"; + + fileUtil.copy(src, target); + Compare.compare(src, target); + } + + @Test + public void createParentDirIgnoresExistingDir() { + String target = CoreTestConstants.OUTPUT_DIR_PREFIX + "/fu" + diff + "/testing.txt"; + File file = new File(target); + cleanupList.add(file); + file.mkdirs(); + assertTrue(file.getParentFile().exists()); + assertTrue(FileUtil.createMissingParentDirectories(file)); + } + + @Test + public void createParentDirAcceptsNoParentSpecified() { + File file = new File("testing.txt"); + assertTrue(FileUtil.createMissingParentDirectories(file)); } - } - - @Test - public void checkParentCreationInquiryAndSubsequentCreation() { - File file = new File(CoreTestConstants.OUTPUT_DIR_PREFIX+"/fu"+diff+"/testing.txt"); - // these will be deleted later - cleanupList.add(file); - cleanupList.add(file.getParentFile()); - - assertFalse(file.getParentFile().exists()); - assertTrue(FileUtil.createMissingParentDirectories(file)); - assertTrue(file.getParentFile().exists()); - } - - @Test - public void checkDeeperParentCreationInquiryAndSubsequentCreation() { - - File file = new File(CoreTestConstants.OUTPUT_DIR_PREFIX+"/fu"+diff+"/bla/testing.txt"); - // these will be deleted later - cleanupList.add(file); - cleanupList.add(file.getParentFile()); - cleanupList.add(file.getParentFile().getParentFile()); - - assertFalse(file.getParentFile().exists()); - assertTrue(FileUtil.createMissingParentDirectories(file)); - assertTrue(file.getParentFile().exists()); - } - - @Test - public void basicCopyingWorks() throws IOException { - String dir = CoreTestConstants.OUTPUT_DIR_PREFIX+"/fu"+diff; - - File dirFile = new File(dir); - dirFile.mkdir(); - - String src = CoreTestConstants.TEST_INPUT_PREFIX + "compress1.copy"; - String target = CoreTestConstants.OUTPUT_DIR_PREFIX+"/fu"+diff+"/copyingWorks.txt"; - - fileUtil.copy(src, target); - Compare.compare(src, target); - } - - @Test - public void createParentDirIgnoresExistingDir() { - String target = CoreTestConstants.OUTPUT_DIR_PREFIX+"/fu"+ diff +"/testing.txt"; - File file = new File(target); - cleanupList.add(file); - file.mkdirs(); - assertTrue(file.getParentFile().exists()); - assertTrue(FileUtil.createMissingParentDirectories(file)); - } - - @Test - public void createParentDirAcceptsNoParentSpecified() { - File file = new File("testing.txt"); - assertTrue(FileUtil.createMissingParentDirectories(file)); - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/LocationUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/LocationUtilTest.java index 273497d07223457ce4113cbc18a340227fbe1257..a3adc860620bba6716b9a864c72f573e369a2e30 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/LocationUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/LocationUtilTest.java @@ -35,66 +35,62 @@ import ch.qos.logback.core.util.LocationUtil; */ public class LocationUtilTest { - private static final String TEST_CLASSPATH_RESOURCE = "util/testResource.txt"; - private static final String TEST_PATTERN = "TEST RESOURCE"; - - @Test - public void testImplicitClasspathUrl() throws Exception { - URL url = LocationUtil.urlForResource(TEST_CLASSPATH_RESOURCE); - validateResource(url); - } - - @Test - public void testExplicitClasspathUrl() throws Exception { - URL url = LocationUtil.urlForResource( - LocationUtil.CLASSPATH_SCHEME + TEST_CLASSPATH_RESOURCE); - validateResource(url); - } - - @Test - public void testExplicitClasspathUrlWithLeadingSlash() throws Exception { - URL url = LocationUtil.urlForResource( - LocationUtil.CLASSPATH_SCHEME + "/" + TEST_CLASSPATH_RESOURCE); - validateResource(url); - } + private static final String TEST_CLASSPATH_RESOURCE = "util/testResource.txt"; + private static final String TEST_PATTERN = "TEST RESOURCE"; - @Test(expected = MalformedURLException.class) - public void testExplicitClasspathUrlEmptyPath() throws Exception { - LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME); - } + @Test + public void testImplicitClasspathUrl() throws Exception { + URL url = LocationUtil.urlForResource(TEST_CLASSPATH_RESOURCE); + validateResource(url); + } + + @Test + public void testExplicitClasspathUrl() throws Exception { + URL url = LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + TEST_CLASSPATH_RESOURCE); + validateResource(url); + } + + @Test + public void testExplicitClasspathUrlWithLeadingSlash() throws Exception { + URL url = LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/" + TEST_CLASSPATH_RESOURCE); + validateResource(url); + } - @Test(expected = MalformedURLException.class) - public void testExplicitClasspathUrlWithRootPath() throws Exception { - LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/"); - } + @Test(expected = MalformedURLException.class) + public void testExplicitClasspathUrlEmptyPath() throws Exception { + LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME); + } - @Test - public void testFileUrl() throws Exception { - File file = File.createTempFile("testResource", ".txt"); - file.deleteOnExit(); - PrintWriter writer = new PrintWriter(file); - writer.println(TEST_PATTERN); - writer.close(); - URL url = file.toURI().toURL(); - validateResource(url); - } - - private void validateResource(URL url) throws IOException { - InputStream inputStream = url.openStream(); - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - String line = reader.readLine(); - assertEquals(TEST_PATTERN, line); + @Test(expected = MalformedURLException.class) + public void testExplicitClasspathUrlWithRootPath() throws Exception { + LocationUtil.urlForResource(LocationUtil.CLASSPATH_SCHEME + "/"); } - finally { - try { - inputStream.close(); - } - catch (IOException ex) { - // ignore close exception - ex.printStackTrace(System.err); - } + + @Test + public void testFileUrl() throws Exception { + File file = File.createTempFile("testResource", ".txt"); + file.deleteOnExit(); + PrintWriter writer = new PrintWriter(file); + writer.println(TEST_PATTERN); + writer.close(); + URL url = file.toURI().toURL(); + validateResource(url); } - } - + + private void validateResource(URL url) throws IOException { + InputStream inputStream = url.openStream(); + try { + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + String line = reader.readLine(); + assertEquals(TEST_PATTERN, line); + } finally { + try { + inputStream.close(); + } catch (IOException ex) { + // ignore close exception + ex.printStackTrace(System.err); + } + } + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/OptionHelperTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/OptionHelperTest.java index f33b06e9609454830a2fd446bb621ff281d5524f..27c764adf2fa5eba4c053899a65051af2a5dc713 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/OptionHelperTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/OptionHelperTest.java @@ -29,231 +29,227 @@ import ch.qos.logback.core.Context; import ch.qos.logback.core.ContextBase; import ch.qos.logback.core.joran.spi.JoranException; +public class OptionHelperTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + String text = "Testing ${v1} variable substitution ${v2}"; + String expected = "Testing if variable substitution works"; + Context context = new ContextBase(); + Map secondaryMap; + + @Before + public void setUp() throws Exception { + secondaryMap = new HashMap(); + } + + @Test + public void testLiteral() { + String noSubst = "hello world"; + String result = OptionHelper.substVars(noSubst, context); + assertEquals(noSubst, result); + } + + @Test + public void testUndefinedValues() { + String withUndefinedValues = "${axyz}"; + + String result = OptionHelper.substVars(withUndefinedValues, context); + assertEquals("axyz" + OptionHelper._IS_UNDEFINED, result); + } + + @Test + public void testSubstVarsVariableNotClosed() { + String noSubst = "testing if ${v1 works"; + + try { + @SuppressWarnings("unused") + String result = OptionHelper.substVars(noSubst, context); + fail(); + } catch (IllegalArgumentException e) { + // ok + } + } + + @Test + public void testSubstVarsContextOnly() { + context.putProperty("v1", "if"); + context.putProperty("v2", "works"); + + String result = OptionHelper.substVars(text, context); + assertEquals(expected, result); + } + + @Test + public void testSubstVarsSystemProperties() { + System.setProperty("v1", "if"); + System.setProperty("v2", "works"); + + String result = OptionHelper.substVars(text, context); + assertEquals(expected, result); + + System.clearProperty("v1"); + System.clearProperty("v2"); + } + + @Test + public void testSubstVarsWithDefault() { + context.putProperty("v1", "if"); + String textWithDefault = "Testing ${v1} variable substitution ${v2:-toto}"; + String resultWithDefault = "Testing if variable substitution toto"; + + String result = OptionHelper.substVars(textWithDefault, context); + assertEquals(resultWithDefault, result); + } + + @Test + public void testSubstVarsRecursive() { + context.putProperty("v1", "if"); + context.putProperty("v2", "${v3}"); + context.putProperty("v3", "works"); + + String result = OptionHelper.substVars(text, context); + assertEquals(expected, result); + } + + @Test + public void testSubstVarsTwoLevelsDeep() { + context.putProperty("v1", "if"); + context.putProperty("v2", "${v3}"); + context.putProperty("v3", "${v4}"); + context.putProperty("v4", "works"); + + String result = OptionHelper.substVars(text, context); + assertEquals(expected, result); + } + + @Test + public void testSubstVarsTwoLevelsWithDefault() { + // Example input taken from LOGBCK-943 bug report + context.putProperty("APP_NAME", "LOGBACK"); + context.putProperty("ARCHIVE_SUFFIX", "archive.log"); + context.putProperty("LOG_HOME", "${logfilepath.default:-logs}"); + context.putProperty("ARCHIVE_PATH", "${LOG_HOME}/archive/${APP_NAME}"); + + String result = OptionHelper.substVars("${ARCHIVE_PATH}_trace_${ARCHIVE_SUFFIX}", context); + assertEquals("logs/archive/LOGBACK_trace_archive.log", result); + } + + @Test(timeout = 1000) + public void stubstVarsShouldNotGoIntoInfiniteLoop() { + context.putProperty("v1", "if"); + context.putProperty("v2", "${v3}"); + context.putProperty("v3", "${v4}"); + context.putProperty("v4", "${v2}c"); + + expectedException.expect(Exception.class); + OptionHelper.substVars(text, context); + } + + @Test + public void nonCircularGraphShouldWork() { + context.putProperty("A", "${B} and ${C}"); + context.putProperty("B", "${B1}"); + context.putProperty("B1", "B1-value"); + context.putProperty("C", "${C1} and ${B}"); + context.putProperty("C1", "C1-value"); + + String result = OptionHelper.substVars("${A}", context); + assertEquals("B1-value and C1-value and B1-value", result); + } + + @Test(timeout = 1000) + public void detectCircularReferences0() { + context.putProperty("A", "${A}"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${A}]"); + OptionHelper.substVars("${A}", context); + } + + @Test(timeout = 1000) + public void detectCircularReferences1() { + context.putProperty("A", "${A}a"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${A}]"); + OptionHelper.substVars("${A}", context); + } + + @Test(timeout = 1000) + public void detectCircularReferences2() { + context.putProperty("A", "${B}"); + context.putProperty("B", "${C}"); + context.putProperty("C", "${A}"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${C} --> ${A}]"); + OptionHelper.substVars("${A}", context); + } + + @Test + public void detectCircularReferencesInDefault() { + context.putProperty("A", "${B:-${A}}"); + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${A}]"); + OptionHelper.substVars("${A}", context); + } + + @Test(timeout = 1000) + public void detectCircularReferences3() { + context.putProperty("A", "${B}"); + context.putProperty("B", "${C}"); + context.putProperty("C", "${A}"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${B} --> ${C} --> ${A} --> ${B}]"); + OptionHelper.substVars("${B} ", context); + } + + @Test(timeout = 1000) + public void detectCircularReferences4() { + context.putProperty("A", "${B}"); + context.putProperty("B", "${C}"); + context.putProperty("C", "${A}"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${C} --> ${A} --> ${B} --> ${C}]"); + OptionHelper.substVars("${C} and ${A}", context); + } + + @Test + public void detectCircularReferences5() { + context.putProperty("A", "${B} and ${C}"); + context.putProperty("B", "${B1}"); + context.putProperty("B1", "B1-value"); + context.putProperty("C", "${C1}"); + context.putProperty("C1", "here's the loop: ${A}"); + + expectedException.expect(IllegalArgumentException.class); + expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${C} --> ${C1} --> ${A}]"); + String result = OptionHelper.substVars("${A}", context); + System.err.println(result); + } + + @Test + public void defaultValueReferencingAVariable() { + context.putProperty("v1", "k1"); + String result = OptionHelper.substVars("${undef:-${v1}}", context); + assertEquals("k1", result); + } + + @Test + public void jackrabbit_standalone() { + String r = OptionHelper.substVars("${jackrabbit.log:-${repo:-jackrabbit}/log/jackrabbit.log}", context); + assertEquals("jackrabbit/log/jackrabbit.log", r); + } + + @Test + public void doesNotThrowNullPointerExceptionForEmptyVariable() throws JoranException { + context.putProperty("var", ""); + OptionHelper.substVars("${var}", context); -public class OptionHelperTest { - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - String text = "Testing ${v1} variable substitution ${v2}"; - String expected = "Testing if variable substitution works"; - Context context = new ContextBase(); - Map secondaryMap; - - - - @Before - public void setUp() throws Exception { - secondaryMap = new HashMap(); - } - - @Test - public void testLiteral() { - String noSubst = "hello world"; - String result = OptionHelper.substVars(noSubst, context); - assertEquals(noSubst, result); - } - - @Test - public void testUndefinedValues() { - String withUndefinedValues = "${axyz}"; - - String result = OptionHelper.substVars(withUndefinedValues, context); - assertEquals("axyz"+OptionHelper._IS_UNDEFINED, result); - } - - @Test - public void testSubstVarsVariableNotClosed() { - String noSubst = "testing if ${v1 works"; - - try { - @SuppressWarnings("unused") - String result = OptionHelper.substVars(noSubst, context); - fail(); - } catch (IllegalArgumentException e) { - //ok } - } - @Test - public void testSubstVarsContextOnly() { - context.putProperty("v1", "if"); - context.putProperty("v2", "works"); - - String result = OptionHelper.substVars(text, context); - assertEquals(expected, result); - } - - @Test - public void testSubstVarsSystemProperties() { - System.setProperty("v1", "if"); - System.setProperty("v2", "works"); - - String result = OptionHelper.substVars(text, context); - assertEquals(expected, result); - - System.clearProperty("v1"); - System.clearProperty("v2"); - } - - @Test - public void testSubstVarsWithDefault() { - context.putProperty("v1", "if"); - String textWithDefault = "Testing ${v1} variable substitution ${v2:-toto}"; - String resultWithDefault = "Testing if variable substitution toto"; - - String result = OptionHelper.substVars(textWithDefault, context); - assertEquals(resultWithDefault, result); - } - - @Test - public void testSubstVarsRecursive() { - context.putProperty("v1", "if"); - context.putProperty("v2", "${v3}"); - context.putProperty("v3", "works"); - - String result = OptionHelper.substVars(text, context); - assertEquals(expected, result); - } - - @Test - public void testSubstVarsTwoLevelsDeep() { - context.putProperty("v1", "if"); - context.putProperty("v2", "${v3}"); - context.putProperty("v3", "${v4}"); - context.putProperty("v4", "works"); - - String result = OptionHelper.substVars(text, context); - assertEquals(expected, result); - } - - @Test - public void testSubstVarsTwoLevelsWithDefault() { - // Example input taken from LOGBCK-943 bug report - context.putProperty("APP_NAME", "LOGBACK"); - context.putProperty("ARCHIVE_SUFFIX", "archive.log"); - context.putProperty("LOG_HOME", "${logfilepath.default:-logs}"); - context.putProperty("ARCHIVE_PATH", "${LOG_HOME}/archive/${APP_NAME}"); - - String result = OptionHelper.substVars("${ARCHIVE_PATH}_trace_${ARCHIVE_SUFFIX}", context); - assertEquals("logs/archive/LOGBACK_trace_archive.log", result); - } - - - @Test(timeout = 1000) - public void stubstVarsShouldNotGoIntoInfiniteLoop() { - context.putProperty("v1", "if"); - context.putProperty("v2", "${v3}"); - context.putProperty("v3", "${v4}"); - context.putProperty("v4", "${v2}c"); - - expectedException.expect(Exception.class); - OptionHelper.substVars(text, context); - } - - @Test - public void nonCircularGraphShouldWork() { - context.putProperty("A", "${B} and ${C}"); - context.putProperty("B", "${B1}"); - context.putProperty("B1", "B1-value"); - context.putProperty("C", "${C1} and ${B}"); - context.putProperty("C1", "C1-value"); - - String result = OptionHelper.substVars("${A}", context); - assertEquals("B1-value and C1-value and B1-value", result); - } - - @Test(timeout = 1000) - public void detectCircularReferences0() { - context.putProperty("A", "${A}"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${A}]"); - OptionHelper.substVars("${A}", context); - } - - @Test(timeout = 1000) - public void detectCircularReferences1() { - context.putProperty("A", "${A}a"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${A}]"); - OptionHelper.substVars("${A}", context); - } - - @Test(timeout = 1000) - public void detectCircularReferences2() { - context.putProperty("A", "${B}"); - context.putProperty("B", "${C}"); - context.putProperty("C", "${A}"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${C} --> ${A}]"); - OptionHelper.substVars("${A}", context); - } - - - @Test - public void detectCircularReferencesInDefault() { - context.putProperty("A", "${B:-${A}}"); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${B} --> ${A}]"); - OptionHelper.substVars("${A}", context); - } - - @Test(timeout = 1000) - public void detectCircularReferences3() { - context.putProperty("A", "${B}"); - context.putProperty("B", "${C}"); - context.putProperty("C", "${A}"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${B} --> ${C} --> ${A} --> ${B}]"); - OptionHelper.substVars("${B} ", context); - } - - @Test(timeout = 1000) - public void detectCircularReferences4() { - context.putProperty("A", "${B}"); - context.putProperty("B", "${C}"); - context.putProperty("C", "${A}"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${C} --> ${A} --> ${B} --> ${C}]"); - OptionHelper.substVars("${C} and ${A}", context); - } - - @Test - public void detectCircularReferences5() { - context.putProperty("A", "${B} and ${C}"); - context.putProperty("B", "${B1}"); - context.putProperty("B1", "B1-value"); - context.putProperty("C", "${C1}"); - context.putProperty("C1", "here's the loop: ${A}"); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${C} --> ${C1} --> ${A}]"); - String result = OptionHelper.substVars("${A}", context); - System.err.println(result); - } - - @Test - public void defaultValueReferencingAVariable() { - context.putProperty("v1", "k1"); - String result = OptionHelper.substVars("${undef:-${v1}}", context); - assertEquals("k1", result); - } - - @Test - public void jackrabbit_standalone() { - String r = OptionHelper.substVars("${jackrabbit.log:-${repo:-jackrabbit}/log/jackrabbit.log}", context); - assertEquals("jackrabbit/log/jackrabbit.log", r); - } - - @Test - public void doesNotThrowNullPointerExceptionForEmptyVariable() throws JoranException { - context.putProperty("var", ""); - OptionHelper.substVars("${var}", context); - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/PackageTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/PackageTest.java index 9f3e7a14df6a137b7c504ae76c2c00d629c75f67..6176f390e97f7893ae3d3b2f391c9077d88f8ad6 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/PackageTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/PackageTest.java @@ -18,14 +18,7 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ - DurationTest.class, - FileSizeTest.class, - FileUtilTest.class, - OptionHelperTest.class, - StatusPrinterTest.class, - TimeUtilTest.class, - ContentTypeUtilTest.class, - CharSequenceToRegexMapperTest.class}) +@SuiteClasses({ DurationTest.class, FileSizeTest.class, FileUtilTest.class, OptionHelperTest.class, StatusPrinterTest.class, TimeUtilTest.class, + ContentTypeUtilTest.class, CharSequenceToRegexMapperTest.class }) public class PackageTest { } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/ResilienceUtil.java b/logback-core/src/test/java/ch/qos/logback/core/util/ResilienceUtil.java index 50f36e61c86339527713015204de9b768232bb41..fb6e206a26d326a094c07f6bc8deb5e61cb3e6fe 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/ResilienceUtil.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/ResilienceUtil.java @@ -23,36 +23,35 @@ import java.util.regex.Pattern; public class ResilienceUtil { - - static public void verify(String logfile, String regexp, long totalSteps, double successRatioLowerBound) throws NumberFormatException, IOException { - FileReader fr = new FileReader(logfile); - BufferedReader br = new BufferedReader(fr); - Pattern p = Pattern.compile(regexp); - String line; - - int totalLines = 0; - int oldNum = -1; - int gaps = 0; - while ((line = br.readLine()) != null) { - Matcher m = p.matcher(line); - if (m.matches()) { - totalLines++; - String g = m.group(1); - int num = Integer.parseInt(g); - if(oldNum != -1 && num != oldNum+1) { - gaps++; + static public void verify(String logfile, String regexp, long totalSteps, double successRatioLowerBound) throws NumberFormatException, IOException { + FileReader fr = new FileReader(logfile); + BufferedReader br = new BufferedReader(fr); + Pattern p = Pattern.compile(regexp); + String line; + + int totalLines = 0; + int oldNum = -1; + int gaps = 0; + while ((line = br.readLine()) != null) { + Matcher m = p.matcher(line); + if (m.matches()) { + totalLines++; + String g = m.group(1); + int num = Integer.parseInt(g); + if (oldNum != -1 && num != oldNum + 1) { + gaps++; + } + oldNum = num; + } } - oldNum = num; - } + fr.close(); + br.close(); + + int lowerLimit = (int) (totalSteps * successRatioLowerBound); + assertTrue("totalLines=" + totalLines + " less than " + lowerLimit, totalLines > lowerLimit); + + // we want at least one gap indicating recuperation + assertTrue("gaps=" + gaps + " less than 1", gaps >= 1); + } - fr.close(); - br.close(); - - int lowerLimit = (int) (totalSteps*successRatioLowerBound); - assertTrue("totalLines="+totalLines+" less than "+lowerLimit, totalLines > lowerLimit); - - // we want at least one gap indicating recuperation - assertTrue("gaps="+gaps+" less than 1", gaps >= 1); - - } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/StatusListenerConfigHelperTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/StatusListenerConfigHelperTest.java index 2694f7840e5f4cd1918bd8120e32c7c167910e0b..868f77ec5e9b945df30f7442df060d8960a33328 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/StatusListenerConfigHelperTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/StatusListenerConfigHelperTest.java @@ -31,14 +31,14 @@ public class StatusListenerConfigHelperTest { public void addOnConsoleListenerInstanceShouldNotStartSecondListener() { OnConsoleStatusListener ocl0 = new OnConsoleStatusListener(); OnConsoleStatusListener ocl1 = new OnConsoleStatusListener(); - + StatusListenerConfigHelper.addOnConsoleListenerInstance(context, ocl0); { List listeners = sm.getCopyOfStatusListenerList(); assertEquals(1, listeners.size()); assertTrue(ocl0.isStarted()); } - + // second listener should not have been started StatusListenerConfigHelper.addOnConsoleListenerInstance(context, ocl1); { diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/StatusPrinterTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/StatusPrinterTest.java index f581c1498bfafb277546eac59ce549f492058df8..7afd6f16f65a491feb7d5aa288c1a3ca94819ea2 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/StatusPrinterTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/StatusPrinterTest.java @@ -31,90 +31,89 @@ import ch.qos.logback.core.status.WarnStatus; public class StatusPrinterTest { - ByteArrayOutputStream outputStream; - PrintStream ps; - - @Before - public void setUp() throws Exception { - outputStream = new ByteArrayOutputStream(); - ps = new PrintStream(outputStream); - StatusPrinter.setPrintStream(ps); - } - - @After - public void tearDown() throws Exception { - StatusPrinter.setPrintStream(System.out); - ps = null; - outputStream = null; - } - - @Test - public void testBasic() { - Context context = new ContextBase(); - context.getStatusManager().add(new InfoStatus("test", this)); - StatusPrinter.print(context); - String result = outputStream.toString(); - assertTrue(result.contains("|-INFO in "+this.getClass().getName())); - } - - @Test - public void testNested() { - Status s0 = new ErrorStatus("test0", this); - Status s1 = new InfoStatus("test1", this); - Status s11 = new InfoStatus("test11", this); - Status s12 = new InfoStatus("test12", this); - s1.add(s11); - s1.add(s12); - - Status s2 = new InfoStatus("test2", this); - Status s21 = new InfoStatus("test21", this); - Status s211 = new WarnStatus("test211", this); - - Status s22 = new InfoStatus("test22", this); - s2.add(s21); - s2.add(s22); - s21.add(s211); - - - Context context = new ContextBase(); - context.getStatusManager().add(s0); - context.getStatusManager().add(s1); - context.getStatusManager().add(s2); - - StatusPrinter.print(context); - String result = outputStream.toString(); - assertTrue(result.contains("+ INFO in "+this.getClass().getName())); - assertTrue(result.contains("+ WARN in "+this.getClass().getName())); - assertTrue(result.contains(" |-WARN in "+this.getClass().getName())); - } - - @Test - public void testWithException() { - Status s0 = new ErrorStatus("test0", this); - Status s1 = new InfoStatus("test1", this, new Exception("testEx")); - Status s11 = new InfoStatus("test11", this); - Status s12 = new InfoStatus("test12", this); - s1.add(s11); - s1.add(s12); - - Status s2 = new InfoStatus("test2", this); - Status s21 = new InfoStatus("test21", this); - Status s211 = new WarnStatus("test211", this); - - Status s22 = new InfoStatus("test22", this); - s2.add(s21); - s2.add(s22); - s21.add(s211); - - Context context = new ContextBase(); - context.getStatusManager().add(s0); - context.getStatusManager().add(s1); - context.getStatusManager().add(s2); - StatusPrinter.print(context); - String result = outputStream.toString(); - assertTrue(result.contains("|-ERROR in "+this.getClass().getName())); - assertTrue(result.contains("+ INFO in "+this.getClass().getName())); - assertTrue(result.contains("ch.qos.logback.core.util.StatusPrinterTest.testWithException")); - } - + ByteArrayOutputStream outputStream; + PrintStream ps; + + @Before + public void setUp() throws Exception { + outputStream = new ByteArrayOutputStream(); + ps = new PrintStream(outputStream); + StatusPrinter.setPrintStream(ps); + } + + @After + public void tearDown() throws Exception { + StatusPrinter.setPrintStream(System.out); + ps = null; + outputStream = null; + } + + @Test + public void testBasic() { + Context context = new ContextBase(); + context.getStatusManager().add(new InfoStatus("test", this)); + StatusPrinter.print(context); + String result = outputStream.toString(); + assertTrue(result.contains("|-INFO in " + this.getClass().getName())); + } + + @Test + public void testNested() { + Status s0 = new ErrorStatus("test0", this); + Status s1 = new InfoStatus("test1", this); + Status s11 = new InfoStatus("test11", this); + Status s12 = new InfoStatus("test12", this); + s1.add(s11); + s1.add(s12); + + Status s2 = new InfoStatus("test2", this); + Status s21 = new InfoStatus("test21", this); + Status s211 = new WarnStatus("test211", this); + + Status s22 = new InfoStatus("test22", this); + s2.add(s21); + s2.add(s22); + s21.add(s211); + + Context context = new ContextBase(); + context.getStatusManager().add(s0); + context.getStatusManager().add(s1); + context.getStatusManager().add(s2); + + StatusPrinter.print(context); + String result = outputStream.toString(); + assertTrue(result.contains("+ INFO in " + this.getClass().getName())); + assertTrue(result.contains("+ WARN in " + this.getClass().getName())); + assertTrue(result.contains(" |-WARN in " + this.getClass().getName())); + } + + @Test + public void testWithException() { + Status s0 = new ErrorStatus("test0", this); + Status s1 = new InfoStatus("test1", this, new Exception("testEx")); + Status s11 = new InfoStatus("test11", this); + Status s12 = new InfoStatus("test12", this); + s1.add(s11); + s1.add(s12); + + Status s2 = new InfoStatus("test2", this); + Status s21 = new InfoStatus("test21", this); + Status s211 = new WarnStatus("test211", this); + + Status s22 = new InfoStatus("test22", this); + s2.add(s21); + s2.add(s22); + s21.add(s211); + + Context context = new ContextBase(); + context.getStatusManager().add(s0); + context.getStatusManager().add(s1); + context.getStatusManager().add(s2); + StatusPrinter.print(context); + String result = outputStream.toString(); + assertTrue(result.contains("|-ERROR in " + this.getClass().getName())); + assertTrue(result.contains("+ INFO in " + this.getClass().getName())); + assertTrue(result.contains("ch.qos.logback.core.util.StatusPrinterTest.testWithException")); + } + } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/StringCollectionUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/StringCollectionUtilTest.java index e9d50468451feec82cf23fef4fd28da4463592bb..cdd087d1454bba7981d8b7bb33a1bf20616c7071 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/util/StringCollectionUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/StringCollectionUtilTest.java @@ -22,7 +22,6 @@ import java.util.List; import org.junit.Test; - /** * Unit tests for {@link StringCollectionUtil}. * @@ -30,53 +29,53 @@ import org.junit.Test; */ public class StringCollectionUtilTest { - @Test - public void testRetainMatchingWithNoPatterns() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.retainMatching(values); - assertTrue(values.contains("A")); - } + @Test + public void testRetainMatchingWithNoPatterns() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.retainMatching(values); + assertTrue(values.contains("A")); + } - @Test - public void testRetainMatchingWithMatchingPattern() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.retainMatching(values, "A"); - assertTrue(values.contains("A")); - } + @Test + public void testRetainMatchingWithMatchingPattern() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.retainMatching(values, "A"); + assertTrue(values.contains("A")); + } - @Test - public void testRetainMatchingWithNoMatchingPattern() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.retainMatching(values, "B"); - assertTrue(values.isEmpty()); - } + @Test + public void testRetainMatchingWithNoMatchingPattern() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.retainMatching(values, "B"); + assertTrue(values.isEmpty()); + } - @Test - public void testRemoveMatchingWithNoPatterns() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.removeMatching(values); - assertTrue(values.contains("A")); - } + @Test + public void testRemoveMatchingWithNoPatterns() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.removeMatching(values); + assertTrue(values.contains("A")); + } - @Test - public void testRemoveMatchingWithMatchingPattern() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.removeMatching(values, "A"); - assertTrue(values.isEmpty()); - } + @Test + public void testRemoveMatchingWithMatchingPattern() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.removeMatching(values, "A"); + assertTrue(values.isEmpty()); + } - @Test - public void testRemoveMatchingWithNoMatchingPattern() throws Exception { - Collection values = stringToList("A"); - StringCollectionUtil.removeMatching(values, "B"); - assertTrue(values.contains("A")); - } + @Test + public void testRemoveMatchingWithNoMatchingPattern() throws Exception { + Collection values = stringToList("A"); + StringCollectionUtil.removeMatching(values, "B"); + assertTrue(values.contains("A")); + } - @SuppressWarnings("unchecked") - private List stringToList(String... values) { - List result = new ArrayList(values.length); - result.addAll(Arrays.asList(values)); - return result; - } + @SuppressWarnings("unchecked") + private List stringToList(String... values) { + List result = new ArrayList(values.length); + result.addAll(Arrays.asList(values)); + return result; + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/TeeOutputStream.java b/logback-core/src/test/java/ch/qos/logback/core/util/TeeOutputStream.java index 1e95445bf4f7991d49f111acb09e810d5f61d837..776b45570861a7ac4415739bb53f156e9d4c64af 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/TeeOutputStream.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/TeeOutputStream.java @@ -27,26 +27,26 @@ import java.io.PrintStream; */ public class TeeOutputStream extends OutputStream { - final PrintStream targetPS; - public final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final PrintStream targetPS; + public final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - public TeeOutputStream(PrintStream targetPS) { - // allow for null arguments - this.targetPS = targetPS; - } + public TeeOutputStream(PrintStream targetPS) { + // allow for null arguments + this.targetPS = targetPS; + } - public void write(int b) throws IOException { - baos.write(b); - if(targetPS != null) { - targetPS.write(b); + public void write(int b) throws IOException { + baos.write(b); + if (targetPS != null) { + targetPS.write(b); + } } - } - public String toString() { - return baos.toString(); - } + public String toString() { + return baos.toString(); + } - public byte[] toByteArray() { - return baos.toByteArray(); - } + public byte[] toByteArray() { + return baos.toByteArray(); + } } diff --git a/logback-core/src/test/java/ch/qos/logback/core/util/TimeUtilTest.java b/logback-core/src/test/java/ch/qos/logback/core/util/TimeUtilTest.java index eeb34987cf8a1959e9b8731f975ecc7b9d31fd4a..47763a2768b4841755c4d42f3a2bb6763b5fa319 100644 --- a/logback-core/src/test/java/ch/qos/logback/core/util/TimeUtilTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/util/TimeUtilTest.java @@ -21,103 +21,101 @@ import java.util.TimeZone; import org.junit.Test; -public class TimeUtilTest { - - @Test - public void testSecond() { - // Mon Nov 20 18:05:17,522 CET 2006 - long now = 1164042317522L; - // Mon Nov 20 18:05:18,000 CET 2006 - long expected = 1164042318000L; - long computed = TimeUtil.computeStartOfNextSecond(now); - assertEquals(expected - now, 478); - assertEquals(expected, computed); - } - - @Test - public void testMinute() { - // Mon Nov 20 18:05:17,522 CET 2006 - long now = 1164042317522L; - // Mon Nov 20 18:06:00 CET 2006 - long expected = 1164042360000L; - - long computed = TimeUtil.computeStartOfNextMinute(now); - assertEquals(expected - now, 1000 * 42 + 478); - assertEquals(expected, computed); - } - - @Test - public void testHour() { - // Mon Nov 20 18:05:17,522 GMT 2006 - long now = 1164045917522L; - now = correctBasedOnTimeZone(now); - // Mon Nov 20 19:00:00 GMT 2006 - long expected = 1164049200000L; - expected = correctBasedOnTimeZone(expected); - - long computed = TimeUtil.computeStartOfNextHour(now); - assertEquals(expected - now, 1000 * (42 + 60 * 54) + 478); - assertEquals(expected, computed); - } - - @Test - public void testDay() { - // Mon Nov 20 18:05:17 GMT 2006 - long now = 1164045917522L; - now = correctBasedOnTimeZone(now); - // Tue Nov 21 00:00:00 GMT 2006 - long expected = 1164067200000L; - expected = correctBasedOnTimeZone(expected); - long computed = TimeUtil.computeStartOfNextDay(now); - - assertEquals(expected - now, 1000 * (3600 * 5 + 60 * 54 + 42) + 478); - assertEquals(expected, computed); - } - - @Test - public void testWeek() { - // Mon Nov 20 18:05:17 GMT 2006 - long now = 1164045917522L; - now = correctBasedOnTimeZone(now); - // Sun Nov 26 00:00:00 GMT 2006 - long expected = 1164499200000L; - expected = correctBasedOnTimeZone(expected); - - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(now)); - - int dayOffset = cal.getFirstDayOfWeek() - Calendar.SUNDAY; - if (dayOffset != 0) { - expected += 24L * 3600 * 1000 * (cal.getFirstDayOfWeek() - Calendar.SUNDAY); +public class TimeUtilTest { + + @Test + public void testSecond() { + // Mon Nov 20 18:05:17,522 CET 2006 + long now = 1164042317522L; + // Mon Nov 20 18:05:18,000 CET 2006 + long expected = 1164042318000L; + long computed = TimeUtil.computeStartOfNextSecond(now); + assertEquals(expected - now, 478); + assertEquals(expected, computed); + } + + @Test + public void testMinute() { + // Mon Nov 20 18:05:17,522 CET 2006 + long now = 1164042317522L; + // Mon Nov 20 18:06:00 CET 2006 + long expected = 1164042360000L; + + long computed = TimeUtil.computeStartOfNextMinute(now); + assertEquals(expected - now, 1000 * 42 + 478); + assertEquals(expected, computed); + } + + @Test + public void testHour() { + // Mon Nov 20 18:05:17,522 GMT 2006 + long now = 1164045917522L; + now = correctBasedOnTimeZone(now); + // Mon Nov 20 19:00:00 GMT 2006 + long expected = 1164049200000L; + expected = correctBasedOnTimeZone(expected); + + long computed = TimeUtil.computeStartOfNextHour(now); + assertEquals(expected - now, 1000 * (42 + 60 * 54) + 478); + assertEquals(expected, computed); + } + + @Test + public void testDay() { + // Mon Nov 20 18:05:17 GMT 2006 + long now = 1164045917522L; + now = correctBasedOnTimeZone(now); + // Tue Nov 21 00:00:00 GMT 2006 + long expected = 1164067200000L; + expected = correctBasedOnTimeZone(expected); + long computed = TimeUtil.computeStartOfNextDay(now); + + assertEquals(expected - now, 1000 * (3600 * 5 + 60 * 54 + 42) + 478); + assertEquals(expected, computed); } - long computed = TimeUtil.computeStartOfNextWeek(now); - // System.out.println("now "+new Date(now)); - // System.out.println("computed "+new Date(computed)); - // System.out.println("expected "+new Date(expected)); - assertEquals(expected - now, - 1000 * (3600 * (5 + 24 * (5 + dayOffset)) + 60 * 54 + 42) + 478); - assertEquals(expected, computed); - } - - @Test - public void testMonth() { - // Mon Nov 20 18:05:17 GMT 2006 - long now = 1164045917522L; - now = correctBasedOnTimeZone(now); - // Fri Dec 01 00:00:00 GMT 2006 - long expected = 1164931200000L; - expected = correctBasedOnTimeZone(expected); - - long computed = TimeUtil.computeStartOfNextMonth(now); - assertEquals(expected - now, - 1000 * (3600 * (5 + 24 * 10) + 60 * 54 + 42) + 478); - assertEquals(expected, computed); - } - - private long correctBasedOnTimeZone(long gmtLong) { - int offset = TimeZone.getDefault().getRawOffset(); - return gmtLong - offset; - } + @Test + public void testWeek() { + // Mon Nov 20 18:05:17 GMT 2006 + long now = 1164045917522L; + now = correctBasedOnTimeZone(now); + // Sun Nov 26 00:00:00 GMT 2006 + long expected = 1164499200000L; + expected = correctBasedOnTimeZone(expected); + + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date(now)); + + int dayOffset = cal.getFirstDayOfWeek() - Calendar.SUNDAY; + if (dayOffset != 0) { + expected += 24L * 3600 * 1000 * (cal.getFirstDayOfWeek() - Calendar.SUNDAY); + } + + long computed = TimeUtil.computeStartOfNextWeek(now); + // System.out.println("now "+new Date(now)); + // System.out.println("computed "+new Date(computed)); + // System.out.println("expected "+new Date(expected)); + assertEquals(expected - now, 1000 * (3600 * (5 + 24 * (5 + dayOffset)) + 60 * 54 + 42) + 478); + assertEquals(expected, computed); + } + + @Test + public void testMonth() { + // Mon Nov 20 18:05:17 GMT 2006 + long now = 1164045917522L; + now = correctBasedOnTimeZone(now); + // Fri Dec 01 00:00:00 GMT 2006 + long expected = 1164931200000L; + expected = correctBasedOnTimeZone(expected); + + long computed = TimeUtil.computeStartOfNextMonth(now); + assertEquals(expected - now, 1000 * (3600 * (5 + 24 * 10) + 60 * 54 + 42) + 478); + assertEquals(expected, computed); + } + + private long correctBasedOnTimeZone(long gmtLong) { + int offset = TimeZone.getDefault().getRawOffset(); + return gmtLong - offset; + } } diff --git a/logback-examples/src/main/java/chapters/appenders/ConfigurationTester.java b/logback-examples/src/main/java/chapters/appenders/ConfigurationTester.java index f20faf6a5c24ed7e6dbd7e137c75d50308bb0fee..f017c893548b9cd4ef73237b0a81d1624ab8184a 100644 --- a/logback-examples/src/main/java/chapters/appenders/ConfigurationTester.java +++ b/logback-examples/src/main/java/chapters/appenders/ConfigurationTester.java @@ -31,30 +31,30 @@ import chapters.appenders.sub.sample.Bar; */ public class ConfigurationTester { - public static void main(String[] args) throws InterruptedException { - Logger logger = (Logger) LoggerFactory.getLogger(ConfigurationTester.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) throws InterruptedException { + Logger logger = (Logger) LoggerFactory.getLogger(ConfigurationTester.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - je.printStackTrace(); - } - // After we've called Joran, let's print information about the - // internal status of logback - StatusPrinter.print(lc); + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + je.printStackTrace(); + } + // After we've called Joran, let's print information about the + // internal status of logback + StatusPrinter.print(lc); - logger.debug("**Hello {}", new Bar()); - MDC.put("testKey", "testValueFromMDC"); - MDC.put("testKey2", "value2"); - for (int i = 0; i < 10; i++) { - logger.debug("logging statement " + i); - Thread.sleep(100); + logger.debug("**Hello {}", new Bar()); + MDC.put("testKey", "testValueFromMDC"); + MDC.put("testKey2", "value2"); + for (int i = 0; i < 10; i++) { + logger.debug("logging statement " + i); + Thread.sleep(100); + } + Bar bar = new Bar(); + bar.createLoggingRequest(); } - Bar bar = new Bar(); - bar.createLoggingRequest(); - } } diff --git a/logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java b/logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java index 4b51f06bb2f6a1fc8918c337d6223b9676957b2a..d0d30ee03965f600ab5631f059da3656ea66f3f6 100755 --- a/logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java +++ b/logback-examples/src/main/java/chapters/appenders/CountingConsoleAppender.java @@ -19,55 +19,54 @@ import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; - public class CountingConsoleAppender extends AppenderBase { - static int DEFAULT_LIMIT = 10; - int counter = 0; - int limit = DEFAULT_LIMIT; - - PatternLayoutEncoder encoder; - - public void setLimit(int limit) { - this.limit = limit; - } + static int DEFAULT_LIMIT = 10; + int counter = 0; + int limit = DEFAULT_LIMIT; - public int getLimit() { - return limit; - } - - @Override - public void start() { - if (this.encoder == null) { - addError("No encoder set for the appender named ["+ name +"]."); - return; - } - - try { - encoder.init(System.out); - } catch (IOException e) { + PatternLayoutEncoder encoder; + + public void setLimit(int limit) { + this.limit = limit; } - super.start(); - } - public void append(ILoggingEvent event) { - if (counter >= limit) { - return; + public int getLimit() { + return limit; } - // output the events as formatted by the wrapped layout - try { - this.encoder.doEncode(event); - } catch (IOException e) { + + @Override + public void start() { + if (this.encoder == null) { + addError("No encoder set for the appender named [" + name + "]."); + return; + } + + try { + encoder.init(System.out); + } catch (IOException e) { + } + super.start(); } - // prepare for next event - counter++; - } + public void append(ILoggingEvent event) { + if (counter >= limit) { + return; + } + // output the events as formatted by the wrapped layout + try { + this.encoder.doEncode(event); + } catch (IOException e) { + } - public PatternLayoutEncoder getEncoder() { - return encoder; - } + // prepare for next event + counter++; + } + + public PatternLayoutEncoder getEncoder() { + return encoder; + } - public void setEncoder(PatternLayoutEncoder encoder) { - this.encoder = encoder; - } + public void setEncoder(PatternLayoutEncoder encoder) { + this.encoder = encoder; + } } diff --git a/logback-examples/src/main/java/chapters/appenders/IO.java b/logback-examples/src/main/java/chapters/appenders/IO.java index 49fedb9372a49a92d9f2ea6fdbf4de359274e436..0b24547ddfcd2737108ca013df3f3c6b8c66f4ed 100644 --- a/logback-examples/src/main/java/chapters/appenders/IO.java +++ b/logback-examples/src/main/java/chapters/appenders/IO.java @@ -22,160 +22,152 @@ import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.encoder.EchoEncoder; public class IO extends Thread { - static String msgLong = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; - static String msgShort = "Hello"; - static boolean scarceCPU; - static int numThreads; - static long l; - static boolean longMessage; - long len; - boolean buffered; - boolean immediateFlush; - Logger logger; - LoggerContext context; - double throughput; - - public IO(boolean _buffered, boolean _immediateFlush, long _len) { - this.len = _len; - this.buffered = _buffered; - this.immediateFlush = _immediateFlush; - context = new LoggerContext(); - logger = context.getLogger("logger-" + getName()); - - // A FileAppender is created according to the buffering and - // immediate flush setting of this IO instance. - FileAppender fa = new FileAppender(); - - if (longMessage) { - PatternLayoutEncoder pa = new PatternLayoutEncoder(); - pa.setPattern("%r %5p %c [%t] - %m%n"); - pa.setContext(context); - pa.start(); - fa.setEncoder(pa); - } else { - fa.setEncoder(new EchoEncoder()); + static String msgLong = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; + static String msgShort = "Hello"; + static boolean scarceCPU; + static int numThreads; + static long l; + static boolean longMessage; + long len; + boolean buffered; + boolean immediateFlush; + Logger logger; + LoggerContext context; + double throughput; + + public IO(boolean _buffered, boolean _immediateFlush, long _len) { + this.len = _len; + this.buffered = _buffered; + this.immediateFlush = _immediateFlush; + context = new LoggerContext(); + logger = context.getLogger("logger-" + getName()); + + // A FileAppender is created according to the buffering and + // immediate flush setting of this IO instance. + FileAppender fa = new FileAppender(); + + if (longMessage) { + PatternLayoutEncoder pa = new PatternLayoutEncoder(); + pa.setPattern("%r %5p %c [%t] - %m%n"); + pa.setContext(context); + pa.start(); + fa.setEncoder(pa); + } else { + fa.setEncoder(new EchoEncoder()); + } + + fa.setFile(getName() + ".log"); + fa.setAppend(false); + fa.setContext(context); + fa.start(); + } - fa.setFile(getName() + ".log"); - fa.setAppend(false); - fa.setContext(context); - fa.start(); - - } + public static void main(String[] argv) throws Exception { + if (argv.length != 4) { + usage("Wrong number of arguments."); + } - public static void main(String[] argv) throws Exception { - if (argv.length != 4) { - usage("Wrong number of arguments."); - } + l = Integer.parseInt(argv[0]); + numThreads = Integer.parseInt(argv[1]); + scarceCPU = "true".equalsIgnoreCase(argv[2]); + longMessage = "long".equalsIgnoreCase(argv[3]); - l = Integer.parseInt(argv[0]); - numThreads = Integer.parseInt(argv[1]); - scarceCPU = "true".equalsIgnoreCase(argv[2]); - longMessage = "long".equalsIgnoreCase(argv[3]); - - // ---------------------------------------------------- - // first test with unbuffered IO and immediate flushing - perfCase(false, true, l); - - // ---------------------------------------------------- - // Second test with unbuffered IO and no immediate flushing - perfCase(false, false, l); - - // ---------------------------------------------------- - // Third test with buffered IO and no immediate flushing - perfCase(true, false, l); - - // There is no fourth test as buffered IO and immediate flushing - // do not make sense. - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + IO.class.getName() + - " runLength numThreads scarceCPU (short|long)\n" + - " runLength (integer) the number of logs to generate perthread\n" + - " numThreads (integer) the number of threads.\n" + - " scarceCPU (boolean) if true an additional CPU intensive thread is created\n" + - " (short|long) length of log messages."); - System.exit(1); - } - - static void perfCase(boolean buffered, boolean immediateFlush, long len) - throws Exception { - IO[] threads = new IO[numThreads]; - Counter counterThread = null; - - if (scarceCPU) { - counterThread = new Counter(); - counterThread.start(); - } + // ---------------------------------------------------- + // first test with unbuffered IO and immediate flushing + perfCase(false, true, l); - // First create the threads - for (int i = 0; i < numThreads; i++) { - threads[i] = new IO(buffered, immediateFlush, len); - } + // ---------------------------------------------------- + // Second test with unbuffered IO and no immediate flushing + perfCase(false, false, l); - // then start them - for (int i = 0; i < numThreads; i++) { - threads[i].start(); - } + // ---------------------------------------------------- + // Third test with buffered IO and no immediate flushing + perfCase(true, false, l); - // wait for them to processPriorToRemoval, compute the average throughput - double sum = 0; + // There is no fourth test as buffered IO and immediate flushing + // do not make sense. + } - for (int i = 0; i < numThreads; i++) { - threads[i].join(); - sum += threads[i].throughput; + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + IO.class.getName() + " runLength numThreads scarceCPU (short|long)\n" + + " runLength (integer) the number of logs to generate perthread\n" + " numThreads (integer) the number of threads.\n" + + " scarceCPU (boolean) if true an additional CPU intensive thread is created\n" + " (short|long) length of log messages."); + System.exit(1); } - if (scarceCPU) { - // setting the interrupted field will cause counterThread to processPriorToRemoval - counterThread.interrupted = true; - counterThread.join(); + static void perfCase(boolean buffered, boolean immediateFlush, long len) throws Exception { + IO[] threads = new IO[numThreads]; + Counter counterThread = null; + + if (scarceCPU) { + counterThread = new Counter(); + counterThread.start(); + } + + // First create the threads + for (int i = 0; i < numThreads; i++) { + threads[i] = new IO(buffered, immediateFlush, len); + } + + // then start them + for (int i = 0; i < numThreads; i++) { + threads[i].start(); + } + + // wait for them to processPriorToRemoval, compute the average throughput + double sum = 0; + + for (int i = 0; i < numThreads; i++) { + threads[i].join(); + sum += threads[i].throughput; + } + + if (scarceCPU) { + // setting the interrupted field will cause counterThread to processPriorToRemoval + counterThread.interrupted = true; + counterThread.join(); + } + + System.out.println("On average throughput of " + (sum / numThreads) * 1000 + " logs per microsecond."); + System.out.println("------------------------------------------------"); } - System.out.println("On average throughput of " + (sum / numThreads)*1000 + - " logs per microsecond."); - System.out.println("------------------------------------------------"); - } + public void run() { + String msg = msgShort; - public void run() { - String msg = msgShort; + if (longMessage) { + msg = msgLong; + } - if (longMessage) { - msg = msgLong; - } + long before = System.nanoTime(); - long before = System.nanoTime(); + for (int i = 0; i < len; i++) { + logger.debug(msg); + } - for (int i = 0; i < len; i++) { - logger.debug(msg); + throughput = (len * 1.0) / (System.nanoTime() - before); + System.out.println(getName() + ", buffered: " + buffered + ", immediateFlush: " + immediateFlush + ", throughput: " + throughput + + " logs per nanosecond."); } - - throughput = (len * 1.0) / (System.nanoTime() - before); - System.out.println(getName() + ", buffered: " + buffered + - ", immediateFlush: " + immediateFlush + ", throughput: " + throughput + - " logs per nanosecond."); - } } - class Counter extends Thread { - public boolean interrupted = false; - public double counter = 0; + public boolean interrupted = false; + public double counter = 0; - public void run() { - long before = System.nanoTime(); + public void run() { + long before = System.nanoTime(); - while (!interrupted) { - if(counter % 1000 == 0) { - Thread.yield(); - } - counter += 1.0; - } + while (!interrupted) { + if (counter % 1000 == 0) { + Thread.yield(); + } + counter += 1.0; + } - double tput = (counter * 1.0) / (System.nanoTime() - before); - System.out.println("Counter thread " + getName() + - " incremented counter by " + tput + " per nanosecond."); - } + double tput = (counter * 1.0) / (System.nanoTime() - before); + System.out.println("Counter thread " + getName() + " incremented counter by " + tput + " per nanosecond."); + } } diff --git a/logback-examples/src/main/java/chapters/appenders/IOPerformance.java b/logback-examples/src/main/java/chapters/appenders/IOPerformance.java index f423370608b814811a0535480b435bf25a17681d..f813400a0ea76b941fc46f5fc690604d686e19f1 100644 --- a/logback-examples/src/main/java/chapters/appenders/IOPerformance.java +++ b/logback-examples/src/main/java/chapters/appenders/IOPerformance.java @@ -25,141 +25,136 @@ import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.util.StatusPrinter; public class IOPerformance extends Thread { - static String MSG = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; - static String LOG_FILE; - public static String PARALLEL_FILE; - - static int NUM_THREADS = 1; - static long l; - long len; - boolean immediateFlush; - Logger logger; - LoggerContext context; - double throughput; - - public IOPerformance(boolean _immediateFlush, long _len) { - this.len = _len; - this.immediateFlush = _immediateFlush; - context = new LoggerContext(); - logger = context.getLogger("logger-" + getName()); - - // A FileAppender is created according to the buffering and - // immediate flush setting of this IO instance. - FileAppender fa = new FileAppender(); - fa.setName("FILE"); - PatternLayoutEncoder pa = new PatternLayoutEncoder(); - pa.setPattern("%r %5p %c [%t] - %m%n"); - pa.setContext(context); - pa.start(); - fa.setEncoder(pa); - - fa.setFile(LOG_FILE); - fa.setAppend(true); - fa.setContext(context); - fa.start(); - - ((ch.qos.logback.classic.Logger) logger).addAppender(fa); - - StatusPrinter.print(context); - } - - public static void main(String[] argv) throws Exception { - if (argv.length != 3) { - usage("Wrong number of arguments."); + static String MSG = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890"; + static String LOG_FILE; + public static String PARALLEL_FILE; + + static int NUM_THREADS = 1; + static long l; + long len; + boolean immediateFlush; + Logger logger; + LoggerContext context; + double throughput; + + public IOPerformance(boolean _immediateFlush, long _len) { + this.len = _len; + this.immediateFlush = _immediateFlush; + context = new LoggerContext(); + logger = context.getLogger("logger-" + getName()); + + // A FileAppender is created according to the buffering and + // immediate flush setting of this IO instance. + FileAppender fa = new FileAppender(); + fa.setName("FILE"); + PatternLayoutEncoder pa = new PatternLayoutEncoder(); + pa.setPattern("%r %5p %c [%t] - %m%n"); + pa.setContext(context); + pa.start(); + fa.setEncoder(pa); + + fa.setFile(LOG_FILE); + fa.setAppend(true); + fa.setContext(context); + fa.start(); + + ((ch.qos.logback.classic.Logger) logger).addAppender(fa); + + StatusPrinter.print(context); } - l = Integer.parseInt(argv[0]); - LOG_FILE = argv[1]; - PARALLEL_FILE = argv[2]; - - // ---------------------------------------------------- - // first test with immediate flushing - perfCase(true, l); - - // ---------------------------------------------------- - // Second test with no immediate flushing - perfCase(false, l); - - // There is no fourth test as buffered IO and immediate flushing - // do not make sense. - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + IOPerformance.class.getName() - + " runLength logFile otherFile\n" - + " runLength (integer) the number of logs to generate perthread\n" - + " logFile path to a logFile\n" - + " otherFile path to a second file\n"); - System.exit(1); - } - - static void perfCase(boolean immediateFlush, long len) throws Exception { - IOPerformance[] threads = new IOPerformance[NUM_THREADS]; - OtherIO otherIOThread = new OtherIO(); - otherIOThread.start(); - - // First create the threads - for (int i = 0; i < NUM_THREADS; i++) { - threads[i] = new IOPerformance(immediateFlush, len); + public static void main(String[] argv) throws Exception { + if (argv.length != 3) { + usage("Wrong number of arguments."); + } + + l = Integer.parseInt(argv[0]); + LOG_FILE = argv[1]; + PARALLEL_FILE = argv[2]; + + // ---------------------------------------------------- + // first test with immediate flushing + perfCase(true, l); + + // ---------------------------------------------------- + // Second test with no immediate flushing + perfCase(false, l); + + // There is no fourth test as buffered IO and immediate flushing + // do not make sense. } - // then start them - for (int i = 0; i < NUM_THREADS; i++) { - threads[i].start(); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + IOPerformance.class.getName() + " runLength logFile otherFile\n" + + " runLength (integer) the number of logs to generate perthread\n" + " logFile path to a logFile\n" + + " otherFile path to a second file\n"); + System.exit(1); } - // wait for them to processPriorToRemoval, compute the average throughput - double sum = 0; + static void perfCase(boolean immediateFlush, long len) throws Exception { + IOPerformance[] threads = new IOPerformance[NUM_THREADS]; + OtherIO otherIOThread = new OtherIO(); + otherIOThread.start(); - for (int i = 0; i < NUM_THREADS; i++) { - threads[i].join(); - sum += threads[i].throughput; - } + // First create the threads + for (int i = 0; i < NUM_THREADS; i++) { + threads[i] = new IOPerformance(immediateFlush, len); + } - // setting the interrupted field will cause counterThread to processPriorToRemoval - otherIOThread.interrupted = true; - otherIOThread.join(); + // then start them + for (int i = 0; i < NUM_THREADS; i++) { + threads[i].start(); + } - System.out.println("On total throughput of " + (sum) - + " logs per microsecond."); - System.out.println("------------------------------------------------"); - } + // wait for them to processPriorToRemoval, compute the average throughput + double sum = 0; - public void run() { + for (int i = 0; i < NUM_THREADS; i++) { + threads[i].join(); + sum += threads[i].throughput; + } - long before = System.nanoTime(); + // setting the interrupted field will cause counterThread to processPriorToRemoval + otherIOThread.interrupted = true; + otherIOThread.join(); - for (int i = 0; i < len; i++) { - logger.debug(MSG); + System.out.println("On total throughput of " + (sum) + " logs per microsecond."); + System.out.println("------------------------------------------------"); } - throughput = (len * 1.0) / ((System.nanoTime() - before) / 1000); - System.out.println(getName() + ", immediateFlush: " + immediateFlush - + ", throughput: " + throughput + " logs per microsecond."); - } + public void run() { + + long before = System.nanoTime(); + + for (int i = 0; i < len; i++) { + logger.debug(MSG); + } + + throughput = (len * 1.0) / ((System.nanoTime() - before) / 1000); + System.out.println(getName() + ", immediateFlush: " + immediateFlush + ", throughput: " + throughput + " logs per microsecond."); + } } class OtherIO extends Thread { - public boolean interrupted = false; - public int counter = 0; - - public void run() { - long before = System.nanoTime(); - try { - FileWriter fw = new FileWriter(IOPerformance.PARALLEL_FILE, true); - - while (!interrupted) { - counter++; - fw.write("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); - fw.flush(); - } - } catch (IOException e) { - e.printStackTrace(); + public boolean interrupted = false; + public int counter = 0; + + public void run() { + long before = System.nanoTime(); + try { + FileWriter fw = new FileWriter(IOPerformance.PARALLEL_FILE, true); + + while (!interrupted) { + counter++; + fw.write("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + fw.flush(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + double tput = (counter * 1.0) / (System.nanoTime() - before); + System.out.println("Counter thread " + getName() + " incremented counter by " + tput + " per nanosecond."); } - - double tput = (counter * 1.0) / (System.nanoTime() - before); - System.out.println("Counter thread " + getName() - + " incremented counter by " + tput + " per nanosecond."); - } } diff --git a/logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java b/logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java index e36c84f4466176a33cac07d6f27e25671f22a821..b097e5f37df92ae8c355d018fdf711337b3e8f9b 100644 --- a/logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java +++ b/logback-examples/src/main/java/chapters/appenders/mail/CounterBasedEvaluator.java @@ -23,41 +23,40 @@ import ch.qos.logback.core.spi.ContextAwareBase; */ public class CounterBasedEvaluator extends ContextAwareBase implements EventEvaluator { - static int LIMIT = 1024; - int counter = 0; - String name; - boolean started; + static int LIMIT = 1024; + int counter = 0; + String name; + boolean started; - public boolean evaluate(Object event) throws NullPointerException, - EvaluationException { - counter++; + public boolean evaluate(Object event) throws NullPointerException, EvaluationException { + counter++; - if (counter == LIMIT) { - counter = 0; + if (counter == LIMIT) { + counter = 0; - return true; - } else { - return false; + return true; + } else { + return false; + } } - } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public boolean isStarted() { - return started; - } + public boolean isStarted() { + return started; + } - public void start() { - started = true; - } + public void start() { + started = true; + } - public void stop() { - started = false; - } + public void stop() { + started = false; + } } diff --git a/logback-examples/src/main/java/chapters/appenders/mail/EMail.java b/logback-examples/src/main/java/chapters/appenders/mail/EMail.java index dc918da6175d306f800d9885fe1de649e6640ffd..31b76edd417e132e025f1beaf23f7db6d03487a2 100644 --- a/logback-examples/src/main/java/chapters/appenders/mail/EMail.java +++ b/logback-examples/src/main/java/chapters/appenders/mail/EMail.java @@ -25,43 +25,39 @@ import ch.qos.logback.core.util.StatusPrinter; * user. * */ public class EMail { - static public void main(String[] args) throws Exception { - if (args.length != 2) { - usage("Wrong number of arguments."); - } + static public void main(String[] args) throws Exception { + if (args.length != 2) { + usage("Wrong number of arguments."); + } - int runLength = Integer.parseInt(args[0]); - String configFile = args[1]; + int runLength = Integer.parseInt(args[0]); + String configFile = args[1]; + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(configFile); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - - Logger logger = LoggerFactory.getLogger(EMail.class); + Logger logger = LoggerFactory.getLogger(EMail.class); - for (int i = 1; i <= runLength; i++) { - if ((i % 10) < 9) { - logger.debug("This is a debug message. Message number: " + i); - } else { - logger.warn("This is a warning message. Message number: " + i); - } - } + for (int i = 1; i <= runLength; i++) { + if ((i % 10) < 9) { + logger.debug("This is a debug message. Message number: " + i); + } else { + logger.warn("This is a warning message. Message number: " + i); + } + } - logger.error("At last an error.", new Exception("Just testing")); - - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - } + logger.error("At last an error.", new Exception("Just testing")); - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + EMail.class.getName() + - " runLength configFile\n" + - " runLength (integer) the number of logs to generate\n" + - " configFile a logback configuration file in XML format." + - " XML files must have a '.xml' extension."); - System.exit(1); - } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + } + + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + EMail.class.getName() + " runLength configFile\n" + " runLength (integer) the number of logs to generate\n" + + " configFile a logback configuration file in XML format." + " XML files must have a '.xml' extension."); + System.exit(1); + } } diff --git a/logback-examples/src/main/java/chapters/appenders/mail/Marked_EMail.java b/logback-examples/src/main/java/chapters/appenders/mail/Marked_EMail.java index 367cfbf471ade4eecb273663cb81d8f11e7a3e03..41bc75f0e32e19a3ca62208ec56dbb4151e47ed4 100644 --- a/logback-examples/src/main/java/chapters/appenders/mail/Marked_EMail.java +++ b/logback-examples/src/main/java/chapters/appenders/mail/Marked_EMail.java @@ -27,44 +27,40 @@ import ch.qos.logback.core.util.StatusPrinter; * However, only one message bears the "NOTIFY_ADMIN" marker. * */ public class Marked_EMail { - static public void main(String[] args) throws Exception { - if (args.length != 1) { - usage("Wrong number of arguments."); - } + static public void main(String[] args) throws Exception { + if (args.length != 1) { + usage("Wrong number of arguments."); + } - String configFile = args[0]; + String configFile = args[0]; - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - Logger logger = LoggerFactory.getLogger(Marked_EMail.class); + Logger logger = LoggerFactory.getLogger(Marked_EMail.class); - int runLength = 100; - for (int i = 1; i <= runLength; i++) { - if ((i % 10) < 9) { - logger.debug("This is a debug message. Message number: " + i); - } else { - logger.error("This is an error message. Message number: " + i); - } - } + int runLength = 100; + for (int i = 1; i <= runLength; i++) { + if ((i % 10) < 9) { + logger.debug("This is a debug message. Message number: " + i); + } else { + logger.error("This is an error message. Message number: " + i); + } + } - Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN"); - logger.error(notifyAdmin, - "This is a serious an error requiring the admin's attention", - new Exception("Just testing")); + Marker notifyAdmin = MarkerFactory.getMarker("NOTIFY_ADMIN"); + logger.error(notifyAdmin, "This is a serious an error requiring the admin's attention", new Exception("Just testing")); - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + } - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + Marked_EMail.class.getName() - + " configFile\n" - + " configFile a logback configuration file in XML format."); - System.exit(1); - } + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + Marked_EMail.class.getName() + " configFile\n" + " configFile a logback configuration file in XML format."); + System.exit(1); + } } diff --git a/logback-examples/src/main/java/chapters/appenders/sift/SiftExample.java b/logback-examples/src/main/java/chapters/appenders/sift/SiftExample.java index 45b710d5817bb159b18ea32c158698e8d5ca4d93..74b9a2cc0a12a356f4461d2dc2a272e4ba3cfe52 100644 --- a/logback-examples/src/main/java/chapters/appenders/sift/SiftExample.java +++ b/logback-examples/src/main/java/chapters/appenders/sift/SiftExample.java @@ -23,33 +23,31 @@ import ch.qos.logback.core.joran.spi.JoranException; public class SiftExample { - public static void main(String[] args) throws JoranException { - if (args.length != 1) { - usage("Wrong number of arguments."); + public static void main(String[] args) throws JoranException { + if (args.length != 1) { + usage("Wrong number of arguments."); + } + + String configFile = args[0]; + + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + + Logger logger = LoggerFactory.getLogger(SiftExample.class); + logger.debug("Application started"); + + MDC.put("userid", "Alice"); + logger.debug("Alice says hello"); + + // StatusPrinter.print(lc); } - String configFile = args[0]; - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - - - Logger logger = LoggerFactory.getLogger(SiftExample.class); - logger.debug("Application started"); - - MDC.put("userid", "Alice"); - logger.debug("Alice says hello"); - - //StatusPrinter.print(lc); - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SiftExample.class.getName() - + " configFile\n" + " configFile a logback configuration file"); - System.exit(1); - } + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SiftExample.class.getName() + " configFile\n" + " configFile a logback configuration file"); + System.exit(1); + } } diff --git a/logback-examples/src/main/java/chapters/appenders/socket/ConsolePluginClient.java b/logback-examples/src/main/java/chapters/appenders/socket/ConsolePluginClient.java index 8aabb05eebf5277534d36fe81b6c4e01ab8f007a..12d6ebb0f8f0346d74e32c0dbaa4e007b99fadef 100755 --- a/logback-examples/src/main/java/chapters/appenders/socket/ConsolePluginClient.java +++ b/logback-examples/src/main/java/chapters/appenders/socket/ConsolePluginClient.java @@ -30,94 +30,93 @@ import static org.slf4j.Logger.ROOT_LOGGER_NAME; */ public class ConsolePluginClient { - static String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lectus augue, pulvinar quis cursus nec, imperdiet nec ante. Cras sit amet arcu et enim adipiscing pellentesque. Suspendisse mi felis, dictum a lobortis nec, placerat in diam. Proin lobortis tortor at nunc facilisis aliquet. Praesent eget dignissim orci. Ut iaculis bibendum."; - - static String LOGGER_NAME = "com.acme.myapp.foo"; - static String UGLY_BETTY_LOGGER_NAME = "com.acme.myapp.UglyBetty"; - static long SLEEP = 1; - static long RUN_LENGTH = 200 * 1000; - - static public void main(String[] args) throws Exception { - // Create a SocketAppender connected to hostname:port with a - // reconnection delay of 10000 seconds. - String hostname = "localhost"; - int port = 4321; - SocketAppender socketAppender = new SocketAppender(); - socketAppender.setRemoteHost(hostname); - socketAppender.setPort(port); - socketAppender.setIncludeCallerData(true); + static String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lectus augue, pulvinar quis cursus nec, imperdiet nec ante. Cras sit amet arcu et enim adipiscing pellentesque. Suspendisse mi felis, dictum a lobortis nec, placerat in diam. Proin lobortis tortor at nunc facilisis aliquet. Praesent eget dignissim orci. Ut iaculis bibendum."; + + static String LOGGER_NAME = "com.acme.myapp.foo"; + static String UGLY_BETTY_LOGGER_NAME = "com.acme.myapp.UglyBetty"; + static long SLEEP = 1; + static long RUN_LENGTH = 200 * 1000; + + static public void main(String[] args) throws Exception { + // Create a SocketAppender connected to hostname:port with a + // reconnection delay of 10000 seconds. + String hostname = "localhost"; + int port = 4321; + SocketAppender socketAppender = new SocketAppender(); + socketAppender.setRemoteHost(hostname); + socketAppender.setPort(port); + socketAppender.setIncludeCallerData(true); socketAppender.setReconnectionDelay(new Duration(10000)); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - socketAppender.setContext(lc); - - lc.reset(); - - lc.getStatusManager().add(new OnConsoleStatusListener()); - // SocketAppender options become active only after the execution - // of the next statement. - socketAppender.start(); - - Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME); - rootLogger.addAppender(socketAppender); - - org.slf4j.Logger logger = LoggerFactory.getLogger(LOGGER_NAME); - - UglyBetty ub = new UglyBetty("ugly-betty-thread-234"); - ub.start(); - for (int i = 0; i < RUN_LENGTH; i++) { - if (i % 3 == 0) { - logger.warn(i + " is divisible by 3"); - } else { - toto(logger, i); - } - Thread.sleep(SLEEP); - } - ub.join(); - - StatusPrinter.print(lc); - } - - /** - * @param logger - * @param i - */ - /** - * @param logger - * @param i - */ - static void toto(org.slf4j.Logger logger, int i) { - logger.debug("this is message number " + i); - } - - static class UglyBetty extends Thread { - org.slf4j.Logger logger = LoggerFactory - .getLogger(UGLY_BETTY_LOGGER_NAME); - - public UglyBetty(String name) { - super(name); - } - - public void run() { - for (int i = 0; i < RUN_LENGTH; i++) { - if (i % 23 == 0) { - logger.warn(LONG_TEXT); - } else if (i % 47 == 0) { - logger.error("this is an exception", new Exception("test")); - } else { - count(logger, i); - } - try { - Thread.sleep(SLEEP); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - void count(org.slf4j.Logger logger, int i) { - logger.debug("Betty counts to " + i); - } - } + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + socketAppender.setContext(lc); + + lc.reset(); + + lc.getStatusManager().add(new OnConsoleStatusListener()); + // SocketAppender options become active only after the execution + // of the next statement. + socketAppender.start(); + + Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME); + rootLogger.addAppender(socketAppender); + + org.slf4j.Logger logger = LoggerFactory.getLogger(LOGGER_NAME); + + UglyBetty ub = new UglyBetty("ugly-betty-thread-234"); + ub.start(); + for (int i = 0; i < RUN_LENGTH; i++) { + if (i % 3 == 0) { + logger.warn(i + " is divisible by 3"); + } else { + toto(logger, i); + } + Thread.sleep(SLEEP); + } + ub.join(); + + StatusPrinter.print(lc); + } + + /** + * @param logger + * @param i + */ + /** + * @param logger + * @param i + */ + static void toto(org.slf4j.Logger logger, int i) { + logger.debug("this is message number " + i); + } + + static class UglyBetty extends Thread { + org.slf4j.Logger logger = LoggerFactory.getLogger(UGLY_BETTY_LOGGER_NAME); + + public UglyBetty(String name) { + super(name); + } + + public void run() { + for (int i = 0; i < RUN_LENGTH; i++) { + if (i % 23 == 0) { + logger.warn(LONG_TEXT); + } else if (i % 47 == 0) { + logger.error("this is an exception", new Exception("test")); + } else { + count(logger, i); + } + try { + Thread.sleep(SLEEP); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + void count(org.slf4j.Logger logger, int i) { + logger.debug("Betty counts to " + i); + } + } } diff --git a/logback-examples/src/main/java/chapters/appenders/socket/SocketClient1.java b/logback-examples/src/main/java/chapters/appenders/socket/SocketClient1.java index 4b8edf5d99dc73dc30550de293858d00a2898198..2ca8f1e045faf54ce00bea2330893823ec039551 100755 --- a/logback-examples/src/main/java/chapters/appenders/socket/SocketClient1.java +++ b/logback-examples/src/main/java/chapters/appenders/socket/SocketClient1.java @@ -13,7 +13,6 @@ */ package chapters.appenders.socket; - import java.io.BufferedReader; import java.io.InputStreamReader; @@ -24,58 +23,55 @@ import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.net.SocketAppender; - /** * This application uses a SocketAppender that log messages to a * server on a host and port specified by the user. It waits for the * user to type a message which will be sent to the server. * */ public class SocketClient1 { - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SocketClient1.class.getName() + - " hostname port\n" + " hostname the name of the remote log server\n" + - " port (integer) the port number of the server\n"); - System.exit(1); - } - - static public void main(String[] args) throws Exception { - if (args.length != 2) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SocketClient1.class.getName() + " hostname port\n" + " hostname the name of the remote log server\n" + + " port (integer) the port number of the server\n"); + System.exit(1); } - String hostName = args[0]; - int port = Integer.parseInt(args[1]); + static public void main(String[] args) throws Exception { + if (args.length != 2) { + usage("Wrong number of arguments."); + } + + String hostName = args[0]; + int port = Integer.parseInt(args[1]); - // Create a SocketAppender connected to hostname:port with a - // reconnection delay of 10000 seconds. - SocketAppender socketAppender = new SocketAppender(); - socketAppender.setRemoteHost(hostName); - socketAppender.setPort(port); - socketAppender.setReconnectionDelay(new Duration(10000)); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - socketAppender.setContext(lc); + // Create a SocketAppender connected to hostname:port with a + // reconnection delay of 10000 seconds. + SocketAppender socketAppender = new SocketAppender(); + socketAppender.setRemoteHost(hostName); + socketAppender.setPort(port); + socketAppender.setReconnectionDelay(new Duration(10000)); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + socketAppender.setContext(lc); - // SocketAppender options become active only after the execution - // of the next statement. - socketAppender.start(); + // SocketAppender options become active only after the execution + // of the next statement. + socketAppender.start(); - Logger logger = (Logger) LoggerFactory.getLogger(SocketClient1.class); - logger.addAppender(socketAppender); + Logger logger = (Logger) LoggerFactory.getLogger(SocketClient1.class); + logger.addAppender(socketAppender); - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - while (true) { - System.out.println("Type a message to send to log server at " + hostName + - ":" + port + ". Type 'q' to quit."); + while (true) { + System.out.println("Type a message to send to log server at " + hostName + ":" + port + ". Type 'q' to quit."); - String s = reader.readLine(); + String s = reader.readLine(); - if (s.equals("q")) { - break; - } else { - logger.debug(s); - } + if (s.equals("q")) { + break; + } else { + logger.debug(s); + } + } } - } } diff --git a/logback-examples/src/main/java/chapters/appenders/socket/SocketClient2.java b/logback-examples/src/main/java/chapters/appenders/socket/SocketClient2.java index 148ec2ae0b1815d1f87842ebc5914702335f4b73..7681f8909dfa8eaf9a602dea19e927eefe53ab71 100644 --- a/logback-examples/src/main/java/chapters/appenders/socket/SocketClient2.java +++ b/logback-examples/src/main/java/chapters/appenders/socket/SocketClient2.java @@ -22,52 +22,48 @@ import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; - /** * This application uses a SocketAppender that log messages to a * server on a host and port specified by the user. It waits for the * user to type a message which will be sent to the server. * */ public class SocketClient2 { - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + SocketClient2.class.getName() + - " configFile\n" + - " configFile a logback configuration file" + - " in XML format."); - System.exit(1); - } - - static public void main(String[] args) throws Exception { - if (args.length != 1) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + SocketClient2.class.getName() + " configFile\n" + " configFile a logback configuration file" + + " in XML format."); + System.exit(1); } - String configFile = args[0]; + static public void main(String[] args) throws Exception { + if (args.length != 1) { + usage("Wrong number of arguments."); + } - if (configFile.endsWith(".xml")) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - lc.stop(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - } + String configFile = args[0]; + + if (configFile.endsWith(".xml")) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + lc.stop(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + } - Logger logger = LoggerFactory.getLogger(SocketClient2.class); + Logger logger = LoggerFactory.getLogger(SocketClient2.class); - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - while (true) { - System.out.println( - "Type a message to send to log server. Type 'q' to quit."); + while (true) { + System.out.println("Type a message to send to log server. Type 'q' to quit."); - String s = reader.readLine(); + String s = reader.readLine(); - if (s.equals("q")) { - break; - } else { - logger.debug(s); - } + if (s.equals("q")) { + break; + } else { + logger.debug(s); + } + } } - } } diff --git a/logback-examples/src/main/java/chapters/appenders/sub/sample/Bar.java b/logback-examples/src/main/java/chapters/appenders/sub/sample/Bar.java index bb88a9e416ec105e930e81cc79b34d341f38df69..ee50aefe47c1286f1f56ea0a3a5a0fceb17510a8 100644 --- a/logback-examples/src/main/java/chapters/appenders/sub/sample/Bar.java +++ b/logback-examples/src/main/java/chapters/appenders/sub/sample/Bar.java @@ -17,18 +17,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Bar { - Logger logger = LoggerFactory.getLogger(Bar.class); - - public String toString() { - return "test 123"; - } - - public void createLoggingRequest() { - subMethodToCreateRequest(); - } - - //this is done to create a stacktrace of more than one line - private void subMethodToCreateRequest() { - logger.error("error-level request", new Exception("test exception")); - } + Logger logger = LoggerFactory.getLogger(Bar.class); + + public String toString() { + return "test 123"; + } + + public void createLoggingRequest() { + subMethodToCreateRequest(); + } + + // this is done to create a stacktrace of more than one line + private void subMethodToCreateRequest() { + logger.error("error-level request", new Exception("test exception")); + } } diff --git a/logback-examples/src/main/java/chapters/architecture/Bar.java b/logback-examples/src/main/java/chapters/architecture/Bar.java index 5e0124b11db25a510c0dc08bd4d675c0ca24a70e..5496083adb02a4703c5ff4f52d58dfb41b1116b9 100644 --- a/logback-examples/src/main/java/chapters/architecture/Bar.java +++ b/logback-examples/src/main/java/chapters/architecture/Bar.java @@ -17,9 +17,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; class Bar { - Logger logger = LoggerFactory.getLogger(Bar.class); + Logger logger = LoggerFactory.getLogger(Bar.class); - public void doIt() { - logger.debug("doing my job"); - } + public void doIt() { + logger.debug("doing my job"); + } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/architecture/MyAppWithConfigFile.java b/logback-examples/src/main/java/chapters/architecture/MyAppWithConfigFile.java index 98e175499049c024832151833e39fe264dbff7e6..0a90c842f634cf7a8f6db275ed2206444d7e4f9a 100644 --- a/logback-examples/src/main/java/chapters/architecture/MyAppWithConfigFile.java +++ b/logback-examples/src/main/java/chapters/architecture/MyAppWithConfigFile.java @@ -24,22 +24,22 @@ import ch.qos.logback.core.util.StatusPrinter; public class MyAppWithConfigFile { - public static void main(String[] args) { - Logger logger = LoggerFactory.getLogger(MyAppWithConfigFile.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger(MyAppWithConfigFile.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - StatusPrinter.print(lc.getStatusManager()); - } - logger.info("Entering application."); - Bar bar = new Bar(); - bar.doIt(); - logger.info("Exiting application."); + try { + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + StatusPrinter.print(lc.getStatusManager()); + } + logger.info("Entering application."); + Bar bar = new Bar(); + bar.doIt(); + logger.info("Exiting application."); - } + } } diff --git a/logback-examples/src/main/java/chapters/architecture/SelectionRule.java b/logback-examples/src/main/java/chapters/architecture/SelectionRule.java index 5c975a6ec9f86489bf0934ee07aad33394f474fd..b73eb5cac85fab3312337a67e4cd7b59bbe2d433 100644 --- a/logback-examples/src/main/java/chapters/architecture/SelectionRule.java +++ b/logback-examples/src/main/java/chapters/architecture/SelectionRule.java @@ -22,30 +22,30 @@ import org.slf4j.LoggerFactory; */ public class SelectionRule { - public static void main(String[] args) { - // get a logger instance named "com.foo". Let us further assume that the - // logger is of type ch.qos.logback.classic.Logger so that we can - // set its level - ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.foo"); - //set its Level to INFO. The setLevel() method requires a logback logger - logger.setLevel(Level.INFO); + public static void main(String[] args) { + // get a logger instance named "com.foo". Let us further assume that the + // logger is of type ch.qos.logback.classic.Logger so that we can + // set its level + ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.foo"); + // set its Level to INFO. The setLevel() method requires a logback logger + logger.setLevel(Level.INFO); - Logger barlogger = LoggerFactory.getLogger("com.foo.Bar"); + Logger barlogger = LoggerFactory.getLogger("com.foo.Bar"); - // This request is enabled, because WARN >= INFO - logger.warn("Low fuel level."); + // This request is enabled, because WARN >= INFO + logger.warn("Low fuel level."); - // This request is disabled, because DEBUG < INFO. - logger.debug("Starting search for nearest gas station."); + // This request is disabled, because DEBUG < INFO. + logger.debug("Starting search for nearest gas station."); - // The logger instance barlogger, named "com.foo.Bar", - // will inherit its level from the logger named - // "com.foo" Thus, the following request is enabled - // because INFO >= INFO. - barlogger.info("Located nearest gas station."); + // The logger instance barlogger, named "com.foo.Bar", + // will inherit its level from the logger named + // "com.foo" Thus, the following request is enabled + // because INFO >= INFO. + barlogger.info("Located nearest gas station."); - // This request is disabled, because DEBUG < INFO. - barlogger.debug("Exiting gas station search"); + // This request is disabled, because DEBUG < INFO. + barlogger.debug("Exiting gas station search"); - } + } } diff --git a/logback-examples/src/main/java/chapters/configuration/AddStatusListenerApp.java b/logback-examples/src/main/java/chapters/configuration/AddStatusListenerApp.java index 6e5d63a0ecc1957c3a8b79efb910f05218bb1a1a..85ef81e1e345186b8cd6c04b140e8e867a3efaa0 100644 --- a/logback-examples/src/main/java/chapters/configuration/AddStatusListenerApp.java +++ b/logback-examples/src/main/java/chapters/configuration/AddStatusListenerApp.java @@ -23,19 +23,18 @@ import ch.qos.logback.core.status.StatusManager; public class AddStatusListenerApp { - public static void main(String[] args) throws JoranException { - - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - StatusManager statusManager = lc.getStatusManager(); - OnConsoleStatusListener onConsoleListener = new OnConsoleStatusListener(); - statusManager.add(onConsoleListener); + public static void main(String[] args) throws JoranException { - Logger logger = LoggerFactory.getLogger("myApp"); - logger.info("Entering application."); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + StatusManager statusManager = lc.getStatusManager(); + OnConsoleStatusListener onConsoleListener = new OnConsoleStatusListener(); + statusManager.add(onConsoleListener); - Foo foo = new Foo(); - foo.doIt(); - logger.info("Exiting application."); - } + Logger logger = LoggerFactory.getLogger("myApp"); + logger.info("Entering application."); + + Foo foo = new Foo(); + foo.doIt(); + logger.info("Exiting application."); + } } diff --git a/logback-examples/src/main/java/chapters/configuration/Foo.java b/logback-examples/src/main/java/chapters/configuration/Foo.java index 24f7232679baaf9c972315301e595511ae122bd0..9eb16c97263e098e72fed8ba47532dc2cdace93d 100644 --- a/logback-examples/src/main/java/chapters/configuration/Foo.java +++ b/logback-examples/src/main/java/chapters/configuration/Foo.java @@ -16,11 +16,10 @@ package chapters.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class Foo { - static final Logger logger = LoggerFactory.getLogger(Foo.class); + static final Logger logger = LoggerFactory.getLogger(Foo.class); - public void doIt() { - logger.debug("Did it again!"); - } + public void doIt() { + logger.debug("Did it again!"); + } } diff --git a/logback-examples/src/main/java/chapters/configuration/MyApp1.java b/logback-examples/src/main/java/chapters/configuration/MyApp1.java index 57d7dbd19f77b23fb5a7a753881f651fba37ecf5..04cd399f2f388a7e94b7c504bca6d9452f932cc7 100644 --- a/logback-examples/src/main/java/chapters/configuration/MyApp1.java +++ b/logback-examples/src/main/java/chapters/configuration/MyApp1.java @@ -16,15 +16,14 @@ package chapters.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - public class MyApp1 { - final static Logger logger = LoggerFactory.getLogger(MyApp1.class); + final static Logger logger = LoggerFactory.getLogger(MyApp1.class); - public static void main(String[] args) { - logger.info("Entering application."); + public static void main(String[] args) { + logger.info("Entering application."); - Foo foo = new Foo(); - foo.doIt(); - logger.info("Exiting application."); - } + Foo foo = new Foo(); + foo.doIt(); + logger.info("Exiting application."); + } } diff --git a/logback-examples/src/main/java/chapters/configuration/MyApp2.java b/logback-examples/src/main/java/chapters/configuration/MyApp2.java index 8680b12e7900c46e4b96069f1981b188da0d9316..9ad01fb97f91934dc965c78bd46a9c5c8feed72f 100644 --- a/logback-examples/src/main/java/chapters/configuration/MyApp2.java +++ b/logback-examples/src/main/java/chapters/configuration/MyApp2.java @@ -20,17 +20,17 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.util.StatusPrinter; public class MyApp2 { - final static Logger logger = LoggerFactory.getLogger(MyApp2.class); + final static Logger logger = LoggerFactory.getLogger(MyApp2.class); - public static void main(String[] args) { - // assume SLF4J is bound to logback in the current environment - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - // print logback's internal status - StatusPrinter.print(lc); - - logger.info("Entering application."); - Foo foo = new Foo(); - foo.doIt(); - logger.info("Exiting application."); - } + public static void main(String[] args) { + // assume SLF4J is bound to logback in the current environment + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + // print logback's internal status + StatusPrinter.print(lc); + + logger.info("Entering application."); + Foo foo = new Foo(); + foo.doIt(); + logger.info("Exiting application."); + } } diff --git a/logback-examples/src/main/java/chapters/configuration/MyApp3.java b/logback-examples/src/main/java/chapters/configuration/MyApp3.java index 62a2c52e643999b3050f7bb98fb27c02b53bf7ac..8c87b418e671ba51e872a452b3f2159b81e3ebb5 100644 --- a/logback-examples/src/main/java/chapters/configuration/MyApp3.java +++ b/logback-examples/src/main/java/chapters/configuration/MyApp3.java @@ -26,28 +26,28 @@ import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; public class MyApp3 { - final static Logger logger = LoggerFactory.getLogger(MyApp3.class); + final static Logger logger = LoggerFactory.getLogger(MyApp3.class); - public static void main(String[] args) { - // assume SLF4J is bound to logback in the current environment - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) { + // assume SLF4J is bound to logback in the current environment + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(context); - // Call context.reset() to clear any previous configuration, e.g. default - // configuration. For multi-step configuration, omit calling context.reset(). - context.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - // StatusPrinter will handle this - } - StatusPrinter.printInCaseOfErrorsOrWarnings(context); + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(context); + // Call context.reset() to clear any previous configuration, e.g. default + // configuration. For multi-step configuration, omit calling context.reset(). + context.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + // StatusPrinter will handle this + } + StatusPrinter.printInCaseOfErrorsOrWarnings(context); - logger.info("Entering application."); + logger.info("Entering application."); - Foo foo = new Foo(); - foo.doIt(); - logger.info("Exiting application."); - } + Foo foo = new Foo(); + foo.doIt(); + logger.info("Exiting application."); + } } diff --git a/logback-examples/src/main/java/chapters/filters/FilterEvents.java b/logback-examples/src/main/java/chapters/filters/FilterEvents.java index 072fb8df8538c46555a1175791ba569e5c4d03eb..43d91d44ffb10b8ef438c38749e4af05492b4bcd 100644 --- a/logback-examples/src/main/java/chapters/filters/FilterEvents.java +++ b/logback-examples/src/main/java/chapters/filters/FilterEvents.java @@ -25,35 +25,35 @@ import ch.qos.logback.core.joran.spi.JoranException; public class FilterEvents { - public static void main(String[] args) throws InterruptedException { - if (args.length == 0) { - System.out.println("A configuration file must be passed as a parameter."); - return; - } - - Logger logger = (Logger) LoggerFactory.getLogger(FilterEvents.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) throws InterruptedException { + if (args.length == 0) { + System.out.println("A configuration file must be passed as a parameter."); + return; + } - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - je.printStackTrace(); - } - - for (int i = 0; i < 10; i++) { - if (i == 3) { - MDC.put("username", "sebastien"); - logger.debug("logging statement {}", i); - MDC.remove("username"); - } else if (i == 6) { - Marker billing = MarkerFactory.getMarker("billing"); - logger.error(billing, "billing statement {}", i); - } else { - logger.info("logging statement {}", i); - } + Logger logger = (Logger) LoggerFactory.getLogger(FilterEvents.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + je.printStackTrace(); + } + + for (int i = 0; i < 10; i++) { + if (i == 3) { + MDC.put("username", "sebastien"); + logger.debug("logging statement {}", i); + MDC.remove("username"); + } else if (i == 6) { + Marker billing = MarkerFactory.getMarker("billing"); + logger.error(billing, "billing statement {}", i); + } else { + logger.info("logging statement {}", i); + } + } } - } } diff --git a/logback-examples/src/main/java/chapters/filters/GoMDC.java b/logback-examples/src/main/java/chapters/filters/GoMDC.java index fe9becd5244848a5c954418a5fcb4eadc2618faa..4e6d1375936117f318351c6c34259da77dae860d 100644 --- a/logback-examples/src/main/java/chapters/filters/GoMDC.java +++ b/logback-examples/src/main/java/chapters/filters/GoMDC.java @@ -24,25 +24,24 @@ import ch.qos.logback.core.util.StatusPrinter; public class GoMDC { - public static void main(String[] args) { - Logger logger = LoggerFactory - .getLogger(GoMDC.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure("mdcFilter.xml"); - - } catch (JoranException je) { - StatusPrinter.print(lc); - } + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger(GoMDC.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure("mdcFilter.xml"); + + } catch (JoranException je) { + StatusPrinter.print(lc); + } - logger.debug("I know me " + 0); - MDC.put("key", "val"); - logger.debug("I know me " + 1); - - StatusPrinter.print(lc); - } + logger.debug("I know me " + 0); + MDC.put("key", "val"); + logger.debug("I know me " + 1); + + StatusPrinter.print(lc); + } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/filters/SampleFilter.java b/logback-examples/src/main/java/chapters/filters/SampleFilter.java index f77a8850b41277f079c20aad3896e4e9aa4e53ed..a08fcb3687aa8858aecbfb908777e60d1d8e0bc4 100644 --- a/logback-examples/src/main/java/chapters/filters/SampleFilter.java +++ b/logback-examples/src/main/java/chapters/filters/SampleFilter.java @@ -19,12 +19,12 @@ import ch.qos.logback.core.spi.FilterReply; public class SampleFilter extends Filter { - @Override - public FilterReply decide(ILoggingEvent event) { - if (event.getMessage() != null && event.getMessage().contains("sample")) { - return FilterReply.ACCEPT; - } else { - return FilterReply.NEUTRAL; + @Override + public FilterReply decide(ILoggingEvent event) { + if (event.getMessage() != null && event.getMessage().contains("sample")) { + return FilterReply.ACCEPT; + } else { + return FilterReply.NEUTRAL; + } } - } } diff --git a/logback-examples/src/main/java/chapters/filters/SampleTurboFilter.java b/logback-examples/src/main/java/chapters/filters/SampleTurboFilter.java index 1760c6e7a274c6ec0b930596762822a6f3d079d3..804efb6904422b88a4c4896e0ea8fda0289b548e 100644 --- a/logback-examples/src/main/java/chapters/filters/SampleTurboFilter.java +++ b/logback-examples/src/main/java/chapters/filters/SampleTurboFilter.java @@ -23,37 +23,36 @@ import ch.qos.logback.core.spi.FilterReply; public class SampleTurboFilter extends TurboFilter { - String marker; - Marker markerToAccept; - - @Override - public FilterReply decide(Marker marker, Logger logger, Level level, - String format, Object[] params, Throwable t) { - - if (!isStarted()) { - return FilterReply.NEUTRAL; - } + String marker; + Marker markerToAccept; + + @Override + public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) { + + if (!isStarted()) { + return FilterReply.NEUTRAL; + } - if ((markerToAccept.equals(marker))) { - return FilterReply.ACCEPT; - } else { - return FilterReply.NEUTRAL; + if ((markerToAccept.equals(marker))) { + return FilterReply.ACCEPT; + } else { + return FilterReply.NEUTRAL; + } } - } - public String getMarker() { - return marker; - } + public String getMarker() { + return marker; + } - public void setMarker(String markerStr) { - this.marker = markerStr; - } + public void setMarker(String markerStr) { + this.marker = markerStr; + } - @Override - public void start() { - if (marker != null && marker.trim().length() > 0) { - markerToAccept = MarkerFactory.getMarker(marker); - super.start(); + @Override + public void start() { + if (marker != null && marker.trim().length() > 0) { + markerToAccept = MarkerFactory.getMarker(marker); + super.start(); + } } - } } diff --git a/logback-examples/src/main/java/chapters/introduction/HelloWorld1.java b/logback-examples/src/main/java/chapters/introduction/HelloWorld1.java index e30c5df86ebd6fa91a3d308fedb9c421e092df99..d5c4bcf7c421c90fbbbb3edca03012972a454341 100644 --- a/logback-examples/src/main/java/chapters/introduction/HelloWorld1.java +++ b/logback-examples/src/main/java/chapters/introduction/HelloWorld1.java @@ -18,9 +18,9 @@ import org.slf4j.LoggerFactory; public class HelloWorld1 { - public static void main(String[] args) { + public static void main(String[] args) { - Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1"); - logger.debug("Hello world."); - } + Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1"); + logger.debug("Hello world."); + } } diff --git a/logback-examples/src/main/java/chapters/introduction/HelloWorld2.java b/logback-examples/src/main/java/chapters/introduction/HelloWorld2.java index 7cd5fb05e98eb8872910d898e2ae2c7754d87079..72a359d79ed3309fd2a2320b8cdcc84c16483359 100644 --- a/logback-examples/src/main/java/chapters/introduction/HelloWorld2.java +++ b/logback-examples/src/main/java/chapters/introduction/HelloWorld2.java @@ -20,12 +20,12 @@ import ch.qos.logback.core.util.StatusPrinter; public class HelloWorld2 { - public static void main(String[] args) { - Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2"); - logger.debug("Hello world."); + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2"); + logger.debug("Hello world."); - // print internal state - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - StatusPrinter.print(lc); - } + // print internal state + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + StatusPrinter.print(lc); + } } diff --git a/logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java b/logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java index c8db69324b3ca3b0833dceb3246c31d3bd76e8ad..5f1dec606a91927a23cd9aac57dd61fcaeb8570d 100644 --- a/logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java +++ b/logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java @@ -23,26 +23,26 @@ import ch.qos.logback.core.util.StatusPrinter; public class CallerEvaluatorExample { - public static void main(String[] args) { - Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - // StatusPrinter will handle this - } - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + // StatusPrinter will handle this + } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - for (int i = 0; i < 5; i++) { - if (i == 3) { - logger.debug("who calls thee?"); - } else { - logger.debug("I know me " + i); - } + for (int i = 0; i < 5; i++) { + if (i == 3) { + logger.debug("who calls thee?"); + } else { + logger.debug("I know me " + i); + } + } } - } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java b/logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java index b83ca62649afe8eb30e2ca73224154d2ca4b2014..45ae4a0814f6ad7d34faa92087ad15448c64b585 100644 --- a/logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java +++ b/logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java @@ -23,27 +23,26 @@ import ch.qos.logback.core.util.StatusPrinter; public class ExceptionEvaluatorExample { - public static void main(String[] args) { - Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + public static void main(String[] args) { + Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - // StatusPrinter will handle this - } - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - for (int i = 0; i < 3; i++) { - if (i == 1) { - logger.debug("logging statement " + i, new TestException( - "do not display this")); - } else { - logger.debug("logging statement " + i, new Exception("display")); - } + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + // StatusPrinter will handle this + } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + + for (int i = 0; i < 3; i++) { + if (i == 1) { + logger.debug("logging statement " + i, new TestException("do not display this")); + } else { + logger.debug("logging statement " + i, new Exception("display")); + } + } } - } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java b/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java index 6bf07984539c7fdcdb236a54bc93907236876dc9..d0724ccd4b5421ce229c3c7eec528ea6a2ba2aab 100644 --- a/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java +++ b/logback-examples/src/main/java/chapters/layouts/MySampleConverter.java @@ -19,11 +19,11 @@ import ch.qos.logback.classic.spi.ILoggingEvent; public class MySampleConverter extends ClassicConverter { - long start = System.nanoTime(); + long start = System.nanoTime(); - @Override - public String convert(ILoggingEvent event) { - long nowInNanos = System.nanoTime(); - return Long.toString(nowInNanos-start); - } + @Override + public String convert(ILoggingEvent event) { + long nowInNanos = System.nanoTime(); + return Long.toString(nowInNanos - start); + } } diff --git a/logback-examples/src/main/java/chapters/layouts/MySampleLayout.java b/logback-examples/src/main/java/chapters/layouts/MySampleLayout.java index 4bf35671225f6e1cdb6d557ad73b6278b644e832..2b7cc2436f7f412be196df7710996ab12da39e5a 100644 --- a/logback-examples/src/main/java/chapters/layouts/MySampleLayout.java +++ b/logback-examples/src/main/java/chapters/layouts/MySampleLayout.java @@ -17,20 +17,20 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.LayoutBase; -public class MySampleLayout extends LayoutBase { +public class MySampleLayout extends LayoutBase { - public String doLayout(ILoggingEvent event) { - StringBuilder sbuf = new StringBuilder(128); - sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); - sbuf.append(" "); - sbuf.append(event.getLevel()); - sbuf.append(" ["); - sbuf.append(event.getThreadName()); - sbuf.append("] "); - sbuf.append(event.getLoggerName()); - sbuf.append(" - "); - sbuf.append(event.getFormattedMessage()); - sbuf.append(CoreConstants.LINE_SEPARATOR); - return sbuf.toString(); - } + public String doLayout(ILoggingEvent event) { + StringBuilder sbuf = new StringBuilder(128); + sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); + sbuf.append(" "); + sbuf.append(event.getLevel()); + sbuf.append(" ["); + sbuf.append(event.getThreadName()); + sbuf.append("] "); + sbuf.append(event.getLoggerName()); + sbuf.append(" - "); + sbuf.append(event.getFormattedMessage()); + sbuf.append(CoreConstants.LINE_SEPARATOR); + return sbuf.toString(); + } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/layouts/MySampleLayout2.java b/logback-examples/src/main/java/chapters/layouts/MySampleLayout2.java index b0aebc805b270566628f2b4464da36baa295f2af..44e9c967890d5263acc223190670792c101ba8b3 100644 --- a/logback-examples/src/main/java/chapters/layouts/MySampleLayout2.java +++ b/logback-examples/src/main/java/chapters/layouts/MySampleLayout2.java @@ -19,36 +19,36 @@ import ch.qos.logback.core.LayoutBase; public class MySampleLayout2 extends LayoutBase { - String prefix = null; - boolean printThreadName = true; + String prefix = null; + boolean printThreadName = true; - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public void setPrintThreadName(boolean printThreadName) { - this.printThreadName = printThreadName; - } + public void setPrefix(String prefix) { + this.prefix = prefix; + } - public String doLayout(ILoggingEvent event) { - StringBuilder sbuf = new StringBuilder(128); - if (prefix != null) { - sbuf.append(prefix + ": "); + public void setPrintThreadName(boolean printThreadName) { + this.printThreadName = printThreadName; } - sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); - sbuf.append(" "); - sbuf.append(event.getLevel()); - if (printThreadName) { - sbuf.append(" ["); - sbuf.append(event.getThreadName()); - sbuf.append("] "); - } else { - sbuf.append(" "); + + public String doLayout(ILoggingEvent event) { + StringBuilder sbuf = new StringBuilder(128); + if (prefix != null) { + sbuf.append(prefix + ": "); + } + sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime()); + sbuf.append(" "); + sbuf.append(event.getLevel()); + if (printThreadName) { + sbuf.append(" ["); + sbuf.append(event.getThreadName()); + sbuf.append("] "); + } else { + sbuf.append(" "); + } + sbuf.append(event.getLoggerName()); + sbuf.append(" - "); + sbuf.append(event.getFormattedMessage()); + sbuf.append(CoreConstants.LINE_SEPARATOR); + return sbuf.toString(); } - sbuf.append(event.getLoggerName()); - sbuf.append(" - "); - sbuf.append(event.getFormattedMessage()); - sbuf.append(CoreConstants.LINE_SEPARATOR); - return sbuf.toString(); - } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/layouts/PatternSample.java b/logback-examples/src/main/java/chapters/layouts/PatternSample.java index 2e3e1e1af06229af04a8dfdb59cef2fd52eef932..1ae02774fffd465825491e280b304eeb4c8e763c 100644 --- a/logback-examples/src/main/java/chapters/layouts/PatternSample.java +++ b/logback-examples/src/main/java/chapters/layouts/PatternSample.java @@ -23,24 +23,24 @@ import ch.qos.logback.core.ConsoleAppender; public class PatternSample { - static public void main(String[] args) throws Exception { - Logger rootLogger = (Logger) LoggerFactory.getLogger("root"); - LoggerContext loggerContext = rootLogger.getLoggerContext(); - loggerContext.reset(); - - PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - encoder.setContext(loggerContext); - encoder.setPattern("%-5level [%thread]: %message%n"); - encoder.start(); - - ConsoleAppender appender = new ConsoleAppender(); - appender.setContext(loggerContext); - appender.setEncoder(encoder); - appender.start(); - - rootLogger.addAppender(appender); - - rootLogger.debug("Message 1"); - rootLogger.warn("Message 2"); - } + static public void main(String[] args) throws Exception { + Logger rootLogger = (Logger) LoggerFactory.getLogger("root"); + LoggerContext loggerContext = rootLogger.getLoggerContext(); + loggerContext.reset(); + + PatternLayoutEncoder encoder = new PatternLayoutEncoder(); + encoder.setContext(loggerContext); + encoder.setPattern("%-5level [%thread]: %message%n"); + encoder.start(); + + ConsoleAppender appender = new ConsoleAppender(); + appender.setContext(loggerContext); + appender.setEncoder(encoder); + appender.start(); + + rootLogger.addAppender(appender); + + rootLogger.debug("Message 1"); + rootLogger.warn("Message 2"); + } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/layouts/SampleLogging.java b/logback-examples/src/main/java/chapters/layouts/SampleLogging.java index 0ba0fa7682f921ff5d8b99cd3beb21780ee062a5..fcda49d880708ae86e6c755d26e9f687c5558556 100644 --- a/logback-examples/src/main/java/chapters/layouts/SampleLogging.java +++ b/logback-examples/src/main/java/chapters/layouts/SampleLogging.java @@ -23,23 +23,23 @@ import ch.qos.logback.core.util.StatusPrinter; public class SampleLogging { - public static void main(String[] args) { - - Logger logger = LoggerFactory.getLogger(SampleLogging.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - lc.reset(); - configurator.setContext(lc); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - // StatusPrinter will handle this + public static void main(String[] args) { + + Logger logger = LoggerFactory.getLogger(SampleLogging.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + try { + JoranConfigurator configurator = new JoranConfigurator(); + lc.reset(); + configurator.setContext(lc); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + // StatusPrinter will handle this + } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + + logger.debug("Everything's going well"); + logger.error("maybe not quite..."); } - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - logger.debug("Everything's going well"); - logger.error("maybe not quite..."); - } } diff --git a/logback-examples/src/main/java/chapters/layouts/TestException.java b/logback-examples/src/main/java/chapters/layouts/TestException.java index 7d3292a112e7d9f7858d34c24d5bfa4e16de81fb..bcc49f80bd1cbb5c4951bb14849b58a30d35ca87 100644 --- a/logback-examples/src/main/java/chapters/layouts/TestException.java +++ b/logback-examples/src/main/java/chapters/layouts/TestException.java @@ -15,9 +15,9 @@ package chapters.layouts; public class TestException extends Exception { - private static final long serialVersionUID = 8326547927308399902L; + private static final long serialVersionUID = 8326547927308399902L; - public TestException(String message) { - super(message); - } + public TestException(String message) { + super(message); + } } diff --git a/logback-examples/src/main/java/chapters/layouts/TrivialMain.java b/logback-examples/src/main/java/chapters/layouts/TrivialMain.java index 97193592b8ee8ffdab5109f7bc4938a00d41c0a0..88a3410d0c4cf3ce4ab90f3bc63adf493245fb3f 100644 --- a/logback-examples/src/main/java/chapters/layouts/TrivialMain.java +++ b/logback-examples/src/main/java/chapters/layouts/TrivialMain.java @@ -22,29 +22,29 @@ import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; public class TrivialMain { - public static void main(String[] args) throws InterruptedException { - Logger logger = LoggerFactory.getLogger(TrivialMain.class); - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - // StatusPrinter will handle this - } - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + public static void main(String[] args) throws InterruptedException { + Logger logger = LoggerFactory.getLogger(TrivialMain.class); + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + // StatusPrinter will handle this + } + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - for (int i = 0; i < 6; i++) { - if (i % 5 == 0) { - logger.warn("a warning message " + i); - } else if(i % 3 == 0) { - logger.info("hello world number" + i); - } else { - logger.debug("hello world number" + i); - } + for (int i = 0; i < 6; i++) { + if (i % 5 == 0) { + logger.warn("a warning message " + i); + } else if (i % 3 == 0) { + logger.info("hello world number" + i); + } else { + logger.debug("hello world number" + i); + } + } + logger.error("Finish off with fireworks", new Exception("Just testing")); } - logger.error("Finish off with fireworks", new Exception("Just testing")); - } } \ No newline at end of file diff --git a/logback-examples/src/main/java/chapters/mdc/NumberCruncher.java b/logback-examples/src/main/java/chapters/mdc/NumberCruncher.java index 028d17385f34acf851786d2fff837e62a85db068..ff72b65db4695bee165974eb5ee557666a848e30 100644 --- a/logback-examples/src/main/java/chapters/mdc/NumberCruncher.java +++ b/logback-examples/src/main/java/chapters/mdc/NumberCruncher.java @@ -16,14 +16,13 @@ package chapters.mdc; import java.rmi.Remote; import java.rmi.RemoteException; - /** * NumberCruncher factors positive integers. */ public interface NumberCruncher extends Remote { - /** - * Factor a positive integer number and return its - * distinct factor's as an integer array. - * */ - int[] factor(int number) throws RemoteException; + /** + * Factor a positive integer number and return its + * distinct factor's as an integer array. + * */ + int[] factor(int number) throws RemoteException; } diff --git a/logback-examples/src/main/java/chapters/mdc/NumberCruncherClient.java b/logback-examples/src/main/java/chapters/mdc/NumberCruncherClient.java index 64be492c8234924f5bd9cd1d9079a92b7574493d..a7167deaeb4ea7a7de4b07e05789c5697acd9af5 100644 --- a/logback-examples/src/main/java/chapters/mdc/NumberCruncherClient.java +++ b/logback-examples/src/main/java/chapters/mdc/NumberCruncherClient.java @@ -18,7 +18,6 @@ import java.io.InputStreamReader; import java.rmi.Naming; import java.rmi.RemoteException; - /** * NumberCruncherClient is a simple client for factoring integers. A * remote NumberCruncher is contacted and asked to factor an @@ -26,61 +25,60 @@ import java.rmi.RemoteException; * are displayed on the screen. * */ public class NumberCruncherClient { - public static void main(String[] args) { - if (args.length == 1) { - try { - String url = "rmi://" + args[0] + "/Factor"; - NumberCruncher nc = (NumberCruncher) Naming.lookup(url); - loop(nc); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - usage("Wrong number of arguments."); + public static void main(String[] args) { + if (args.length == 1) { + try { + String url = "rmi://" + args[0] + "/Factor"; + NumberCruncher nc = (NumberCruncher) Naming.lookup(url); + loop(nc); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + usage("Wrong number of arguments."); + } } - } - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java chapters.mdc.NumberCruncherClient HOST\n" + - " where HOST is the machine where the NumberCruncherServer is running."); - System.exit(1); - } + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java chapters.mdc.NumberCruncherClient HOST\n" + " where HOST is the machine where the NumberCruncherServer is running."); + System.exit(1); + } - static void loop(NumberCruncher nc) { - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - int i = 0; + static void loop(NumberCruncher nc) { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + int i = 0; - while (true) { - System.out.print("Enter a number to factor, '-1' to quit: "); + while (true) { + System.out.print("Enter a number to factor, '-1' to quit: "); - try { - i = Integer.parseInt(in.readLine()); - } catch (Exception e) { - e.printStackTrace(); - } + try { + i = Integer.parseInt(in.readLine()); + } catch (Exception e) { + e.printStackTrace(); + } - if (i == -1) { - System.out.print("Exiting loop."); + if (i == -1) { + System.out.print("Exiting loop."); - return; - } else { - try { - System.out.println("Will attempt to factor " + i); + return; + } else { + try { + System.out.println("Will attempt to factor " + i); - int[] factors = nc.factor(i); - System.out.print("The factors of " + i + " are"); + int[] factors = nc.factor(i); + System.out.print("The factors of " + i + " are"); - for (int k = 0; k < factors.length; k++) { - System.out.print(" " + factors[k]); - } + for (int k = 0; k < factors.length; k++) { + System.out.print(" " + factors[k]); + } - System.out.println("."); - } catch (RemoteException e) { - System.err.println("Could not factor " + i); - e.printStackTrace(); + System.out.println("."); + } catch (RemoteException e) { + System.err.println("Could not factor " + i); + e.printStackTrace(); + } + } } - } } - } } diff --git a/logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java b/logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java index 55753cbcd4f09c81c05bdfe9f7dd195db49d4b57..be58bc993078d84289d7f3bf8273e8ffa700ca9a 100644 --- a/logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java +++ b/logback-examples/src/main/java/chapters/mdc/NumberCruncherServer.java @@ -27,136 +27,132 @@ import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; - /** * A simple NumberCruncher implementation that logs its progress when * factoring numbers. The purpose of the whole exercise is to show the * use of mapped diagnostic contexts in order to distinguish the log * output from different client requests. * */ -public class NumberCruncherServer extends UnicastRemoteObject - implements NumberCruncher { - - private static final long serialVersionUID = 1L; - - static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class); - - public NumberCruncherServer() throws RemoteException { - } - - public int[] factor(int number) throws RemoteException { - // The client's host is an important source of information. - try { - MDC.put("client", NumberCruncherServer.getClientHost()); - } catch (java.rmi.server.ServerNotActiveException e) { - logger.warn("Caught unexpected ServerNotActiveException.", e); - } - - // The information contained within the request is another source - // of distinctive information. It might reveal the users name, - // date of request, request ID etc. In servlet type environments, - // useful information is contained in the HttpRequest or in the - // HttpSession. - MDC.put("number", String.valueOf(number)); - - logger.info("Beginning to factor."); - - if (number <= 0) { - throw new IllegalArgumentException(number + - " is not a positive integer."); - } else if (number == 1) { - return new int[] { 1 }; - } - - Vector factors = new Vector(); - int n = number; - - for (int i = 2; (i <= n) && ((i * i) <= number); i++) { - // It is bad practice to place log requests within tight loops. - // It is done here to show interleaved log output from - // different requests. - logger.debug("Trying " + i + " as a factor."); +public class NumberCruncherServer extends UnicastRemoteObject implements NumberCruncher { - if ((n % i) == 0) { - logger.info("Found factor " + i); - factors.addElement(i); + private static final long serialVersionUID = 1L; - do { - n /= i; - } while ((n % i) == 0); - } + static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class); - // Placing artificial delays in tight loops will also lead to - // sub-optimal resuts. :-) - delay(100); + public NumberCruncherServer() throws RemoteException { } - if (n != 1) { - logger.info("Found factor " + n); - factors.addElement(n); + public int[] factor(int number) throws RemoteException { + // The client's host is an important source of information. + try { + MDC.put("client", NumberCruncherServer.getClientHost()); + } catch (java.rmi.server.ServerNotActiveException e) { + logger.warn("Caught unexpected ServerNotActiveException.", e); + } + + // The information contained within the request is another source + // of distinctive information. It might reveal the users name, + // date of request, request ID etc. In servlet type environments, + // useful information is contained in the HttpRequest or in the + // HttpSession. + MDC.put("number", String.valueOf(number)); + + logger.info("Beginning to factor."); + + if (number <= 0) { + throw new IllegalArgumentException(number + " is not a positive integer."); + } else if (number == 1) { + return new int[] { 1 }; + } + + Vector factors = new Vector(); + int n = number; + + for (int i = 2; (i <= n) && ((i * i) <= number); i++) { + // It is bad practice to place log requests within tight loops. + // It is done here to show interleaved log output from + // different requests. + logger.debug("Trying " + i + " as a factor."); + + if ((n % i) == 0) { + logger.info("Found factor " + i); + factors.addElement(i); + + do { + n /= i; + } while ((n % i) == 0); + } + + // Placing artificial delays in tight loops will also lead to + // sub-optimal resuts. :-) + delay(100); + } + + if (n != 1) { + logger.info("Found factor " + n); + factors.addElement(n); + } + + int len = factors.size(); + + int[] result = new int[len]; + + for (int i = 0; i < len; i++) { + result[i] = ((Integer) factors.elementAt(i)).intValue(); + } + + // clean up + MDC.remove("client"); + MDC.remove("number"); + + return result; } - int len = factors.size(); - - int[] result = new int[len]; - - for (int i = 0; i < len; i++) { - result[i] = ((Integer) factors.elementAt(i)).intValue(); - } - - // clean up - MDC.remove("client"); - MDC.remove("number"); - - return result; - } - - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" + - " where configFile is a logback configuration file."); - System.exit(1); - } - - public static void delay(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } - - public static void main(String[] args) { - if (args.length != 1) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" + " where configFile is a logback configuration file."); + System.exit(1); } - String configFile = args[0]; - - if (configFile.endsWith(".xml")) { - try { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure(args[0]); - } catch (JoranException je) { - je.printStackTrace(); - } + public static void delay(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + } } - NumberCruncherServer ncs; - - try { - ncs = new NumberCruncherServer(); - logger.info("Creating registry."); - - Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); - registry.rebind("Factor", ncs); - logger.info("NumberCruncherServer bound and ready."); - } catch (Exception e) { - logger.error("Could not bind NumberCruncherServer.", e); - - return; + public static void main(String[] args) { + if (args.length != 1) { + usage("Wrong number of arguments."); + } + + String configFile = args[0]; + + if (configFile.endsWith(".xml")) { + try { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(args[0]); + } catch (JoranException je) { + je.printStackTrace(); + } + } + + NumberCruncherServer ncs; + + try { + ncs = new NumberCruncherServer(); + logger.info("Creating registry."); + + Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); + registry.rebind("Factor", ncs); + logger.info("NumberCruncherServer bound and ready."); + } catch (Exception e) { + logger.error("Could not bind NumberCruncherServer.", e); + + return; + } } - } } diff --git a/logback-examples/src/main/java/chapters/mdc/SimpleMDC.java b/logback-examples/src/main/java/chapters/mdc/SimpleMDC.java index 0b3b16b2416ba6a8e68a64c94de08ba2ad4c583e..8f3734e5a475e56df133d544a9b61167fdd80f14 100644 --- a/logback-examples/src/main/java/chapters/mdc/SimpleMDC.java +++ b/logback-examples/src/main/java/chapters/mdc/SimpleMDC.java @@ -29,66 +29,64 @@ import ch.qos.logback.core.util.Loader; import ch.qos.logback.core.util.StatusPrinter; public class SimpleMDC { - static public void main(String[] args) throws Exception { - // You can put values in the MDC at any time. Before anything else - // we put the first name - MDC.put("first", "Dorothy"); + static public void main(String[] args) throws Exception { + // You can put values in the MDC at any time. Before anything else + // we put the first name + MDC.put("first", "Dorothy"); - // configure via the configuration file "chapters/mdc/simpleMDC.xml" - // which ships with the examples - configureViaXML_File(); - - // For educational purposes, the same configuration can - // be accomplished programmatically. - // - // programmaticConfiguration(); - - Logger logger = LoggerFactory.getLogger(SimpleMDC.class); - // We now put the last name - MDC.put("last", "Parker"); + // configure via the configuration file "chapters/mdc/simpleMDC.xml" + // which ships with the examples + configureViaXML_File(); - // The most beautiful two words in the English language according - // to Dorothy Parker: - logger.info("Check enclosed."); - logger.debug("The most beautiful two words in English."); + // For educational purposes, the same configuration can + // be accomplished programmatically. + // + // programmaticConfiguration(); - MDC.put("first", "Richard"); - MDC.put("last", "Nixon"); - logger.info("I am not a crook."); - logger.info("Attributed to the former US president. 17 Nov 1973."); - } + Logger logger = LoggerFactory.getLogger(SimpleMDC.class); + // We now put the last name + MDC.put("last", "Parker"); - static void programmaticConfiguration() { - // Configure logback - LoggerContext loggerContext = (LoggerContext) LoggerFactory - .getILoggerFactory(); - loggerContext.reset(); - PatternLayoutEncoder layout = new PatternLayoutEncoder(); - layout.setContext(loggerContext); - layout.setPattern("%X{first} %X{last} - %m%n"); - layout.start(); - ConsoleAppender appender = new ConsoleAppender(); - appender.setContext(loggerContext); - appender.setEncoder(layout); - appender.start(); - // cast root logger to c.q.logback.classic.Logger so that we can attach - // an appender to it - ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger("root"); - root.addAppender(appender); - } + // The most beautiful two words in the English language according + // to Dorothy Parker: + logger.info("Check enclosed."); + logger.debug("The most beautiful two words in English."); - static void configureViaXML_File() { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - URL url = Loader.getResourceBySelfClassLoader("chapters/mdc/simpleMDC.xml"); - configurator.doConfigure(url); - } catch (JoranException je) { - StatusPrinter.print(lc); + MDC.put("first", "Richard"); + MDC.put("last", "Nixon"); + logger.info("I am not a crook."); + logger.info("Attributed to the former US president. 17 Nov 1973."); + } + + static void programmaticConfiguration() { + // Configure logback + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + loggerContext.reset(); + PatternLayoutEncoder layout = new PatternLayoutEncoder(); + layout.setContext(loggerContext); + layout.setPattern("%X{first} %X{last} - %m%n"); + layout.start(); + ConsoleAppender appender = new ConsoleAppender(); + appender.setContext(loggerContext); + appender.setEncoder(layout); + appender.start(); + // cast root logger to c.q.logback.classic.Logger so that we can attach + // an appender to it + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("root"); + root.addAppender(appender); + } + + static void configureViaXML_File() { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + try { + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + URL url = Loader.getResourceBySelfClassLoader("chapters/mdc/simpleMDC.xml"); + configurator.doConfigure(url); + } catch (JoranException je) { + StatusPrinter.print(lc); + } } - } } diff --git a/logback-examples/src/main/java/chapters/mdc/UserServletFilter.java b/logback-examples/src/main/java/chapters/mdc/UserServletFilter.java index bc82d1478683acaf03bdae816d36bfda5c9c9ce3..8d96661b8c96d6efefc2f87bae46318a24bdc227 100644 --- a/logback-examples/src/main/java/chapters/mdc/UserServletFilter.java +++ b/logback-examples/src/main/java/chapters/mdc/UserServletFilter.java @@ -37,49 +37,48 @@ import org.slf4j.MDC; */ public class UserServletFilter implements Filter { - private final String USER_KEY = "username"; - - public void destroy() { - } + private final String USER_KEY = "username"; - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + public void destroy() { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + + boolean successfulRegistration = false; + HttpServletRequest req = (HttpServletRequest) request; + Principal principal = req.getUserPrincipal(); + // Please note that we also could have used a cookie to + // retrieve the user name - boolean successfulRegistration = false; - HttpServletRequest req = (HttpServletRequest) request; - Principal principal = req.getUserPrincipal(); - // Please note that we also could have used a cookie to - // retrieve the user name - - if (principal != null) { - String username = principal.getName(); - successfulRegistration = registerUsername(username); + if (principal != null) { + String username = principal.getName(); + successfulRegistration = registerUsername(username); + } + + try { + chain.doFilter(request, response); + } finally { + if (successfulRegistration) { + MDC.remove(USER_KEY); + } + } } - - try { - chain.doFilter(request, response); - } finally { - if (successfulRegistration) { - MDC.remove(USER_KEY); - } + + public void init(FilterConfig arg0) throws ServletException { } - } - public void init(FilterConfig arg0) throws ServletException { - } - - /** - * Register the user in the MDC under USER_KEY. - * - * @param username - * @return true id the user can be successfully registered - */ - private boolean registerUsername(String username) { - if (username != null && username.trim().length() > 0) { - MDC.put(USER_KEY, username); - return true; + /** + * Register the user in the MDC under USER_KEY. + * + * @param username + * @return true id the user can be successfully registered + */ + private boolean registerUsername(String username) { + if (username != null && username.trim().length() > 0) { + MDC.put(USER_KEY, username); + return true; + } + return false; } - return false; - } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/Log4jMain.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/Log4jMain.java index 7e859b769a2fde98adafa49cbe19f9afad2519da..cf031e4dc2fccd49cb75e8be4706b7d445cbf6a6 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/Log4jMain.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/Log4jMain.java @@ -24,11 +24,11 @@ import org.apache.log4j.PropertyConfigurator; */ public class Log4jMain { - static Logger logger = Logger.getLogger(Log4jMain.class); + static Logger logger = Logger.getLogger(Log4jMain.class); - public static void main(String[] args) { - PropertyConfigurator.configure("src/main/java/chapters/migrationFromLog4j/log4jTrivial.properties"); - logger.debug("Hello world"); - } + public static void main(String[] args) { + PropertyConfigurator.configure("src/main/java/chapters/migrationFromLog4j/log4jTrivial.properties"); + logger.debug("Hello world"); + } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/LogbackMain.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/LogbackMain.java index 0bee962f599a6f7d6acf547490afc5c03ecfebed..ee469d3b98ebadae2108db7be26e913697004c4d 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/LogbackMain.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/LogbackMain.java @@ -30,19 +30,18 @@ import ch.qos.logback.core.util.StatusPrinter; */ public class LogbackMain { - static Logger logger = LoggerFactory.getLogger(LogbackMain.class); - - public static void main(String[] args) throws JoranException { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - lc.reset(); - configurator.doConfigure("src/main/java/chapters/migrationFromLog4j/logback-trivial.xml"); - StatusPrinter.printInCaseOfErrorsOrWarnings(lc); - - - logger.debug("Hello world"); - } + static Logger logger = LoggerFactory.getLogger(LogbackMain.class); + + public static void main(String[] args) throws JoranException { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure("src/main/java/chapters/migrationFromLog4j/logback-trivial.xml"); + StatusPrinter.printInCaseOfErrorsOrWarnings(lc); + + logger.debug("Hello world"); + } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jAppender.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jAppender.java index 67a4868d0eb95c2eb21c0b3efb7b5b1f839abbce..6fb2ae0389d44cf95cda4c488a189138d29248e6 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jAppender.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jAppender.java @@ -18,17 +18,17 @@ import org.apache.log4j.spi.LoggingEvent; public class TrivialLog4jAppender extends AppenderSkeleton { - protected void append(LoggingEvent loggingevent) { - String s = this.layout.format(loggingevent); - System.out.println(s); - } + protected void append(LoggingEvent loggingevent) { + String s = this.layout.format(loggingevent); + System.out.println(s); + } - public void close() { - // nothing to do - } + public void close() { + // nothing to do + } - public boolean requiresLayout() { - return true; - } + public boolean requiresLayout() { + return true; + } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jLayout.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jLayout.java index c5a6137aead2a964492c389e02bcd89f4edc0b0d..a6546cf5f9b0624b46539dc8f4588f3b3defd7d1 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jLayout.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLog4jLayout.java @@ -16,7 +16,6 @@ package chapters.migrationFromLog4j; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; - /** * * A very simple log4j layout which formats a logging event @@ -27,17 +26,17 @@ import org.apache.log4j.spi.LoggingEvent; */ public class TrivialLog4jLayout extends Layout { - public void activateOptions() { - // there are no options to activate - } + public void activateOptions() { + // there are no options to activate + } - public String format(LoggingEvent loggingEvent) { - return loggingEvent.getRenderedMessage(); - } + public String format(LoggingEvent loggingEvent) { + return loggingEvent.getRenderedMessage(); + } - @Override - public boolean ignoresThrowable() { - return true; - } + @Override + public boolean ignoresThrowable() { + return true; + } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackAppender.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackAppender.java index 7dcfc641b4c4318cde4f4559b9d852031e92da8e..95443e4737edc778b0180c26de3e5e81b085ef46 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackAppender.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackAppender.java @@ -21,40 +21,40 @@ import ch.qos.logback.core.AppenderBase; public class TrivialLogbackAppender extends AppenderBase { - PatternLayoutEncoder encoder; - - public PatternLayoutEncoder getEncoder() { - return encoder; - } - - public void setEncoder(PatternLayoutEncoder encoder) { - this.encoder = encoder; - } - - @Override - public void start() { - if (this.encoder == null) { - addError("No encoder set for the appender named [" + name + "]."); - return; + PatternLayoutEncoder encoder; + + public PatternLayoutEncoder getEncoder() { + return encoder; } - try { - encoder.init(System.out); - } catch (IOException e) { + + public void setEncoder(PatternLayoutEncoder encoder) { + this.encoder = encoder; } - super.start(); - } - - @Override - protected void append(ILoggingEvent loggingevent) { - // note that AppenderBase.doAppend will invoke this method only if - // this appender was successfully started. - try { - this.encoder.doEncode(loggingevent); - } catch (IOException e) { - // we can't do much with the exception except halting - super.stop(); - addError("Failed to write to the console"); + + @Override + public void start() { + if (this.encoder == null) { + addError("No encoder set for the appender named [" + name + "]."); + return; + } + try { + encoder.init(System.out); + } catch (IOException e) { + } + super.start(); + } + + @Override + protected void append(ILoggingEvent loggingevent) { + // note that AppenderBase.doAppend will invoke this method only if + // this appender was successfully started. + try { + this.encoder.doEncode(loggingevent); + } catch (IOException e) { + // we can't do much with the exception except halting + super.stop(); + addError("Failed to write to the console"); + } } - } } diff --git a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackLayout.java b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackLayout.java index e86004abdc5a5872789acf2b6bb370e0879d896b..ef04d481c62962f0a251cf705c54b0cdc6873e1e 100644 --- a/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackLayout.java +++ b/logback-examples/src/main/java/chapters/migrationFromLog4j/TrivialLogbackLayout.java @@ -16,7 +16,6 @@ package chapters.migrationFromLog4j; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.LayoutBase; - /** * * A very simple logback-classic layout which formats a logging event @@ -27,7 +26,7 @@ import ch.qos.logback.core.LayoutBase; */ public class TrivialLogbackLayout extends LayoutBase { - public String doLayout(ILoggingEvent loggingEvent) { - return loggingEvent.getMessage(); - } + public String doLayout(ILoggingEvent loggingEvent) { + return loggingEvent.getMessage(); + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/SimpleConfigurator.java b/logback-examples/src/main/java/chapters/onJoran/SimpleConfigurator.java index 35a0f28068ce88c97ba51da604cb1ae87fc6a4df..98e773310d96d75032b2e59affb97f276dc6248a 100644 --- a/logback-examples/src/main/java/chapters/onJoran/SimpleConfigurator.java +++ b/logback-examples/src/main/java/chapters/onJoran/SimpleConfigurator.java @@ -32,33 +32,33 @@ import ch.qos.logback.core.joran.spi.RuleStore; */ public class SimpleConfigurator extends GenericConfigurator { - final Map ruleMap; - final List iaList; + final Map ruleMap; + final List iaList; - public SimpleConfigurator(Map ruleMap) { - this(ruleMap, null); - } - - public SimpleConfigurator(Map ruleMap, List iaList) { - this.ruleMap = ruleMap; - this.iaList = iaList; - } + public SimpleConfigurator(Map ruleMap) { + this(ruleMap, null); + } - @Override - protected void addInstanceRules(RuleStore rs) { - for (ElementSelector elementSelector : ruleMap.keySet()) { - Action action = ruleMap.get(elementSelector); - rs.addRule(elementSelector, action); + public SimpleConfigurator(Map ruleMap, List iaList) { + this.ruleMap = ruleMap; + this.iaList = iaList; } - } - @Override - protected void addImplicitRules(Interpreter interpreter) { - if(iaList == null) { - return; + @Override + protected void addInstanceRules(RuleStore rs) { + for (ElementSelector elementSelector : ruleMap.keySet()) { + Action action = ruleMap.get(elementSelector); + rs.addRule(elementSelector, action); + } } - for (ImplicitAction ia : iaList) { - interpreter.addImplicitAction(ia); + + @Override + protected void addImplicitRules(Interpreter interpreter) { + if (iaList == null) { + return; + } + for (ImplicitAction ia : iaList) { + interpreter.addImplicitAction(ia); + } } - } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/AddAction.java b/logback-examples/src/main/java/chapters/onJoran/calculator/AddAction.java index 8129339d53aff51bf6e340167795f6481064e782..60e253ab8a4315261aa90c4a41ef5bf1b6210549 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/AddAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/AddAction.java @@ -20,7 +20,6 @@ import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - /** * This action adds the two integers at the top of the stack (they are removed) * and pushes the result to the top the stack. @@ -28,42 +27,40 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; * @author Ceki Gülcü */ public class AddAction extends Action { - - public void begin(InterpretationContext ic, String name, Attributes attributes) { - int first = fetchInteger(ic); - int second = fetchInteger(ic); - // Push the result of the addition for the following actions. - ic.pushObject(first + second); - } - /** - * Pop the Integer object at the top of the stack. - * This code also illustrates usage of Joran's error handling paradigm. - */ - int fetchInteger(InterpretationContext ic) { - int result = 0; + public void begin(InterpretationContext ic, String name, Attributes attributes) { + int first = fetchInteger(ic); + int second = fetchInteger(ic); + // Push the result of the addition for the following actions. + ic.pushObject(first + second); + } + + /** + * Pop the Integer object at the top of the stack. + * This code also illustrates usage of Joran's error handling paradigm. + */ + int fetchInteger(InterpretationContext ic) { + int result = 0; - try { - // Pop the object at the top of the interpretation context's stack. - Object o1 = ic.popObject(); + try { + // Pop the object at the top of the interpretation context's stack. + Object o1 = ic.popObject(); - if (o1 instanceof Integer) { - result = ((Integer) o1).intValue(); - } else { - String errMsg = - "Object [" + o1 - + "] currently at the top of the stack is not an integer."; - ic.addError(errMsg); - throw new IllegalArgumentException(errMsg); - } - } catch (EmptyStackException ese) { - ic.addError(("Expecting an integer on the execution stack.")); - throw ese; + if (o1 instanceof Integer) { + result = ((Integer) o1).intValue(); + } else { + String errMsg = "Object [" + o1 + "] currently at the top of the stack is not an integer."; + ic.addError(errMsg); + throw new IllegalArgumentException(errMsg); + } + } catch (EmptyStackException ese) { + ic.addError(("Expecting an integer on the execution stack.")); + throw ese; + } + return result; } - return result; - } - public void end(InterpretationContext ic, String name) { - // Nothing to do here. - } + public void end(InterpretationContext ic, String name) { + // Nothing to do here. + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator1.java b/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator1.java index fc9e9b396937b301ae8ca752135e7597a639a76b..391875ff1686bfeff2f5988cb76d42136bd791c6 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator1.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator1.java @@ -31,25 +31,25 @@ import chapters.onJoran.SimpleConfigurator; */ public class Calculator1 { - public static void main(String[] args) throws Exception { - Context context = new ContextBase(); + public static void main(String[] args) throws Exception { + Context context = new ContextBase(); - Map ruleMap = new HashMap(); + Map ruleMap = new HashMap(); - // Associate "/computation" pattern with ComputationAction1 - ruleMap.put(new ElementSelector("/computation"), new ComputationAction1()); + // Associate "/computation" pattern with ComputationAction1 + ruleMap.put(new ElementSelector("/computation"), new ComputationAction1()); - // Other associations - ruleMap.put(new ElementSelector("/computation/literal"), new LiteralAction()); - ruleMap.put(new ElementSelector("/computation/add"), new AddAction()); - ruleMap.put(new ElementSelector("/computation/multiply"), new MultiplyAction()); + // Other associations + ruleMap.put(new ElementSelector("/computation/literal"), new LiteralAction()); + ruleMap.put(new ElementSelector("/computation/add"), new AddAction()); + ruleMap.put(new ElementSelector("/computation/multiply"), new MultiplyAction()); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); - // link the configurator with its context - simpleConfigurator.setContext(context); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); + // link the configurator with its context + simpleConfigurator.setContext(context); - simpleConfigurator.doConfigure(args[0]); - // Print any errors that might have occured. - StatusPrinter.print(context); - } + simpleConfigurator.doConfigure(args[0]); + // Print any errors that might have occured. + StatusPrinter.print(context); + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator2.java b/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator2.java index 9d7f49f54762752385b98c133e4b5658b787dc36..5df6787b013750def2df1869cf9d64260c577f4c 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator2.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/Calculator2.java @@ -24,7 +24,6 @@ import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import chapters.onJoran.SimpleConfigurator; - /** * This examples illustrates collaboration between multiple actions through the * common execution context stack. @@ -37,28 +36,27 @@ import chapters.onJoran.SimpleConfigurator; * @author Ceki Güulcü */ public class Calculator2 { - public static void main(String[] args) throws Exception { - Map ruleMap = new HashMap(); - - - // Note the wild card character '*', in the paterns, signifying any level - // of nesting. - ruleMap.put(new ElementSelector("*/computation"), new ComputationAction2()); + public static void main(String[] args) throws Exception { + Map ruleMap = new HashMap(); + + // Note the wild card character '*', in the paterns, signifying any level + // of nesting. + ruleMap.put(new ElementSelector("*/computation"), new ComputationAction2()); + + ruleMap.put(new ElementSelector("*/computation/literal"), new LiteralAction()); + ruleMap.put(new ElementSelector("*/computation/add"), new AddAction()); + ruleMap.put(new ElementSelector("*/computation/multiply"), new MultiplyAction()); - ruleMap.put(new ElementSelector("*/computation/literal"), new LiteralAction()); - ruleMap.put(new ElementSelector("*/computation/add"), new AddAction()); - ruleMap.put(new ElementSelector("*/computation/multiply"), new MultiplyAction()); - - Context context = new ContextBase(); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); - // link the configurator with its context - simpleConfigurator.setContext(context); + Context context = new ContextBase(); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); + // link the configurator with its context + simpleConfigurator.setContext(context); - try { - simpleConfigurator.doConfigure(args[0]); - } catch (JoranException e) { - // Print any errors that might have occured. - StatusPrinter.print(context); + try { + simpleConfigurator.doConfigure(args[0]); + } catch (JoranException e) { + // Print any errors that might have occured. + StatusPrinter.print(context); + } } - } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction1.java b/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction1.java index 12e73fa8dc15b77865cc4268bfa5f9bc78fba52a..56193ae06963624a76437b0eb10bb1538bbb6a1f 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction1.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction1.java @@ -13,15 +13,12 @@ */ package chapters.onJoran.calculator; - - import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.OptionHelper; - /** * ComputationAction1 will print the result of the compuration made by * children elements but only if the compuration itself is named, that is if the @@ -31,31 +28,30 @@ import ch.qos.logback.core.util.OptionHelper; * @author Ceki Gülcü */ public class ComputationAction1 extends Action { - public static final String NAME_ATR = "name"; + public static final String NAME_ATR = "name"; - String nameStr; + String nameStr; - /** - * Store the value of the name attribute for future use. - */ - public void begin(InterpretationContext ec, String name, Attributes attributes) { - nameStr = attributes.getValue(NAME_ATR); - } + /** + * Store the value of the name attribute for future use. + */ + public void begin(InterpretationContext ec, String name, Attributes attributes) { + nameStr = attributes.getValue(NAME_ATR); + } - /** - * Children elements have been processed. The sesults should be an integer - * placed at the top of the execution stack. - * - * This value will be printed on the console but only if the action is - * named. Anonymous computation will not print their result. - */ - public void end(InterpretationContext ec, String name) { - if (OptionHelper.isEmpty(nameStr)) { - // nothing to do - } else { - Integer i = (Integer) ec.peekObject(); - System.out.println( - "The computation named [" + nameStr + "] resulted in the value " + i); + /** + * Children elements have been processed. The sesults should be an integer + * placed at the top of the execution stack. + * + * This value will be printed on the console but only if the action is + * named. Anonymous computation will not print their result. + */ + public void end(InterpretationContext ec, String name) { + if (OptionHelper.isEmpty(nameStr)) { + // nothing to do + } else { + Integer i = (Integer) ec.peekObject(); + System.out.println("The computation named [" + nameStr + "] resulted in the value " + i); + } } - } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction2.java b/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction2.java index 598332de2e54435a0ef4927ae6a4e5a3f1bc6353..e7a8eb69a733a13326c27c876f2de153f1a347cd 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction2.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/ComputationAction2.java @@ -21,7 +21,6 @@ import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; import ch.qos.logback.core.util.OptionHelper; - /** * ComputationAction2 will print the result of the compuration made by * children elements but only if the computation itself is named, that is if the @@ -59,28 +58,26 @@ import ch.qos.logback.core.util.OptionHelper; * @author Ceki Gülcü */ public class ComputationAction2 extends Action { - public static final String NAME_ATR = "name"; + public static final String NAME_ATR = "name"; + + Stack nameStrStack = new Stack(); + + public void begin(InterpretationContext ec, String name, Attributes attributes) { + String nameStr = attributes.getValue(NAME_ATR); + // save nameStr value in a special stack. Note that the value is saved + // even if it is empty or null. + nameStrStack.push(nameStr); + } - Stack nameStrStack = new Stack(); - - - public void begin(InterpretationContext ec, String name, Attributes attributes) { - String nameStr = attributes.getValue(NAME_ATR); - // save nameStr value in a special stack. Note that the value is saved - // even if it is empty or null. - nameStrStack.push(nameStr); - } + public void end(InterpretationContext ec, String name) { + // pop nameStr value from the special stack + String nameStr = (String) nameStrStack.pop(); - public void end(InterpretationContext ec, String name) { - // pop nameStr value from the special stack - String nameStr = (String) nameStrStack.pop(); - - if (OptionHelper.isEmpty(nameStr)) { - // nothing to do - } else { - Integer i = (Integer) ec.peekObject(); - System.out.println( - "The computation named [" + nameStr + "] resulted in the value " + i); + if (OptionHelper.isEmpty(nameStr)) { + // nothing to do + } else { + Integer i = (Integer) ec.peekObject(); + System.out.println("The computation named [" + nameStr + "] resulted in the value " + i); + } } - } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/LiteralAction.java b/logback-examples/src/main/java/chapters/onJoran/calculator/LiteralAction.java index a43a713f19303e0975547ba58d7f43833dd5499d..bc230f519134a0ba2df839ee0b33e46979376181 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/LiteralAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/LiteralAction.java @@ -29,30 +29,29 @@ import ch.qos.logback.core.util.OptionHelper; * @author Ceki Gülcü */ public class LiteralAction extends Action { - public static final String VALUE_ATR = "value"; + public static final String VALUE_ATR = "value"; - public void begin(InterpretationContext ic, String name, Attributes attributes) { - String valueStr = attributes.getValue(VALUE_ATR); + public void begin(InterpretationContext ic, String name, Attributes attributes) { + String valueStr = attributes.getValue(VALUE_ATR); - if (OptionHelper.isEmpty(valueStr)) { - ic.addError("The literal action requires a value attribute"); - return; - } + if (OptionHelper.isEmpty(valueStr)) { + ic.addError("The literal action requires a value attribute"); + return; + } - try { - Integer i = Integer.valueOf(valueStr); - ic.pushObject(i); - } catch (NumberFormatException nfe) { - ic.addError("The value [" + valueStr - + "] could not be converted to an Integer", nfe); - throw nfe; + try { + Integer i = Integer.valueOf(valueStr); + ic.pushObject(i); + } catch (NumberFormatException nfe) { + ic.addError("The value [" + valueStr + "] could not be converted to an Integer", nfe); + throw nfe; + } } - } - public void end(InterpretationContext ic, String name) { - // Nothing to do here. - // In general, the end() method of actions associated with elements - // having no children do not need to perform any processing in their - // end() method. - } + public void end(InterpretationContext ic, String name) { + // Nothing to do here. + // In general, the end() method of actions associated with elements + // having no children do not need to perform any processing in their + // end() method. + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/calculator/MultiplyAction.java b/logback-examples/src/main/java/chapters/onJoran/calculator/MultiplyAction.java index da7f1dfe1d3931942f90dcf9e18c86903b765144..bd13f4117d4744b2b44729df0cca6297c927655d 100644 --- a/logback-examples/src/main/java/chapters/onJoran/calculator/MultiplyAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/calculator/MultiplyAction.java @@ -29,38 +29,37 @@ import java.util.EmptyStackException; */ public class MultiplyAction extends Action { - public void begin(InterpretationContext ic, String name, Attributes attributes) { - int first = fetchInteger(ic); - int second = fetchInteger(ic); - ic.pushObject(first * second); - } + public void begin(InterpretationContext ic, String name, Attributes attributes) { + int first = fetchInteger(ic); + int second = fetchInteger(ic); + ic.pushObject(first * second); + } - /** - * Pop the Integer object at the top of the stack. This code illustrates usage - * of Joran's error handling paradigm. - */ - int fetchInteger(InterpretationContext ic) { - int result = 0; + /** + * Pop the Integer object at the top of the stack. This code illustrates usage + * of Joran's error handling paradigm. + */ + int fetchInteger(InterpretationContext ic) { + int result = 0; - try { - Object o1 = ic.popObject(); + try { + Object o1 = ic.popObject(); - if (o1 instanceof Integer) { - result = ((Integer) o1).intValue(); - } else { - String errMsg = "Object [" + o1 - + "] currently at the top of the stack is not an integer."; - ic.addError(errMsg); - throw new IllegalArgumentException(errMsg); - } - } catch (EmptyStackException ese) { - ic.addError("Expecting an integer on the execution stack."); - throw ese; + if (o1 instanceof Integer) { + result = ((Integer) o1).intValue(); + } else { + String errMsg = "Object [" + o1 + "] currently at the top of the stack is not an integer."; + ic.addError(errMsg); + throw new IllegalArgumentException(errMsg); + } + } catch (EmptyStackException ese) { + ic.addError("Expecting an integer on the execution stack."); + throw ese; + } + return result; } - return result; - } - public void end(InterpretationContext ic, String name) { - // Nothing to do here. - } + public void end(InterpretationContext ic, String name) { + // Nothing to do here. + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorld.java b/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorld.java index fcfaeb2807e05ef9a746a22e7a0aab0ef6b53873..249d7c862ad0c7cc332fcee77ee606cc378dada5 100644 --- a/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorld.java +++ b/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorld.java @@ -30,19 +30,19 @@ import chapters.onJoran.SimpleConfigurator; * @author Ceki Gulcu */ public class HelloWorld { - public static void main(String[] args) throws Exception { - Map ruleMap = new HashMap(); + public static void main(String[] args) throws Exception { + Map ruleMap = new HashMap(); - // Associate "hello-world" pattern with HelloWorldAction - ruleMap.put(new ElementSelector("hello-world"), new HelloWorldAction()); + // Associate "hello-world" pattern with HelloWorldAction + ruleMap.put(new ElementSelector("hello-world"), new HelloWorldAction()); - // Joran needs to work within a context. - Context context = new ContextBase(); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); - // link the configurator with its context - simpleConfigurator.setContext(context); + // Joran needs to work within a context. + Context context = new ContextBase(); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); + // link the configurator with its context + simpleConfigurator.setContext(context); - simpleConfigurator.doConfigure(args[0]); - StatusPrinter.print(context); - } + simpleConfigurator.doConfigure(args[0]); + StatusPrinter.print(context); + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorldAction.java b/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorldAction.java index 4a82ab4f7d91cd431133cc14ae45999516db9ae7..1cb4f70696c7401b88fecca7bfebee7633dfe549 100644 --- a/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorldAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/helloWorld/HelloWorldAction.java @@ -26,10 +26,10 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; * @author Ceki Gülcü */ public class HelloWorldAction extends Action { - public void begin(InterpretationContext ec, String name, Attributes attributes) { - System.out.println("Hello World"); - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + System.out.println("Hello World"); + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/implicit/NOPAction.java b/logback-examples/src/main/java/chapters/onJoran/implicit/NOPAction.java index fa7b6f6299baa901aed805a3c70fccb0af76c1a5..b9a9c53edaba8cbf7a2cddc36b1e0ba4528645c2 100644 --- a/logback-examples/src/main/java/chapters/onJoran/implicit/NOPAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/implicit/NOPAction.java @@ -18,17 +18,16 @@ import org.xml.sax.Attributes; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.spi.InterpretationContext; - /** * No operation (NOP) action that does strictly nothing. * * @author Ceki Gülcü */ public class NOPAction extends Action { - - public void begin(InterpretationContext ec, String name, Attributes attributes) { - } - public void end(InterpretationContext ec, String name) { - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + } + + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMe.java b/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMe.java index 670661a2e784aa6c359764097dff55730a674185..650eab3ced76a318db6d27d0b0c7ffa7d1f5ab09 100644 --- a/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMe.java +++ b/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMe.java @@ -37,25 +37,24 @@ import chapters.onJoran.SimpleConfigurator; */ public class PrintMe { - public static void main(String[] args) throws Exception { - Context context = new ContextBase(); + public static void main(String[] args) throws Exception { + Context context = new ContextBase(); - Map ruleMap = new HashMap(); + Map ruleMap = new HashMap(); - // we start with the rule for the top-most (root) element - ruleMap.put(new ElementSelector("*/foo"), new NOPAction()); + // we start with the rule for the top-most (root) element + ruleMap.put(new ElementSelector("*/foo"), new NOPAction()); - // Add an implicit action. - List iaList = new ArrayList(); - iaList.add(new PrintMeImplicitAction()); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap, - iaList); + // Add an implicit action. + List iaList = new ArrayList(); + iaList.add(new PrintMeImplicitAction()); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap, iaList); - // link the configurator with its context - simpleConfigurator.setContext(context); + // link the configurator with its context + simpleConfigurator.setContext(context); - simpleConfigurator.doConfigure(args[0]); - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - - } + simpleConfigurator.doConfigure(args[0]); + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMeImplicitAction.java b/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMeImplicitAction.java index cb88413123338746bb318167a3a99376a3e5102c..b7e68c351ac4260c4285af6dffb327d1f2d85db8 100644 --- a/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMeImplicitAction.java +++ b/logback-examples/src/main/java/chapters/onJoran/implicit/PrintMeImplicitAction.java @@ -28,17 +28,16 @@ import ch.qos.logback.core.joran.spi.InterpretationContext; */ public class PrintMeImplicitAction extends ImplicitAction { - public boolean isApplicable(ElementPath elementPath, Attributes attributes, - InterpretationContext ec) { - String printmeStr = attributes.getValue("printme"); + public boolean isApplicable(ElementPath elementPath, Attributes attributes, InterpretationContext ec) { + String printmeStr = attributes.getValue("printme"); - return Boolean.valueOf(printmeStr).booleanValue(); - } + return Boolean.valueOf(printmeStr).booleanValue(); + } - public void begin(InterpretationContext ec, String name, Attributes attributes) { - System.out.println("Element [" + name + "] asked to be printed."); - } + public void begin(InterpretationContext ec, String name, Attributes attributes) { + System.out.println("Element [" + name + "] asked to be printed."); + } - public void end(InterpretationContext ec, String name) { - } + public void end(InterpretationContext ec, String name) { + } } diff --git a/logback-examples/src/main/java/chapters/onJoran/newRule/NewRuleCalculator.java b/logback-examples/src/main/java/chapters/onJoran/newRule/NewRuleCalculator.java index b4fe4f7a8136bfc092f26ec1c3ce67a4e27a8bef..4d966826d385c97231457274ac6450fbdbf6ab77 100644 --- a/logback-examples/src/main/java/chapters/onJoran/newRule/NewRuleCalculator.java +++ b/logback-examples/src/main/java/chapters/onJoran/newRule/NewRuleCalculator.java @@ -35,29 +35,29 @@ import chapters.onJoran.calculator.ComputationAction1; * @author Ceki Güulcü */ public class NewRuleCalculator { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - Context context = new ContextBase(); + Context context = new ContextBase(); - Map ruleMap = new HashMap(); + Map ruleMap = new HashMap(); - // we start with the rule for the top-most (root) element - ruleMap.put(new ElementSelector("*/computation"), new ComputationAction1()); + // we start with the rule for the top-most (root) element + ruleMap.put(new ElementSelector("*/computation"), new ComputationAction1()); - // Associate "/new-rule" pattern with NewRuleAction from the - // org.apache.joran.action package. - // - // We will let the XML file to teach the Joran interpreter about new rules - ruleMap.put(new ElementSelector("/computation/newRule"), new NewRuleAction()); + // Associate "/new-rule" pattern with NewRuleAction from the + // org.apache.joran.action package. + // + // We will let the XML file to teach the Joran interpreter about new rules + ruleMap.put(new ElementSelector("/computation/newRule"), new NewRuleAction()); - SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); - // link the configurator with its context - simpleConfigurator.setContext(context); + SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); + // link the configurator with its context + simpleConfigurator.setContext(context); - simpleConfigurator.doConfigure(args[0]); + simpleConfigurator.doConfigure(args[0]); - // Print any errors that might have occured. - StatusPrinter.printInCaseOfErrorsOrWarnings(context); - } + // Print any errors that might have occured. + StatusPrinter.printInCaseOfErrorsOrWarnings(context); + } } diff --git a/logback-examples/src/main/java/chapters/receivers/socket/AppenderExample.java b/logback-examples/src/main/java/chapters/receivers/socket/AppenderExample.java index 93e3101810a751a5d8255f8cbcf5d6ca8a3b1691..14fcad922196bd50ae2142284bda5491dc47f1d3 100755 --- a/logback-examples/src/main/java/chapters/receivers/socket/AppenderExample.java +++ b/logback-examples/src/main/java/chapters/receivers/socket/AppenderExample.java @@ -29,48 +29,45 @@ import ch.qos.logback.classic.joran.JoranConfigurator; */ public class AppenderExample { - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + AppenderExample.class.getName() + - " configFile\n" + - " configFile a logback configuration file" + - " in XML format."); - System.exit(1); - } - - static public void main(String[] args) throws Exception { - if (args.length != 1) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + AppenderExample.class.getName() + " configFile\n" + " configFile a logback configuration file" + + " in XML format."); + System.exit(1); } - String configFile = args[0]; + static public void main(String[] args) throws Exception { + if (args.length != 1) { + usage("Wrong number of arguments."); + } - if (configFile.endsWith(".xml")) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - } + String configFile = args[0]; + + if (configFile.endsWith(".xml")) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + } + + Logger logger = LoggerFactory.getLogger(AppenderExample.class); - Logger logger = LoggerFactory.getLogger(AppenderExample.class); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + System.out.println("Type a message to send to remote clients. Type 'q' to quit."); - while (true) { - System.out.println( - "Type a message to send to remote clients. Type 'q' to quit."); + String s = reader.readLine(); - String s = reader.readLine(); + if (s.equals("q")) { + break; + } else { + logger.debug(s); + } + } - if (s.equals("q")) { - break; - } else { - logger.debug(s); - } + ((LoggerContext) LoggerFactory.getILoggerFactory()).stop(); } - - ((LoggerContext) LoggerFactory.getILoggerFactory()).stop(); - } } diff --git a/logback-examples/src/main/java/chapters/receivers/socket/ReceiverExample.java b/logback-examples/src/main/java/chapters/receivers/socket/ReceiverExample.java index c1dd3f0623efcdbf5909d13d54af6d8bd53f3724..ea51e7e1119b625a480c40aceab5a9adfc712971 100755 --- a/logback-examples/src/main/java/chapters/receivers/socket/ReceiverExample.java +++ b/logback-examples/src/main/java/chapters/receivers/socket/ReceiverExample.java @@ -25,31 +25,29 @@ import ch.qos.logback.classic.joran.JoranConfigurator; */ public class ReceiverExample { - static void usage(String msg) { - System.err.println(msg); - System.err.println("Usage: java " + ReceiverExample.class.getName() + - " configFile\n" + - " configFile a logback configuration file" + - " in XML format."); - System.exit(1); - } - - static public void main(String[] args) throws Exception { - if (args.length != 1) { - usage("Wrong number of arguments."); + static void usage(String msg) { + System.err.println(msg); + System.err.println("Usage: java " + ReceiverExample.class.getName() + " configFile\n" + " configFile a logback configuration file" + + " in XML format."); + System.exit(1); } - String configFile = args[0]; + static public void main(String[] args) throws Exception { + if (args.length != 1) { + usage("Wrong number of arguments."); + } - if (configFile.endsWith(".xml")) { - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - lc.reset(); - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(lc); - configurator.doConfigure(configFile); - } + String configFile = args[0]; + + if (configFile.endsWith(".xml")) { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.reset(); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + configurator.doConfigure(configFile); + } - Thread.sleep(Long.MAX_VALUE); - } + Thread.sleep(Long.MAX_VALUE); + } }