diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..412eeda78dc9de1186c2e0e1526764af82ab3431 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain 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 bf04d51f24d55797282075dc919a160336fb1844..b1825cb6c975e4bf3aa9327eb421fa25a4dce706 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 @@ -1,59 +1,59 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.jetty; - -import ch.qos.logback.access.spi.IAccessEvent; -import ch.qos.logback.access.PatternLayoutEncoder; -import ch.qos.logback.access.testUtil.NotifyingListAppender; -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); - } -} - +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.jetty; + +import ch.qos.logback.access.spi.IAccessEvent; +import ch.qos.logback.access.PatternLayoutEncoder; +import ch.qos.logback.access.testUtil.NotifyingListAppender; +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); + } +} + 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 2d7dee1d158ee7b48981bde919c9271918a33c2e..008118d871d469e42a22f7291f4db628c51a7472 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 @@ -1,95 +1,95 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.joran; - -import ch.qos.logback.access.TeztConstants; -import ch.qos.logback.access.spi.AccessContext; -import ch.qos.logback.core.ConsoleAppender; -import ch.qos.logback.core.joran.spi.JoranException; -import ch.qos.logback.core.read.ListAppender; -import ch.qos.logback.core.status.StatusChecker; -import ch.qos.logback.core.testUtil.RandomUtil; -import ch.qos.logback.core.util.CoreTestConstants; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** - * @author Ceki Gücü - */ -public class ConditionalTest { - - AccessContext context = new AccessContext(); - StatusChecker checker = new StatusChecker(context); - - 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(); - } - } - - 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(TeztConstants.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(TeztConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); - - ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); - assertNull(consoleAppender); - - StatusChecker checker = new StatusChecker(context); - assertTrue(checker.isErrorFree(0)); - } - - @Test - public void conditionalConsoleApp_ELSE() throws JoranException, - IOException, InterruptedException { - configure(TeztConstants.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)); - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.joran; + +import ch.qos.logback.access.TeztConstants; +import ch.qos.logback.access.spi.AccessContext; +import ch.qos.logback.core.ConsoleAppender; +import ch.qos.logback.core.joran.spi.JoranException; +import ch.qos.logback.core.read.ListAppender; +import ch.qos.logback.core.status.StatusChecker; +import ch.qos.logback.core.testUtil.RandomUtil; +import ch.qos.logback.core.util.CoreTestConstants; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * @author Ceki Gücü + */ +public class ConditionalTest { + + AccessContext context = new AccessContext(); + StatusChecker checker = new StatusChecker(context); + + 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(); + } + } + + 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(TeztConstants.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(TeztConstants.TEST_DIR_PREFIX + "input/joran/conditional/conditionalConsole.xml"); + + ConsoleAppender consoleAppender = (ConsoleAppender) context.getAppender("CON"); + assertNull(consoleAppender); + + StatusChecker checker = new StatusChecker(context); + assertTrue(checker.isErrorFree(0)); + } + + @Test + public void conditionalConsoleApp_ELSE() throws JoranException, + IOException, InterruptedException { + configure(TeztConstants.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)); + } +} 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 229e44e1291756a4c7e871cc077befee2b86f77d..65f0390592a888ed217e6a71a82d739d9992358e 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 @@ -1,25 +1,25 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.joran; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * @author Ceki Gücü - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({JoranConfiguratorTest.class, ConditionalTest.class}) -public class PackageTest { -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.joran; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; + +/** + * @author Ceki Gücü + */ +@RunWith(Suite.class) +@Suite.SuiteClasses({JoranConfiguratorTest.class, ConditionalTest.class}) +public class PackageTest { +} 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 8c6763c2cd2d016119bfeb2b9c88d5032b2a7e93..f7f9ff667111bf0ef8e6cdcb1f24c1a6bffd6f7f 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 @@ -1,47 +1,47 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.issue.lbcore211; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; -import ch.qos.logback.core.joran.spi.JoranException; -import ch.qos.logback.core.util.StatusPrinter; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -/** - * @author Ceki Gücü - */ -public class Lbcore211 { - - @Test - public void lbcore211() throws JoranException { - - LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - - 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); - } - - lc.stop(); - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.issue.lbcore211; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.core.joran.spi.JoranException; +import ch.qos.logback.core.util.StatusPrinter; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * @author Ceki Gücü + */ +public class Lbcore211 { + + @Test + public void lbcore211() throws JoranException { + + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + + 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); + } + + lc.stop(); + } +} 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 f45978524380b876cc3bb99fab90cc51fd664cbd..1f7650c1d59f0c3a6264eb19f59d57bbd12e8aab 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 @@ -1,33 +1,33 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -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; - } - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +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; + } + } +} 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 5dc53d1d9f891cfe007ef8b8f49512f254b8d5cc..d38266d97ee82d9cc0b2fcf1bab2ab157a37f861 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 @@ -1,51 +1,51 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.turbo.lru; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * An lru cache based on Java's LinkedHashMap. - * - * @author Ceki Gulcu - * - * @param - * @param - */ -public class LRUCache extends LinkedHashMap { - private static final long serialVersionUID = -6592964689843698200L; - - 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; - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.turbo.lru; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * An lru cache based on Java's LinkedHashMap. + * + * @author Ceki Gulcu + * + * @param + * @param + */ +public class LRUCache extends LinkedHashMap { + private static final long serialVersionUID = -6592964689843698200L; + + 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; + } +} 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 f367301fd48e77e9e9622701db7b5af35da58440..94b7bb1b5ab700633b9ac50a80c38f641f9e6479 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 @@ -1,122 +1,122 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.turbo.lru; - -import static org.junit.Assert.assertEquals; - -import java.util.LinkedList; -import java.util.List; - -import org.junit.Ignore; -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]); - } - } - } - - 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); - } - 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()); - } - - 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"); - } - } - -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.turbo.lru; + +import static org.junit.Assert.assertEquals; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.Ignore; +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]); + } + } + } + + 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); + } + 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()); + } + + 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 72bb87942128940846420ff17afdd813fcb9528b..0f8abd80eafe924f1753f21a4ecd26635548f9cf 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 @@ -1,89 +1,89 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.turbo.lru; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class Simulator { - - Random random; - - 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 List generateScenario(int len) { - List scenario = new ArrayList(); - - 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); - } - 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); - } - } - } - } - - // 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"); - // } - // } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.turbo.lru; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public class Simulator { + + Random random; + + 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 List generateScenario(int len) { + List scenario = new ArrayList(); + + 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); + } + 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); + } + } + } + } + + // 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 dd9bcf3ff8a6e14ec35a8c5ae444f47ec396bda4..1514b7f6e28c794a16f55df69bcc42fa39132742 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 @@ -1,45 +1,45 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.turbo.lru; - -public class T_Entry implements Comparable { - - 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 other = (T_Entry) o; - if(sequenceNumber > other.sequenceNumber) { - return 1; - } - if(sequenceNumber == other.sequenceNumber) { - return 0; - } - return -1; - } - @Override - public String toString() { - return "("+k+","+sequenceNumber+")"; - //return "("+k+")"; - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.turbo.lru; + +public class T_Entry implements Comparable { + + 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 other = (T_Entry) o; + if(sequenceNumber > other.sequenceNumber) { + return 1; + } + if(sequenceNumber == other.sequenceNumber) { + return 0; + } + 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 23fdfd69be1993b8305c484359d1f176ad9c1305..50ea156c9594f14bd1ea96d15244142f897edde0 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 @@ -1,94 +1,94 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.turbo.lru; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * This is an alternative (slower) implementation of LRUCache for testing - * purposes. - * - * @author Ceki Gulcu - */ -public class T_LRUCache { - - 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); - } - } - - @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; - } - } - - synchronized public List keyList() { - List keyList = new ArrayList(); - for (T_Entry e : cacheList) { - keyList.add(e.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; - } - } - return null; - } - - - 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(); - } - -} - +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.classic.turbo.lru; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * This is an alternative (slower) implementation of LRUCache for testing + * purposes. + * + * @author Ceki Gulcu + */ +public class T_LRUCache { + + 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); + } + } + + @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; + } + } + + synchronized public List keyList() { + List keyList = new ArrayList(); + for (T_Entry e : cacheList) { + keyList.add(e.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; + } + } + return null; + } + + + 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(); + } + +} + diff --git a/logback-classic/src/test/resources/TWO_DATE_logback-test.xml b/logback-classic/src/test/resources/TWO_DATE_logback-test.xml index d2c3444c23988d7440ed02b5d29cbf8737f8a5b3..e5f43f6fd046cff951579252d0da76aaf4c98016 100644 --- a/logback-classic/src/test/resources/TWO_DATE_logback-test.xml +++ b/logback-classic/src/test/resources/TWO_DATE_logback-test.xml @@ -1,21 +1,21 @@ - - - - - test.log - - - - - bla-%d{yyyy-MM-dd, SECONDARY}/app.%d{yyyy-MM-dd'T'HH_mm}.log - - - - %d{"yyyy-MM-dd HH:mm:ss,SSS"} [%thread] %-5level %logger{36} - %msg%n%xEx - - - - - - + + + + + test.log + + + + + bla-%d{yyyy-MM-dd, SECONDARY}/app.%d{yyyy-MM-dd'T'HH_mm}.log + + + + %d{"yyyy-MM-dd HH:mm:ss,SSS"} [%thread] %-5level %logger{36} - %msg%n%xEx + + + + + + \ No newline at end of file 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 3c4a07721d0298a9d0bb4bdc866af8803833f0c4..07ca2c468e63ce9d5690f06aae3c12a776e9ae30 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 @@ -1,60 +1,60 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.hook; - -import ch.qos.logback.core.Context; -import ch.qos.logback.core.ContextBase; -import ch.qos.logback.core.util.Duration; - -/** - * ShutdownHook implementation that stops the Logback context after a specified - * delay. The default delay is 0 ms (zero). - * - * @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() { - } - - 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) { - } - super.stop(); - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.hook; + +import ch.qos.logback.core.Context; +import ch.qos.logback.core.ContextBase; +import ch.qos.logback.core.util.Duration; + +/** + * ShutdownHook implementation that stops the Logback context after a specified + * delay. The default delay is 0 ms (zero). + * + * @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() { + } + + 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) { + } + super.stop(); + } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHook.java b/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHook.java index be85f854a928dae0f3a50947d8b8775f6ea1d891..4c3a507c8d97f01578ee9539335d7bf85da960d5 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHook.java +++ b/logback-core/src/main/java/ch/qos/logback/core/hook/ShutdownHook.java @@ -1,24 +1,24 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.hook; - -import ch.qos.logback.core.spi.ContextAware; - -/** - * Interface describing a logback shutdown hook implementation - * - * @author Mike Reinhold - */ -public interface ShutdownHook extends Runnable, ContextAware { -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.hook; + +import ch.qos.logback.core.spi.ContextAware; + +/** + * Interface describing a logback shutdown hook implementation + * + * @author Mike Reinhold + */ +public interface ShutdownHook extends Runnable, ContextAware { +} 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 facd02e7696c8b34e0c28165cbae8a782c4829c9..af30161ce829fffc5075688ad4d7ebf115661eb2 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 @@ -1,42 +1,42 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.hook; - -import ch.qos.logback.core.Context; -import ch.qos.logback.core.ContextBase; -import ch.qos.logback.core.spi.ContextAwareBase; - -/** - * Base class for classes implementing a Logback ShutdownHook via extension - * - * @author Mike Reinhold - */ -public abstract class ShutdownHookBase extends ContextAwareBase implements ShutdownHook { - - public ShutdownHookBase() { - } - - /** - * 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(); - } - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.hook; + +import ch.qos.logback.core.Context; +import ch.qos.logback.core.ContextBase; +import ch.qos.logback.core.spi.ContextAwareBase; + +/** + * Base class for classes implementing a Logback ShutdownHook via extension + * + * @author Mike Reinhold + */ +public abstract class ShutdownHookBase extends ContextAwareBase implements ShutdownHook { + + public ShutdownHookBase() { + } + + /** + * 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(); + } + } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/hook/package.html b/logback-core/src/main/java/ch/qos/logback/core/hook/package.html index 4b858d8d27480fc653c39cc2c90ffa6e1ddbab8d..af1009e4d4dc2186c5478f50843e510a40e373c1 100644 --- a/logback-core/src/main/java/ch/qos/logback/core/hook/package.html +++ b/logback-core/src/main/java/ch/qos/logback/core/hook/package.html @@ -1,17 +1,17 @@ - - - - - - - - - -

Contains the shutdown hook functionality of logback, -including the interface and base class for implementing -hooks as well as some default implementations, such as -@link{ch.qos.logback.core.hook.DelayingShutdownHook} -

- - - + + + + + + + + + +

Contains the shutdown hook functionality of logback, +including the interface and base class for implementing +hooks as well as some default implementations, such as +@link{ch.qos.logback.core.hook.DelayingShutdownHook} +

+ + + 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 ec0d7c6e4d8df23066dbe2802f5d8b5f881e5668..a3730578458249f29297b824085a854aff69a977 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 @@ -1,90 +1,90 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.joran.action; - -import org.xml.sax.Attributes; - -import ch.qos.logback.core.CoreConstants; -import ch.qos.logback.core.hook.ShutdownHookBase; -import ch.qos.logback.core.joran.spi.ActionException; -import ch.qos.logback.core.joran.spi.InterpretationContext; -import ch.qos.logback.core.util.OptionHelper; - -/** - * Action which handles elements in configuration files. - * - * @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; - } - - 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); - } - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.joran.action; + +import org.xml.sax.Attributes; + +import ch.qos.logback.core.CoreConstants; +import ch.qos.logback.core.hook.ShutdownHookBase; +import ch.qos.logback.core.joran.spi.ActionException; +import ch.qos.logback.core.joran.spi.InterpretationContext; +import ch.qos.logback.core.util.OptionHelper; + +/** + * Action which handles elements in configuration files. + * + * @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; + } + + 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/conditional/PropertyWrapperForScripts.java b/logback-core/src/main/java/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.java index 8eb495cebaceb01d2d73cc5e63f900c23074e630..f4022f494920ac4631ce61900cef54d9476dc33a 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 @@ -1,51 +1,51 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.joran.conditional; - -import ch.qos.logback.core.spi.PropertyContainer; -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 ""; - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.joran.conditional; + +import ch.qos.logback.core.spi.PropertyContainer; +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 ""; + } +} 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 03137f40aaddac9bfc054b17cc5bee6dae0176f9..3b31845bc113c37213dba1aaa34db9bf4cdb15f0 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 @@ -1,25 +1,25 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.spi; - -/** - * This class just makes it easier to identify locks associated with logback - * when analysing thread dumps. - * - * @author Ceki Gücü - */ -public class LogbackLock extends Object { - - -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.spi; + +/** + * This class just makes it easier to identify locks associated with logback + * when analysing thread dumps. + * + * @author Ceki Gücü + */ +public class LogbackLock extends Object { + + +} 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 d405f5eb512607afa0f178281ad838bf2e79b509..aa00b98283e86899bdbef9001a69f9254742207d 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 @@ -1,84 +1,84 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.rolling; - -import ch.qos.logback.core.Context; -import ch.qos.logback.core.ContextBase; -import org.junit.Before; -import org.junit.Test; - -import java.util.logging.Logger; - -import static org.junit.Assert.assertEquals; - -/** - * @author Ceki Gücü - */ -public class TimeBasedFileNamingAndTriggeringPolicyBaseTest { - - static long MILLIS_IN_MINUTE = 60*1000; - - 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); - timeBasedFNATP.isTriggeringEvent(null, null); - String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); - assertEquals("foo-2011-12/59.log", elapsedPeriodsFileName); - } - -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.rolling; + +import ch.qos.logback.core.Context; +import ch.qos.logback.core.ContextBase; +import org.junit.Before; +import org.junit.Test; + +import java.util.logging.Logger; + +import static org.junit.Assert.assertEquals; + +/** + * @author Ceki Gücü + */ +public class TimeBasedFileNamingAndTriggeringPolicyBaseTest { + + static long MILLIS_IN_MINUTE = 60*1000; + + 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); + timeBasedFNATP.isTriggeringEvent(null, null); + String elapsedPeriodsFileName = timeBasedFNATP.getElapsedPeriodsFileName(); + assertEquals("foo-2011-12/59.log", elapsedPeriodsFileName); + } + +} 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 aec647299510ca91b8e652dc9afcb9f939f7e46a..6bf0e12974f3c67d309ea2c19fadb5968b78c7a1 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 @@ -1,37 +1,37 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.testUtil; - -import ch.qos.logback.core.util.CoreTestConstants; - -import java.io.File; - -import static junit.framework.Assert.assertTrue; - -/** - * @author Ceki Gücü - */ -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"); - } - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.testUtil; + +import ch.qos.logback.core.util.CoreTestConstants; + +import java.io.File; + +import static junit.framework.Assert.assertTrue; + +/** + * @author Ceki Gücü + */ +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"); + } + } +} diff --git a/logback-core/src/test/scala/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_STest.scala b/logback-core/src/test/scala/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_STest.scala index 00caf985e283229171cee32b5e860877d8a6eeb6..6eb3da6980d0ed7ffa6536f7333f2b5756e80dc1 100644 --- a/logback-core/src/test/scala/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_STest.scala +++ b/logback-core/src/test/scala/ch/qos/logback/core/rolling/SizeAndTimeBasedFNATP_STest.scala @@ -1,188 +1,188 @@ -package ch.qos.logback.core.rolling - -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2011, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ - -import ch.qos.logback.core.encoder.EchoEncoder -import ch.qos.logback.core.status.InfoStatus -import java.util.Date -import org.junit.{Ignore, Test} -import org.junit.Before -import java.io.File -import ch.qos.logback.core.util.StatusPrinter - -/** - * @author Ceki Gücü - */ -class SizeAndTimeBasedFNATP_STest extends RollingScaffolding { - private var sizeAndTimeBasedFNATP: SizeAndTimeBasedFNATP[AnyRef] = null - private val rfa1: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] - private val tbrp1: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] - private val rfa2: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] - private val tbrp2: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] - - private val encoder: EchoEncoder[AnyRef] = new EchoEncoder[AnyRef] - var fileSize = 0 - var fileIndexCounter = 0 - var sizeThreshold = 0 - - @Before - def setUp() { - setUpScaffolding - } - - private def initRollingFileAppender(rfa: RollingFileAppender[AnyRef], filename: String): Unit = { - rfa.setContext(context) - rfa.setEncoder(encoder) - if (filename != null) { - rfa.setFile(filename) - } - } - - private def initPolicies(rfa: RollingFileAppender[AnyRef], tbrp: TimeBasedRollingPolicy[AnyRef], filenamePattern: String, sizeThreshold: Int, givenTime: Long, lastCheck: Long): Unit = { - sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP[AnyRef] - tbrp.setContext(context) - sizeAndTimeBasedFNATP.setMaxFileSize("" + sizeThreshold) - tbrp.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP) - tbrp.setFileNamePattern(filenamePattern) - tbrp.setParent(rfa) - tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime) - rfa.setRollingPolicy(tbrp) - tbrp.start - rfa.start - } - - private def addExpectedFileNamedIfItsTime(randomOutputDir: String, testId: String, msg: String, compressionSuffix: String) { - fileSize = fileSize + msg.getBytes.length - if (passThresholdTime(nextRolloverThreshold)) { - fileIndexCounter = 0 - fileSize = 0 - addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) - recomputeRolloverThreshold(currentTime) - return - } - - // windows can delay file size changes, so we only allow for - // fileIndexCounter 0 - if ((fileIndexCounter < 1) && fileSize > sizeThreshold) { - addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) - fileIndexCounter = fileIndexCounter + 1 - fileSize = 0 - } - } - - def generic(testId: String, stem: String, withSecondPhase: Boolean, compressionSuffix: String = "") { - var file = if (stem != null) randomOutputDir + stem else null - initRollingFileAppender(rfa1, file) - sizeThreshold = 300 - initPolicies(rfa1, tbrp1, randomOutputDir + testId + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}-%i.txt"+compressionSuffix, sizeThreshold, currentTime, 0) - addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) - incCurrentTime(100) - tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) - var runLength: Int = 100 - var prefix: String = "Hello -----------------" - - for (i <- 0 until runLength) { - var msg: String = prefix + i - rfa1.doAppend(msg) - addExpectedFileNamedIfItsTime(randomOutputDir, testId, msg, compressionSuffix) - incCurrentTime(20) - tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) - } - - - if(withSecondPhase) { - secondPhase - runLength = runLength*2 - } - - if (stem != null) - massageExpectedFilesToCorresponToCurrentTarget(file, true) - - Thread.sleep(20) - // wait for compression to finish - if(tbrp1.future != null) { - tbrp1.future.get() - } - - StatusPrinter.print(context) - expectedFilenameList.foreach(println(_)) - existenceCheck(expectedFilenameList) - sortedContentCheck(randomOutputDir, runLength, prefix) - - def secondPhase() { - rfa1.stop(); - - if(stem != null) { - val f = new File(file); - f.setLastModified(currentTime); - } - - sm.add(new InfoStatus("Time when rfa1 is stopped: " + new Date(currentTime), this)); - sm.add(new InfoStatus("currentTime%1000=" + (currentTime % 1000), this)); - - initRollingFileAppender(rfa2, file); - initPolicies(rfa2, tbrp2, randomOutputDir + testId + "-%d{" - + DATE_PATTERN_WITH_SECONDS + "}-%i.txt"+compressionSuffix, sizeThreshold, currentTime, 0); - - for (i <- runLength until runLength * 2) { - incCurrentTime(100); - tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); - var msg = prefix + i - rfa2.doAppend(msg); - addExpectedFileNamedIfItsTime(randomOutputDir, testId, msg, compressionSuffix); - } - } - } - - val FIRST_PHASE_ONLY = false - val WITH_SECOND_PHASE = true - - @Test - def noCompression_FileSet_NoRestart_1 { - generic("test1", "toto.log", FIRST_PHASE_ONLY) - } - - @Test - def noCompression_FileBlank_NoRestart_2 { - generic("test2", null, FIRST_PHASE_ONLY) - } - - @Test - def noCompression_FileBlank_WithStopStart_3 { - generic("test3", null, WITH_SECOND_PHASE) - } - - @Test - def noCompression_FileSet_WithStopStart_4 { - generic("test4", "test4.log", WITH_SECOND_PHASE) - } - - @Test - def withGZCompression_FileSet_NoRestart_5 { - generic("test5", "toto.log", FIRST_PHASE_ONLY, ".gz") - } - - @Test - def withGZCompression_FileBlank_NoRestart_6 { - generic("test6", null, FIRST_PHASE_ONLY, ".gz") - } - - @Test - def withZipCompression_FileSet_NoRestart_7 { - generic("test7", "toto.log", FIRST_PHASE_ONLY, ".zip") - checkZipEntryMatchesZipFilename(expectedFilenameList.filter(_.endsWith(".zip")), "test7-20\\d{2}-\\d{2}-\\d{2}_\\d{2}_\\d{2}_\\d{2}-\\d") - - } -} +package ch.qos.logback.core.rolling + +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2011, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ + +import ch.qos.logback.core.encoder.EchoEncoder +import ch.qos.logback.core.status.InfoStatus +import java.util.Date +import org.junit.{Ignore, Test} +import org.junit.Before +import java.io.File +import ch.qos.logback.core.util.StatusPrinter + +/** + * @author Ceki Gücü + */ +class SizeAndTimeBasedFNATP_STest extends RollingScaffolding { + private var sizeAndTimeBasedFNATP: SizeAndTimeBasedFNATP[AnyRef] = null + private val rfa1: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] + private val tbrp1: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] + private val rfa2: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] + private val tbrp2: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] + + private val encoder: EchoEncoder[AnyRef] = new EchoEncoder[AnyRef] + var fileSize = 0 + var fileIndexCounter = 0 + var sizeThreshold = 0 + + @Before + def setUp() { + setUpScaffolding + } + + private def initRollingFileAppender(rfa: RollingFileAppender[AnyRef], filename: String): Unit = { + rfa.setContext(context) + rfa.setEncoder(encoder) + if (filename != null) { + rfa.setFile(filename) + } + } + + private def initPolicies(rfa: RollingFileAppender[AnyRef], tbrp: TimeBasedRollingPolicy[AnyRef], filenamePattern: String, sizeThreshold: Int, givenTime: Long, lastCheck: Long): Unit = { + sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP[AnyRef] + tbrp.setContext(context) + sizeAndTimeBasedFNATP.setMaxFileSize("" + sizeThreshold) + tbrp.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP) + tbrp.setFileNamePattern(filenamePattern) + tbrp.setParent(rfa) + tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime) + rfa.setRollingPolicy(tbrp) + tbrp.start + rfa.start + } + + private def addExpectedFileNamedIfItsTime(randomOutputDir: String, testId: String, msg: String, compressionSuffix: String) { + fileSize = fileSize + msg.getBytes.length + if (passThresholdTime(nextRolloverThreshold)) { + fileIndexCounter = 0 + fileSize = 0 + addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) + recomputeRolloverThreshold(currentTime) + return + } + + // windows can delay file size changes, so we only allow for + // fileIndexCounter 0 + if ((fileIndexCounter < 1) && fileSize > sizeThreshold) { + addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) + fileIndexCounter = fileIndexCounter + 1 + fileSize = 0 + } + } + + def generic(testId: String, stem: String, withSecondPhase: Boolean, compressionSuffix: String = "") { + var file = if (stem != null) randomOutputDir + stem else null + initRollingFileAppender(rfa1, file) + sizeThreshold = 300 + initPolicies(rfa1, tbrp1, randomOutputDir + testId + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}-%i.txt"+compressionSuffix, sizeThreshold, currentTime, 0) + addExpectedFileName_ByFileIndexCounter(randomOutputDir, testId, getMillisOfCurrentPeriodsStart, fileIndexCounter, compressionSuffix) + incCurrentTime(100) + tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) + var runLength: Int = 100 + var prefix: String = "Hello -----------------" + + for (i <- 0 until runLength) { + var msg: String = prefix + i + rfa1.doAppend(msg) + addExpectedFileNamedIfItsTime(randomOutputDir, testId, msg, compressionSuffix) + incCurrentTime(20) + tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) + } + + + if(withSecondPhase) { + secondPhase + runLength = runLength*2 + } + + if (stem != null) + massageExpectedFilesToCorresponToCurrentTarget(file, true) + + Thread.sleep(20) + // wait for compression to finish + if(tbrp1.future != null) { + tbrp1.future.get() + } + + StatusPrinter.print(context) + expectedFilenameList.foreach(println(_)) + existenceCheck(expectedFilenameList) + sortedContentCheck(randomOutputDir, runLength, prefix) + + def secondPhase() { + rfa1.stop(); + + if(stem != null) { + val f = new File(file); + f.setLastModified(currentTime); + } + + sm.add(new InfoStatus("Time when rfa1 is stopped: " + new Date(currentTime), this)); + sm.add(new InfoStatus("currentTime%1000=" + (currentTime % 1000), this)); + + initRollingFileAppender(rfa2, file); + initPolicies(rfa2, tbrp2, randomOutputDir + testId + "-%d{" + + DATE_PATTERN_WITH_SECONDS + "}-%i.txt"+compressionSuffix, sizeThreshold, currentTime, 0); + + for (i <- runLength until runLength * 2) { + incCurrentTime(100); + tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); + var msg = prefix + i + rfa2.doAppend(msg); + addExpectedFileNamedIfItsTime(randomOutputDir, testId, msg, compressionSuffix); + } + } + } + + val FIRST_PHASE_ONLY = false + val WITH_SECOND_PHASE = true + + @Test + def noCompression_FileSet_NoRestart_1 { + generic("test1", "toto.log", FIRST_PHASE_ONLY) + } + + @Test + def noCompression_FileBlank_NoRestart_2 { + generic("test2", null, FIRST_PHASE_ONLY) + } + + @Test + def noCompression_FileBlank_WithStopStart_3 { + generic("test3", null, WITH_SECOND_PHASE) + } + + @Test + def noCompression_FileSet_WithStopStart_4 { + generic("test4", "test4.log", WITH_SECOND_PHASE) + } + + @Test + def withGZCompression_FileSet_NoRestart_5 { + generic("test5", "toto.log", FIRST_PHASE_ONLY, ".gz") + } + + @Test + def withGZCompression_FileBlank_NoRestart_6 { + generic("test6", null, FIRST_PHASE_ONLY, ".gz") + } + + @Test + def withZipCompression_FileSet_NoRestart_7 { + generic("test7", "toto.log", FIRST_PHASE_ONLY, ".zip") + checkZipEntryMatchesZipFilename(expectedFilenameList.filter(_.endsWith(".zip")), "test7-20\\d{2}-\\d{2}-\\d{2}_\\d{2}_\\d{2}_\\d{2}-\\d") + + } +} diff --git a/logback-core/src/test/scala/ch/qos/logback/core/rolling/TimeBasedRolling_STest.scala b/logback-core/src/test/scala/ch/qos/logback/core/rolling/TimeBasedRolling_STest.scala index 2429013dabd918e0a1b20404c0de50ef6773ce38..cd3bd9a5cd37f221c8b6b95e61a5f5601c4bc228 100755 --- a/logback-core/src/test/scala/ch/qos/logback/core/rolling/TimeBasedRolling_STest.scala +++ b/logback-core/src/test/scala/ch/qos/logback/core/rolling/TimeBasedRolling_STest.scala @@ -1,209 +1,209 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2010, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * 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.rolling - -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import ch.qos.logback.core.encoder.EchoEncoder -import java.io.{FileOutputStream, File} -import ch.qos.logback.core.util.{StatusPrinter, Compare, CoreTestConstants} -import ch.qos.logback.core.testUtil.EnvUtilForTests -import java.security.PrivateKey - -class TimeBasedRolling_STest extends RollingScaffolding { - - private var rfa1: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] - private var tbrp1: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] - private var rfa2: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] - private var tbrp2: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] - - private var encoder: EchoEncoder[AnyRef] = new EchoEncoder[AnyRef] - - @Before - def setUp: Unit = { - setUpScaffolding - } - - private def initRFA(rfa: RollingFileAppender[AnyRef], filename: String): Unit = { - rfa.setContext(context) - rfa.setEncoder(encoder) - if (filename != null) { - rfa.setFile(filename) - } - } - - private def initTRBP(rfa: RollingFileAppender[AnyRef], tbrp: TimeBasedRollingPolicy[AnyRef], - filenamePattern: String, givenTime: Long): Unit = { - tbrp.setContext(context) - tbrp.setFileNamePattern(filenamePattern) - tbrp.setParent(rfa) - tbrp.timeBasedFileNamingAndTriggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy[AnyRef] - tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime) - rfa.setRollingPolicy(tbrp) - tbrp.start - rfa.start - } - - type CheckFunction = ((String, Boolean, String) => Unit) - def genericTest(checkFunction: CheckFunction)(testId: String, patternPrefix: String, compressionSuffix: String, fileOptionIsSet: Boolean, waitDuration: Int): Unit = { - val withCompression = compressionSuffix.length > 0 - val fileName = if (fileOptionIsSet) testId2FileName(testId) else null; - initRFA(rfa1, fileName); - - val 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 (i <- 0 until 3) { - rfa1.doAppend("Hello---" + i); - addExpectedFileNamedIfItsTime_ByDate(fileNamePatternStr) //, withCompression && (i != 2)) - incCurrentTime(500); - tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) - if (withCompression) - waitForCompression(tbrp1) - } - rfa1.stop - - if (waitDuration != NO_RESTART) { - doRestart(testId, patternPrefix, fileOptionIsSet, waitDuration); - } - - massageExpectedFilesToCorresponToCurrentTarget(fileName, fileOptionIsSet) - - StatusPrinter.print(context) - checkFunction(testId, withCompression, compressionSuffix) - } - - // defaultTest uses the defaultCheck function - val defaultTest = genericTest(defaultCheck)_ - - def defaultCheck(testId: String, withCompression: Boolean, compressionSuffix:String) = { - var i = 0; - for (fn <- expectedFilenameList) { - val suffix: String = if (withCompression) addGZIfNotLast(i, compressionSuffix) else "" - val witnessFileName: String = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId + "." + i.toString + suffix - assertTrue(Compare.compare(fn, witnessFileName)); - i += 1 - } - } - - def zCheck(testId: String, withCompression: Boolean, compressionSuffix:String) = { - val lastFile = expectedFilenameList.last - val witnessFileName: String = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId - println(lastFile+" "+witnessFileName) - assertTrue(Compare.compare(lastFile, witnessFileName)); - } - - - - def doRestart(testId: String, patternPart: String, fileOptionIsSet: Boolean, waitDuration: Int) { - // change the timestamp of the currently actively file - var activeFile: File = new File(rfa1.getFile) - activeFile.setLastModified(currentTime) - - incCurrentTime(waitDuration) - - val filePatternStr = randomOutputDir + patternPart + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}" - - val fileName = if (fileOptionIsSet) testId2FileName(testId) else null; - initRFA(rfa2, fileName) - initTRBP(rfa2, tbrp2, filePatternStr, currentTime) - for (i <- 0 until 3) { - rfa2.doAppend("World---" + i) - addExpectedFileNamedIfItsTime_ByDate(filePatternStr) - incCurrentTime(100) - tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) - } - rfa2.stop(); - } - - val NO_RESTART = 0 - val WITH_RESTART = 1 - val WITH_RESTART_AND_LONG_WAIT = 2000 - - @Test - def noCompression_FileBlank_NoRestart_1 = { - defaultTest("test1", "test1", "", FILE_OPTION_BLANK, NO_RESTART) - } - - @Test - def withCompression_FileBlank_NoRestart_2 = { - defaultTest("test2", "test2", ".gz", FILE_OPTION_BLANK, NO_RESTART); - } - - @Test - def noCompression_FileBlank_StopRestart_3 = { - defaultTest("test3", "test3", "", FILE_OPTION_BLANK, WITH_RESTART); - } - - @Test - def noCompression_FileSet_StopRestart_4 = { - defaultTest("test4", "test4", "", FILE_OPTION_SET, WITH_RESTART); - } - - @Test - def noCompression_FileSet_StopRestart_WithLongWait_4B = { - defaultTest("test4B", "test4B", "", FILE_OPTION_SET, WITH_RESTART_AND_LONG_WAIT); - } - - @Test - def noCompression_FileSet_NoRestart_5 = { - defaultTest("test5", "test6", "", FILE_OPTION_SET, NO_RESTART); - } - - @Test - def withCompression_FileSet_NoRestart_6 = { - defaultTest("test6", "test6", ".gz", FILE_OPTION_SET, NO_RESTART); - } - - // LBCORE-169 - @Test - def withMissingTargetDirWithCompression = { - defaultTest("test7", "%d{yyyy-MM-dd, aux}/", ".gz", FILE_OPTION_SET, NO_RESTART); - } - - @Test - def withMissingTargetDirWithZipCompression = { - defaultTest("test8", "%d{yyyy-MM-dd, aux}/", ".zip", FILE_OPTION_SET, NO_RESTART); - } - - @Test - def failed_rename: Unit = { - if(!EnvUtilForTests.isWindows) return - - var fos: FileOutputStream = null - try { - val fileName = testId2FileName("failed_rename"); - val file= new File(fileName) - file.getParentFile.mkdirs - - fos = new FileOutputStream(fileName) - genericTest(zCheck)("failed_rename", "failed_rename", "", FILE_OPTION_SET, NO_RESTART) - - } finally { - StatusPrinter.print(context) - if(fos != null) fos.close; - } - } - - - +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2010, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * 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.rolling + +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import ch.qos.logback.core.encoder.EchoEncoder +import java.io.{FileOutputStream, File} +import ch.qos.logback.core.util.{StatusPrinter, Compare, CoreTestConstants} +import ch.qos.logback.core.testUtil.EnvUtilForTests +import java.security.PrivateKey + +class TimeBasedRolling_STest extends RollingScaffolding { + + private var rfa1: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] + private var tbrp1: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] + private var rfa2: RollingFileAppender[AnyRef] = new RollingFileAppender[AnyRef] + private var tbrp2: TimeBasedRollingPolicy[AnyRef] = new TimeBasedRollingPolicy[AnyRef] + + private var encoder: EchoEncoder[AnyRef] = new EchoEncoder[AnyRef] + + @Before + def setUp: Unit = { + setUpScaffolding + } + + private def initRFA(rfa: RollingFileAppender[AnyRef], filename: String): Unit = { + rfa.setContext(context) + rfa.setEncoder(encoder) + if (filename != null) { + rfa.setFile(filename) + } + } + + private def initTRBP(rfa: RollingFileAppender[AnyRef], tbrp: TimeBasedRollingPolicy[AnyRef], + filenamePattern: String, givenTime: Long): Unit = { + tbrp.setContext(context) + tbrp.setFileNamePattern(filenamePattern) + tbrp.setParent(rfa) + tbrp.timeBasedFileNamingAndTriggeringPolicy = new DefaultTimeBasedFileNamingAndTriggeringPolicy[AnyRef] + tbrp.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(givenTime) + rfa.setRollingPolicy(tbrp) + tbrp.start + rfa.start + } + + type CheckFunction = ((String, Boolean, String) => Unit) + def genericTest(checkFunction: CheckFunction)(testId: String, patternPrefix: String, compressionSuffix: String, fileOptionIsSet: Boolean, waitDuration: Int): Unit = { + val withCompression = compressionSuffix.length > 0 + val fileName = if (fileOptionIsSet) testId2FileName(testId) else null; + initRFA(rfa1, fileName); + + val 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 (i <- 0 until 3) { + rfa1.doAppend("Hello---" + i); + addExpectedFileNamedIfItsTime_ByDate(fileNamePatternStr) //, withCompression && (i != 2)) + incCurrentTime(500); + tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) + if (withCompression) + waitForCompression(tbrp1) + } + rfa1.stop + + if (waitDuration != NO_RESTART) { + doRestart(testId, patternPrefix, fileOptionIsSet, waitDuration); + } + + massageExpectedFilesToCorresponToCurrentTarget(fileName, fileOptionIsSet) + + StatusPrinter.print(context) + checkFunction(testId, withCompression, compressionSuffix) + } + + // defaultTest uses the defaultCheck function + val defaultTest = genericTest(defaultCheck)_ + + def defaultCheck(testId: String, withCompression: Boolean, compressionSuffix:String) = { + var i = 0; + for (fn <- expectedFilenameList) { + val suffix: String = if (withCompression) addGZIfNotLast(i, compressionSuffix) else "" + val witnessFileName: String = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId + "." + i.toString + suffix + assertTrue(Compare.compare(fn, witnessFileName)); + i += 1 + } + } + + def zCheck(testId: String, withCompression: Boolean, compressionSuffix:String) = { + val lastFile = expectedFilenameList.last + val witnessFileName: String = CoreTestConstants.TEST_SRC_PREFIX + "witness/rolling/tbr-" + testId + println(lastFile+" "+witnessFileName) + assertTrue(Compare.compare(lastFile, witnessFileName)); + } + + + + def doRestart(testId: String, patternPart: String, fileOptionIsSet: Boolean, waitDuration: Int) { + // change the timestamp of the currently actively file + var activeFile: File = new File(rfa1.getFile) + activeFile.setLastModified(currentTime) + + incCurrentTime(waitDuration) + + val filePatternStr = randomOutputDir + patternPart + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}" + + val fileName = if (fileOptionIsSet) testId2FileName(testId) else null; + initRFA(rfa2, fileName) + initTRBP(rfa2, tbrp2, filePatternStr, currentTime) + for (i <- 0 until 3) { + rfa2.doAppend("World---" + i) + addExpectedFileNamedIfItsTime_ByDate(filePatternStr) + incCurrentTime(100) + tbrp2.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime) + } + rfa2.stop(); + } + + val NO_RESTART = 0 + val WITH_RESTART = 1 + val WITH_RESTART_AND_LONG_WAIT = 2000 + + @Test + def noCompression_FileBlank_NoRestart_1 = { + defaultTest("test1", "test1", "", FILE_OPTION_BLANK, NO_RESTART) + } + + @Test + def withCompression_FileBlank_NoRestart_2 = { + defaultTest("test2", "test2", ".gz", FILE_OPTION_BLANK, NO_RESTART); + } + + @Test + def noCompression_FileBlank_StopRestart_3 = { + defaultTest("test3", "test3", "", FILE_OPTION_BLANK, WITH_RESTART); + } + + @Test + def noCompression_FileSet_StopRestart_4 = { + defaultTest("test4", "test4", "", FILE_OPTION_SET, WITH_RESTART); + } + + @Test + def noCompression_FileSet_StopRestart_WithLongWait_4B = { + defaultTest("test4B", "test4B", "", FILE_OPTION_SET, WITH_RESTART_AND_LONG_WAIT); + } + + @Test + def noCompression_FileSet_NoRestart_5 = { + defaultTest("test5", "test6", "", FILE_OPTION_SET, NO_RESTART); + } + + @Test + def withCompression_FileSet_NoRestart_6 = { + defaultTest("test6", "test6", ".gz", FILE_OPTION_SET, NO_RESTART); + } + + // LBCORE-169 + @Test + def withMissingTargetDirWithCompression = { + defaultTest("test7", "%d{yyyy-MM-dd, aux}/", ".gz", FILE_OPTION_SET, NO_RESTART); + } + + @Test + def withMissingTargetDirWithZipCompression = { + defaultTest("test8", "%d{yyyy-MM-dd, aux}/", ".zip", FILE_OPTION_SET, NO_RESTART); + } + + @Test + def failed_rename: Unit = { + if(!EnvUtilForTests.isWindows) return + + var fos: FileOutputStream = null + try { + val fileName = testId2FileName("failed_rename"); + val file= new File(fileName) + file.getParentFile.mkdirs + + fos = new FileOutputStream(fileName) + genericTest(zCheck)("failed_rename", "failed_rename", "", FILE_OPTION_SET, NO_RESTART) + + } finally { + StatusPrinter.print(context) + if(fos != null) fos.close; + } + } + + + } \ No newline at end of file