CVE-2021-21234: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (CWE-22)
value: spring-boot-actuator-logview in a library that adds a simple logfile viewer as spring boot actuator endpoint. It is maven package "eu.hinsch:spring-boot-actuator-logview". In spring-boot-actuator-logview before version 0.2.13 there is a directory traversal vulnerability. The nature of this library is to expose a log file directory via admin (spring boot actuator) HTTP endpoints. Both the filename to view and a base folder (relative to the logging folder root) can be specified via request parameters. While the filename parameter was checked to prevent directory traversal exploits (so that `filename=../somefile` would not work), the base folder parameter was not sufficiently checked, so that `filename=somefile&base=../` could access a file outside the logging base directory). The vulnerability has been patched in release 0.2.13. Any users of 0.2.12 should be able to update without any issues as there are no other changes in that release. There is no workaround to fix the vulnerability other than updating or removing the dependency. However, removing read access of the user the application is run with to any directory not required for running the application can limit the impact. Additionally, access to the logview endpoint can be limited by deploying the application behind a reverse proxy.
CWE description: The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
CVSS v3 base score: 7.7
Published: 2021-01-05T18:15Z
Repository: https://github.com/lukashinsch/spring-boot-actuator-logview
Language: Java
Files changed: .gitignore, .travis.yml, CHANGELOG.md, LICENSE, README.md, build.gradle, gradle/wrapper/gradle-wrapper.properties, gradlew, gradlew.bat, lib/lib.gradle, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/AbstractFileProvider.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileEntry.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileProvider.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileSystemFileProvider.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileType.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpoint.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfig.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/SortBy.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/TarGzArchiveFileProvider.java, lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/ZipArchiveFileProvider.java, lib/src/main/resources/META-INF/spring-configuration-metadata.json, lib/src/main/resources/META-INF/spring.factories, lib/src/main/resources/templates/logview.ftl, lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfigTest.java, lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointTest.java, settings.gradle, src/main/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplication.java, src/main/resources/application.yml, src/test/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplicationTests.java
Commit date: 2021-01-01 22:46:05 +0100
Commit message: Merge pull request #30 from lukashinsch/hotfix/dir-traversal

backport directory traversal vulnerability fix
Diff: diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2279dbe
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+.gradle
+.idea
+*.iml
+build/
+out/
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..2de67b2
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,6 @@
+language: java
+jdk:
+  - openjdk8
+
+after_success:
+  - ./gradlew lib:jacocoTestReport lib:coveralls
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..377225d
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,47 @@
+# spring-boot-actuator-logview changelog
+
+## 0.2.12
+- support logfile configuration via logging.file property (thanks @oyvindhorneland)
+
+## 0.2.11
+- Set missing content type in search result
+
+## 0.2.10
+- Set content type in log response (fixes [#21](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/21))
+- Prettify file size display (fixes [#23](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/23))
+
+## 0.2.9
+- Add configuration option to override stylesheet urls (fixes [#20](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/20))
+
+## 0.2.8
+- Remove tail option for files inside archives in UI (lead to 500 error before) (fixes [#17](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/17))
+
+## 0.2.7
+- Correctly encode file/dir names in urls (fixes - [#19](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/19))
+
+## 0.2.6
+- Fixed display issue with illegal whitespace
+- Fix cdn url
+
+## 0.2.5
+- allow downloading only the last 50 lines of each file (closes [#13](https://github.com/lukashinsch/spring-boot-actuator-logview/pull/13))
+
+## 0.2.4
+- show file content when calling endpoint url without trailing slash (fixes [#11](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/11))
+- allow to specify logging path via "endpoints.logview.path" property (fixes [#3](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/3)
+
+## 0.2.3
+- don't require trailing slash in endpoint url ("/log" instead of "/log/")
+
+## 0.2.2
+- allow viewing logfiles in subfolders inside archives
+
+## 0.2.1
+- switch to use dedicated freemarker config to allow loading template from jar
+- use spring boot autoconfig
+
+## 0.2
+- basic support for searching logfiles (no archives, no subfolders)
+
+## 0.1
+- initial release
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f3b9266
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Lukas Hinsch
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b79ad68
--- /dev/null
+++ b/README.md
@@ -0,0 +1,45 @@
+[![Coverage Status](https://coveralls.io/repos/lukashinsch/spring-boot-actuator-logview/badge.svg?branch=master)](https://coveralls.io/r/lukashinsch/spring-boot-actuator-logview?branch=master)
+[![Build Status](https://travis-ci.org/lukashinsch/spring-boot-actuator-logview.svg?branch=master)](https://travis-ci.org/lukashinsch/spring-boot-actuator-logview)
+[![Maven Central](https://maven-badges.herokuapp.com/maven-central/eu.hinsch/spring-boot-actuator-logview/badge.svg)](https://maven-badges.herokuapp.com/maven-central/eu.hinsch/spring-boot-actuator-logview/)
+
+# spring-boot-actuator-logview
+Simple logfile viewer as spring boot actuator endpoint
+
+##Features
+* allow quick access to spring-boot web application logfiles
+* uses actuator framework to provide management endpoint
+* list log folder content
+* view individual logfiles
+* view content of log archives (*.zip, *.tar.gz)
+* browse subdirectories
+* search in (non-compressed) files in logging root folder
+* tail without reading entire file
+
+![screenshot](img/screenshot.png)
+
+##Howto use
+* include library on classpath of spring-boot app
+* configure `logging.path`, `logging.file` or `endpoints.logview.path` in spring environment
+    * `logging.file` specifies a custom log file. Logviewer will use it's parent directory.
+    * `logging.path` specifies a log directory and log filename `spring.log`.
+    * `endpoints.logview.path` specifies a directory containing log files in case you use other custom log configurations.
+* endpoint will be available under <management-base>/log
+* to replace default stylesheet links, set property `endpoints.logview.stylesheets` in yml to list of urls
+
+###Gradle
+```groovy
+compile 'eu.hinsch:spring-boot-actuator-logview:0.2.12'
+```
+
+###Maven
+```xml
+<dependency>
+    <groupId>eu.hinsch</groupId>
+    <artifactId>spring-boot-actuator-logview</artifactId>
+    <version>0.2.12</version>
+</dependency>
+```
+
+
+Note
+* lib depends on spring-boot-starter-freemarker, so it may currently not work with another templating engine for the main app
diff --git a/build.gradle b/build.gradle
new file mode 100644
index 0000000..a891dab
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,50 @@
+buildscript {
+    ext {
+        springBootVersion = '1.2.1.RELEASE'
+        springLoadedVersion = '1.2.1.RELEASE'
+    }
+    repositories {
+        mavenCentral()
+    }
+    dependencies {
+        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
+        classpath("org.springframework:springloaded:${springLoadedVersion}")
+        classpath("org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1")
+    }
+}
+
+apply plugin: 'java'
+apply plugin: 'idea'
+apply plugin: 'spring-boot'
+
+
+jar {
+    baseName = 'spring-boot-actuator-logview-sample'
+    version = '0.0.1-SNAPSHOT'
+}
+
+sourceCompatibility = 1.8
+targetCompatibility = 1.8
+
+repositories {
+    mavenCentral()
+}
+
+
+dependencies {
+    compile project("lib")
+
+    testCompile("org.springframework.boot:spring-boot-starter-test")
+}
+
+
+idea {
+    module {
+        inheritOutputDirs = false
+        outputDir = file("$buildDir/classes/main/")
+    }
+}
+
+task wrapper(type: Wrapper) {
+    gradleVersion = '2.3'
+}
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..085a1cd
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..90a94cb
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Fri Mar 13 22:18:34 CET 2015
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-bin.zip
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..91a7e26
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,164 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+##  Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+    echo "$*"
+}
+
+die ( ) {
+    echo
+    echo "$*"
+    echo
+    exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+  CYGWIN* )
+    cygwin=true
+    ;;
+  Darwin* )
+    darwin=true
+    ;;
+  MINGW* )
+    msys=true
+    ;;
+esac
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched.
+if $cygwin ; then
+    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+fi
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+        PRG="$link"
+    else
+        PRG=`dirname "$PRG"`"/$link"
+    fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >&-
+APP_HOME="`pwd -P`"
+cd "$SAVED" >&-
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+        # IBM's JDK on AIX uses strange locations for the executables
+        JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+        JAVACMD="$JAVA_HOME/bin/java"
+    fi
+    if [ ! -x "$JAVACMD" ] ; then
+        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+    fi
+else
+    JAVACMD="java"
+    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+    MAX_FD_LIMIT=`ulimit -H -n`
+    if [ $? -eq 0 ] ; then
+        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+            MAX_FD="$MAX_FD_LIMIT"
+        fi
+        ulimit -n $MAX_FD
+        if [ $? -ne 0 ] ; then
+            warn "Could not set maximum file descriptor limit: $MAX_FD"
+        fi
+    else
+        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+    fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
+    # We build the pattern for arguments to be converted via cygpath
+    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+    SEP=""
+    for dir in $ROOTDIRSRAW ; do
+        ROOTDIRS="$ROOTDIRS$SEP$dir"
+        SEP="|"
+    done
+    OURCYGPATTERN="(^($ROOTDIRS))"
+    # Add a user-defined pattern to the cygpath arguments
+    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+    fi
+    # Now convert the arguments - kludge to limit ourselves to /bin/sh
+    i=0
+    for arg in "$@" ; do
+        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option
+
+        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
+            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+        else
+            eval `echo args$i`="\"$arg\""
+        fi
+        i=$((i+1))
+    done
+    case $i in
+        (0) set -- ;;
+        (1) set -- "$args0" ;;
+        (2) set -- "$args0" "$args1" ;;
+        (3) set -- "$args0" "$args1" "$args2" ;;
+        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+    esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+    JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..8a0b282
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem  Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/img/screenshot.png b/img/screenshot.png
new file mode 100644
index 0000000..62d1888
Binary files /dev/null and b/img/screenshot.png differ
diff --git a/lib/lib.gradle b/lib/lib.gradle
new file mode 100644
index 0000000..0317de7
--- /dev/null
+++ b/lib/lib.gradle
@@ -0,0 +1,134 @@
+buildscript {
+    repositories {
+        mavenCentral()
+    }
+    dependencies {
+        classpath("org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1")
+    }
+}
+
+apply plugin: 'java'
+apply plugin: 'idea'
+apply plugin: 'jacoco'
+apply plugin: 'com.github.kt3k.coveralls'
+
+ext {
+    springBootVersion = '1.2.1.RELEASE'
+    libVersion = '0.2.12'
+}
+
+jar {
+    baseName = 'spring-boot-actuator-logview'
+    version = libVersion
+}
+
+sourceCompatibility = 1.8
+targetCompatibility = 1.8
+
+repositories {
+    mavenCentral()
+}
+
+dependencies {
+    compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
+    compile("org.springframework.boot:spring-boot-starter-freemarker:${springBootVersion}")
+    compile("org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}")
+    compile("org.ocpsoft.prettytime:prettytime:3.2.7.Final")
+    compile("commons-io:commons-io:2.4")
+    compile("org.apache.commons:commons-compress:1.9")
+
+    testCompile("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
+}
+
+
+idea {
+    module {
+        inheritOutputDirs = false
+        outputDir = file("$buildDir/classes/main/")
+    }
+}
+
+jacocoTestReport {
+    reports {
+        xml.enabled = true // coveralls plugin depends on xml format report
+        html.enabled = true
+    }
+}
+
+test {
+    testLogging {
+        events "failed"
+        exceptionFormat "full" // show assertion errors in build
+    }
+}
+
+// sign and publish to MC is done only locally so far
+
+if (System.getenv('CI') != 'true') {
+
+    apply plugin: 'signing'
+    apply plugin: 'maven'
+
+    group = 'eu.hinsch'
+    version = libVersion
+
+    task javadocJar(type: Jar, dependsOn: javadoc) {
+        classifier = 'javadoc'
+        from tasks.javadoc.destinationDir
+    }
+
+    task sourcesJar(type: Jar) {
+        from sourceSets.main.allSource
+        classifier = 'sources'
+    }
+
+    artifacts {
+        archives jar
+        archives javadocJar
+        archives sourcesJar
+    }
+
+    signing {
+        sign configurations.archives
+    }
+
+    uploadArchives {
+        repositories {
+            mavenDeployer {
+                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
+
+                repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
+                    authentication(userName: sonatypeUsername, password: sonatypePassword)
+                }
+
+                pom.project {
+                    name 'spring-boot-actuator-logview'
+                    packaging 'jar'
+                    description 'simple logfile viewer as spring boot actuator endpoint'
+                    url 'https://github.com/lukashinsch/spring-boot-actuator-logview/'
+
+                    scm {
+                        url 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
+                        connection 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
+                        developerConnection 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
+                    }
+
+                    licenses {
+                        license {
+                            name 'MIT License'
+                            url 'http://www.opensource.org/licenses/mit-license.php'
+                            distribution 'repo'
+                        }
+                    }
+
+                    developers {
+                        developer {
+                            id 'lukashinsch'
+                            name 'Lukas Hinsch'
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/AbstractFileProvider.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/AbstractFileProvider.java
new file mode 100644
index 0000000..ffd52f9
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/AbstractFileProvider.java
@@ -0,0 +1,24 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.ocpsoft.prettytime.PrettyTime;
+
+import java.nio.file.Path;
+
+/**
+* Created by lh on 28/02/15.
+*/
+public abstract class AbstractFileProvider implements FileProvider {
+    protected static final PrettyTime prettyTime = new PrettyTime();
+
+    protected boolean isArchive(Path path) {
+        return isZip(path) || isTarGz(path);
+    }
+
+    protected boolean isTarGz(Path path) {
+        return !path.toFile().isDirectory() && path.getFileName().toString().endsWith(".tar.gz");
+    }
+
+    protected boolean isZip(Path path) {
+        return !path.toFile().isDirectory() && path.getFileName().toString().endsWith(".zip");
+    }
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileEntry.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileEntry.java
new file mode 100644
index 0000000..ad05fd4
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileEntry.java
@@ -0,0 +1,70 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.apache.commons.io.FileUtils;
+
+import java.nio.file.attribute.FileTime;
+
+/**
+* Created by lh on 26/02/15.
+*/
+public class FileEntry {
+    private String filename;
+    private String displayFilename;
+    private FileTime modified;
+    private String modifiedPretty;
+    private long size;
+    private FileType fileType;
+
+    public String getFilename() {
+        return filename;
+    }
+
+    public void setFilename(String filename) {
+        this.filename = filename;
+    }
+
+    public FileTime getModified() {
+        return modified;
+    }
+
+    public void setModified(FileTime modified) {
+        this.modified = modified;
+    }
+
+    public long getSize() {
+        return size;
+    }
+
+    public void setSize(long size) {
+        this.size = size;
+    }
+
+    public String getModifiedPretty() {
+        return modifiedPretty;
+    }
+
+    public void setModifiedPretty(String modifiedPretty) {
+        this.modifiedPretty = modifiedPretty;
+    }
+
+    public FileType getFileType() {
+        return fileType;
+    }
+
+    public void setFileType(FileType fileType) {
+        this.fileType = fileType;
+    }
+
+    public void setDisplayFilename(String displayFilename) {
+        this.displayFilename = displayFilename;
+    }
+
+    public String getDisplayFilename() {
+        return displayFilename;
+    }
+
+    public String getSizePretty() {
+        return FileUtils.byteCountToDisplaySize(size);
+    }
+
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileProvider.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileProvider.java
new file mode 100644
index 0000000..58c0307
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileProvider.java
@@ -0,0 +1,22 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Path;
+import java.util.List;
+
+/**
+* Created by lh on 28/02/15.
+*/
+public interface FileProvider {
+
+    boolean canHandle(Path folder);
+
+    List<FileEntry> getFileEntries(Path folder) throws IOException;
+
+    void streamContent(Path folder, String filename, OutputStream stream) throws IOException;
+
+    default void tailContent(Path folder, String filename, OutputStream stream, int lines) throws IOException {
+        throw new UnsupportedOperationException("by default no tailing possible");
+    }
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileSystemFileProvider.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileSystemFileProvider.java
new file mode 100644
index 0000000..1af7ffb
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileSystemFileProvider.java
@@ -0,0 +1,89 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.input.ReversedLinesFileReader;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+/**
+* Created by lh on 28/02/15.
+*/
+public class FileSystemFileProvider extends AbstractFileProvider {
+
+    @Override
+    public boolean canHandle(Path folder) {
+        return folder.toFile().isDirectory();
+    }
+
+    @Override
+    public List<FileEntry> getFileEntries(Path loggingPath) throws IOException {
+        final List<FileEntry> files = new ArrayList<>();
+        Files.newDirectoryStream(loggingPath)
+                .forEach((path) -> files.add(createFileEntry(path)));
+        return files;
+    }
+
+    private FileEntry createFileEntry(Path path)  {
+        final FileEntry fileEntry = new FileEntry();
+        try {
+            fileEntry.setFilename(URLEncoder.encode(path.getFileName().toString(), "UTF-8"));
+            fileEntry.setDisplayFilename(path.getFileName().toString());
+            fileEntry.setModified(Files.getLastModifiedTime(path));
+            fileEntry.setSize(Files.size(path));
+        } catch (IOException e) {
+            throw new RuntimeException("unable to retrieve file attribute", e);
+        }
+        fileEntry.setModifiedPretty(prettyTime.format(new Date(fileEntry.getModified().toMillis())));
+        fileEntry.setFileType(getFileType(path));
+
+        return fileEntry;
+    }
+
+    private FileType getFileType(Path path) {
+        FileType fileType;
+        if (path.toFile().isDirectory()) {
+            fileType = FileType.DIRECTORY;
+        }
+        else if (isArchive(path)) {
+            fileType = FileType.ARCHIVE;
+        }
+        else {
+            fileType = FileType.FILE;
+        }
+        return fileType;
+    }
+
+    @Override
+    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
+        IOUtils.copy(new FileInputStream(getFile(folder, filename)), stream);
+    }
+
+    private File getFile(Path folder, String filename) {
+        return Paths.get(folder.toString(), filename).toFile();
+    }
+
+    @Override
+    public void tailContent(Path folder, String filename, OutputStream stream, int lines) throws IOException {
+        try (ReversedLinesFileReader reader = new ReversedLinesFileReader(getFile(folder, filename))) {
+            int i = 0;
+            String line;
+            List<String> content = new ArrayList<>();
+            while ((line = reader.readLine()) != null && i++ < lines) {
+                content.add(line);
+            }
+            Collections.reverse(content);
+            IOUtils.writeLines(content, System.lineSeparator(), stream);
+        }
+    }
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileType.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileType.java
new file mode 100644
index 0000000..2920e48
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/FileType.java
@@ -0,0 +1,8 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+/**
+* Created by lh on 26/02/15.
+*/
+public enum FileType {
+    FILE, DIRECTORY, ARCHIVE
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpoint.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpoint.java
new file mode 100644
index 0000000..493f07d
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpoint.java
@@ -0,0 +1,201 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import freemarker.template.Configuration;
+import freemarker.template.TemplateException;
+import org.apache.commons.io.IOUtils;
+import org.springframework.boot.actuate.endpoint.Endpoint;
+import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
+import org.springframework.http.MediaType;
+import org.springframework.ui.Model;
+import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
+import org.springframework.util.Assert;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import static java.util.Arrays.asList;
+import static java.util.stream.Collectors.toList;
+
+/**
+ * Created by lh on 23/02/15.
+ */
+public class LogViewEndpoint implements MvcEndpoint{
+
+    private final List<FileProvider> fileProviders;
+    private final Configuration freemarkerConfig;
+    private final String loggingPath;
+    private final List<String> stylesheets;
+
+    public LogViewEndpoint(String loggingPath, List<String> stylesheets) {
+        this.loggingPath = loggingPath;
+        this.stylesheets = stylesheets;
+        fileProviders = asList(new FileSystemFileProvider(),
+                new ZipArchiveFileProvider(),
+                new TarGzArchiveFileProvider());
+        freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
+        freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates");
+    }
+
+    @RequestMapping
+    public void redirect(HttpServletResponse response) throws IOException {
+        response.sendRedirect("log/");
+    }
+
+    @RequestMapping("/")
+    @ResponseBody
+    public String list(Model model, // TODO model should no longer be injected
+                       @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
+                       @RequestParam(required = false, defaultValue = "false") boolean desc,
+                       @RequestParam(required = false) String base) throws IOException, TemplateException {
+        Path currentFolder = loggingPath(base);
+        securityCheck(currentFolder, null);
+
+
+        List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
+        List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);
+
+        model.addAttribute("sortBy", sortBy);
+        model.addAttribute("desc", desc);
+        model.addAttribute("files", sortedFiles);
+        model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
+        model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
+        model.addAttribute("parent", getParent(currentFolder));
+        model.addAttribute("stylesheets", stylesheets);
+
+        return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
+    }
+
+    private FileProvider getFileProvider(Path folder) {
+        return fileProviders.stream()
+                .filter(provider -> provider.canHandle(folder))
+                .findFirst()
+                .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString()));
+    }
+
+    private String getParent(Path loggingPath) {
+        Path basePath = loggingPath(null);
+        String parent = "";
+        if (!basePath.toString().equals(loggingPath.toString())) {
+            parent = loggingPath.getParent().toString();
+            if (parent.startsWith(basePath.toString())) {
+                parent = parent.substring(basePath.toString().length());
+            }
+        }
+        return parent;
+    }
+
+    private Path loggingPath(String base) {
+        return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath);
+    }
+
+    private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) {
+        Comparator<FileEntry> comparator = null;
+        switch (sortBy) {
+            case FILENAME:
+                comparator = (a, b) -> a.getFilename().compareTo(b.getFilename());
+                break;
+            case SIZE:
+                comparator = (a, b) -> Long.compare(a.getSize(), b.getSize());
+                break;
+            case MODIFIED:
+                comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis());
+                break;
+        }
+        List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList());
+
+        if (desc) {
+            Collections.reverse(sortedFiles);
+        }
+        return sortedFiles;
+    }
+
+    @RequestMapping("/view")
+    public void view(@RequestParam String filename,
+                     @RequestParam(required = false) String base,
+                     @RequestParam(required = false) Integer tailLines,
+                     HttpServletResponse response) throws IOException {
+
+        Path path = loggingPath(base);
+        securityCheck(path, filename);
+        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
+        FileProvider fileProvider = getFileProvider(path);
+        if (tailLines != null) {
+            fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines);
+        }
+        else {
+            fileProvider.streamContent(path, filename, response.getOutputStream());
+        }
+    }
+
+    @RequestMapping("/search")
+    public void search(@RequestParam String term, HttpServletResponse response) throws IOException {
+        Path folder = loggingPath(null);
+        List<FileEntry> files = getFileProvider(folder).getFileEntries(folder);
+        List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false);
+
+        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
+        ServletOutputStream outputStream = response.getOutputStream();
+
+        sortedFiles.stream()
+                .filter(file -> file.getFileType().equals(FileType.FILE))
+                .forEach(file -> searchAndStreamFile(file, term, outputStream));
+    }
+
+    private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) {
+        Path folder = loggingPath(null);
+        try {
+            List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename())))
+                    .stream()
+                    .filter(line -> line.contains(term))
+                    .map(line -> "[" + fileEntry.getFilename() + "] " + line)
+                    .collect(toList());
+            for (String line : lines) {
+                outputStream.write(line.getBytes());
+                outputStream.write(System.lineSeparator().getBytes());
+            }
+        } catch (IOException e) {
+            throw new RuntimeException("error reading file", e);
+        }
+    }
+
+    private void securityCheck(Path base, String filename) {
+        try {
+            String canonicalLoggingPath = (filename != null ? new File(base.toFile().toString(), filename) : new File(base.toFile().toString())).getCanonicalPath();
+            String baseCanonicalPath = new File(loggingPath).getCanonicalPath();
+            String errorMessage = "File " + base.toString() + "/" + filename + " may not be located outside base path " + loggingPath;
+            Assert.isTrue(canonicalLoggingPath.startsWith(baseCanonicalPath), errorMessage);
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    @Override
+    public String getPath() {
+        return "/log";
+    }
+
+    @Override
+    public boolean isSensitive() {
+        return true;
+    }
+
+
+    @Override
+    public Class<? extends Endpoint> getEndpointType() {
+        return null;
+    }
+
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfig.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfig.java
new file mode 100644
index 0000000..06785e5
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfig.java
@@ -0,0 +1,68 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Component;
+
+import java.io.File;
+import java.util.List;
+
+import static java.util.Arrays.asList;
+
+@Configuration
+public class LogViewEndpointAutoconfig {
+
+    public static final String LOGGING_FILE = "logging.file";
+    public static final String LOGGING_PATH = "logging.path";
+    public static final String ENDPOINTS_LOGVIEW_PATH = "endpoints.logview.path";
+
+    @ConditionalOnProperty(LOGGING_FILE)
+    @ConditionalOnMissingBean(LogViewEndpoint.class)
+    @Bean
+    public LogViewEndpoint logViewEndpointWithDefaultFile(Environment environment, EndpointConfiguration configuration) {
+        String logDirectory = new File(environment.getRequiredProperty(LOGGING_FILE)).getParentFile().getAbsolutePath();
+        return new LogViewEndpoint(logDirectory, configuration.getStylesheets());
+    }
+
+    @ConditionalOnProperty(LOGGING_PATH)
+    @ConditionalOnMissingBean(LogViewEndpoint.class)
+    @Bean
+    public LogViewEndpoint logViewEndpointWithDefaultPath(Environment environment, EndpointConfiguration configuration) {
+        return new LogViewEndpoint(environment.getRequiredProperty(LOGGING_PATH), configuration.getStylesheets());
+    }
+
+    @ConditionalOnProperty(ENDPOINTS_LOGVIEW_PATH)
+    @ConditionalOnMissingBean(LogViewEndpoint.class)
+    @Bean
+    public LogViewEndpoint logViewEndpointWithDeviatingPath(Environment environment, EndpointConfiguration configuration) {
+        return new LogViewEndpoint(configuration.getPath(), configuration.getStylesheets());
+    }
+
+    @Component
+    @ConfigurationProperties(prefix = "endpoints.logview")
+    static class EndpointConfiguration {
+        private List<String> stylesheets = asList("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css",
+                "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css");
+        private String path;
+
+        public List<String> getStylesheets() {
+            return stylesheets;
+        }
+
+        public void setStylesheets(List<String> stylesheets) {
+            this.stylesheets = stylesheets;
+        }
+
+        public String getPath() {
+            return path;
+        }
+
+        public void setPath(String path) {
+            this.path = path;
+        }
+    }
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/SortBy.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/SortBy.java
new file mode 100644
index 0000000..f09ad32
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/SortBy.java
@@ -0,0 +1,8 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+/**
+* Created by lh on 26/02/15.
+*/
+public enum SortBy {
+    FILENAME, SIZE, MODIFIED
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/TarGzArchiveFileProvider.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/TarGzArchiveFileProvider.java
new file mode 100644
index 0000000..93c2abe
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/TarGzArchiveFileProvider.java
@@ -0,0 +1,63 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.io.IOUtils;
+
+import java.io.*;
+import java.net.URLEncoder;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.zip.GZIPInputStream;
+
+/**
+* Created by lh on 28/02/15.
+*/
+public class TarGzArchiveFileProvider extends AbstractFileProvider {
+
+    @Override
+    public boolean canHandle(Path folder) {
+        return isTarGz(folder);
+    }
+
+    @Override
+    public List<FileEntry> getFileEntries(Path folder) throws IOException {
+        TarArchiveInputStream inputStream = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(folder.toFile())));
+        TarArchiveEntry entry;
+        List<FileEntry> files = new ArrayList<>();
+        while ((entry = inputStream.getNextTarEntry()) != null) {
+            files.add(createFileEntry(entry));
+        }
+        return files;
+    }
+
+    private static FileEntry createFileEntry(TarArchiveEntry entry) {
+        FileEntry fileEntry = new FileEntry();
+        try {
+            fileEntry.setFilename(URLEncoder.encode(entry.getName(), "UTF-8"));
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("encoding error", e);
+        }
+        fileEntry.setDisplayFilename(entry.getName());
+        fileEntry.setSize(entry.getSize());
+        fileEntry.setFileType(entry.isDirectory() ? FileType.DIRECTORY : FileType.FILE);
+        fileEntry.setModified(FileTime.fromMillis(entry.getLastModifiedDate().getTime()));
+        fileEntry.setModifiedPretty(prettyTime.format(new Date(entry.getLastModifiedDate().getTime())));
+        return fileEntry;
+    }
+
+    @Override
+    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
+        TarArchiveInputStream tarStream = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(folder.toFile())));
+        TarArchiveEntry entry;
+        while ((entry = tarStream.getNextTarEntry()) != null) {
+            if (entry.getName().equals(filename)) {
+                // TODO why do we need the byte array in between???
+                IOUtils.copy(new ByteArrayInputStream(IOUtils.toByteArray(tarStream)), stream);
+            }
+        }
+    }
+}
diff --git a/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/ZipArchiveFileProvider.java b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/ZipArchiveFileProvider.java
new file mode 100644
index 0000000..8d0a3ad
--- /dev/null
+++ b/lib/src/main/java/eu/hinsch/spring/boot/actuator/logview/ZipArchiveFileProvider.java
@@ -0,0 +1,57 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.apache.commons.io.IOUtils;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.util.Date;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import static java.util.stream.Collectors.toList;
+
+/**
+* Created by lh on 28/02/15.
+*/
+public class ZipArchiveFileProvider extends AbstractFileProvider {
+
+    @Override
+    public boolean canHandle(Path folder) {
+        return isZip(folder);
+    }
+
+    @Override
+    public List<FileEntry> getFileEntries(Path folder) throws IOException {
+        ZipFile zipFile = new ZipFile(folder.toFile());
+        return zipFile.stream()
+                .map(ZipArchiveFileProvider::createFileEntry)
+                .collect(toList());
+    }
+
+    private static FileEntry createFileEntry(ZipEntry entry) {
+        FileEntry fileEntry = new FileEntry();
+        try {
+            fileEntry.setFilename(URLEncoder.encode(entry.getName(), "UTF-8"));
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException("encoding error", e);
+        }
+        fileEntry.setDisplayFilename(entry.getName());
+        fileEntry.setSize(entry.getSize());
+        fileEntry.setFileType(entry.isDirectory() ? FileType.DIRECTORY : FileType.FILE);
+        fileEntry.setModified(FileTime.fromMillis(entry.getTime()));
+        fileEntry.setModifiedPretty(prettyTime.format(new Date(entry.getTime())));
+        return fileEntry;
+    }
+
+    @Override
+    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
+        ZipFile zipFile = new ZipFile(folder.toFile());
+        ZipEntry entry = zipFile.getEntry(filename);
+        IOUtils.copy(zipFile.getInputStream(entry), stream);
+    }
+}
diff --git a/lib/src/main/resources/META-INF/spring-configuration-metadata.json b/lib/src/main/resources/META-INF/spring-configuration-metadata.json
new file mode 100644
index 0000000..3e3a02e
--- /dev/null
+++ b/lib/src/main/resources/META-INF/spring-configuration-metadata.json
@@ -0,0 +1,12 @@
+{"properties": [
+  {
+    "name": "endpoints.logview.path",
+    "type": "java.lang.String",
+    "description": "Logfile root folder - if logging.path is not used",
+    "sourceType": "eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig"
+  },
+  {
+    "name": "endpoints.logview.stylesheets",
+    "description": "Stylesheets urls to load (will replace default CDN links)"
+  }
+]}
\ No newline at end of file
diff --git a/lib/src/main/resources/META-INF/spring.factories b/lib/src/main/resources/META-INF/spring.factories
new file mode 100644
index 0000000..edbf884
--- /dev/null
+++ b/lib/src/main/resources/META-INF/spring.factories
@@ -0,0 +1,3 @@
+# Auto Configure
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig
\ No newline at end of file
diff --git a/lib/src/main/resources/templates/logview.ftl b/lib/src/main/resources/templates/logview.ftl
new file mode 100644
index 0000000..1546368
--- /dev/null
+++ b/lib/src/main/resources/templates/logview.ftl
@@ -0,0 +1,90 @@
+<html>
+    <head>
+        <title>Logfiles</title>
+        <#list stylesheets as stylesheet>
+        <link rel="stylesheet" href="${stylesheet}">
+        </#list>
+        <style>
+            .form-group {
+                margin-right: 10px;
+            }
+        </style>
+    </head>
+    <body>
+            <div class="container">
+                <div class="page-header">
+                    <h1>Log file viewer</h1>
+                </div>
+            <div class="panel panel-default">
+                <div class="panel-heading">
+                    <div class="form-inline">
+                        <form action="search" method="get">
+                            <div class="form-group">
+                                <label>Current location</label>
+                                <p class="form-control-static">${currentFolder}</p>
+                            </div>
+                            <#if base == "">
+                                <div class="form-group">
+                                    <label for="term">Search</label>
+                                    <input class="form-control" id="term" name="term" type="text"/>
+                                </div>
+                                <button class="btn btn-default">Search</button>
+                            </#if>
+                        </form>
+                    </div>
+                </div>
+                <table class="table table-striped table-hover">
+                    <thead>
+                        <tr>
+                            <th><a href="?sortBy=FILENAME<#if sortBy == 'FILENAME' && desc == false>&desc=true</#if>&base=${base}">Name</a></th>
+                            <th><a href="?sortBy=SIZE<#if sortBy == 'SIZE' && desc == false>&desc=true</#if>&base=${base}">Size</a></th>
+                            <th><a href="?sortBy=MODIFIED<#if sortBy == 'MODIFIED' && desc == false>&desc=true</#if>&base=${base}">Modified</a></th>
+                        </tr>
+                    </thead>
+                    <#if base != "">
+                    <tr>
+                        <td><i class="fa fa-folder-o"></i>&nbsp;<a href="?base=${parent}">..</a></td>
+                        <td></td>
+                        <td></td>
+                    </tr>
+                    </#if>
+
+                    <#list files as file>
+                        <tr>
+                            <td>
+                                <#if file.fileType == 'FILE'>
+                                    <i class="fa fa-file-o"></i>
+                                </#if>
+                                <#if file.fileType == 'DIRECTORY'>
+                                    <i class="fa fa-folder-o"></i>
+                                </#if>
+                                <#if file.fileType == 'ARCHIVE'>
+                                    <i class="fa fa-file-archive-o"></i>
+                                </#if>
+                                &nbsp;
+                                <#if file.fileType == 'FILE'>
+                                    <a href="view?filename=${file.filename}&base=${base}">${file.displayFilename}</a>&nbsp;
+                                    <#if !base?ends_with(".tar.gz") && !base?ends_with(".zip")>
+                                    <a href="view?filename=${file.filename}&base=${base}&tailLines=50" title="Download last 50 lines"><i class="fa fa-angle-double-down"></i></a>
+                                    </#if>
+                                </#if>
+                                <#if file.fileType == 'ARCHIVE'>
+                                    <a href="?base=${base}/${file.filename}">${file.displayFilename}</a>
+                                </#if>
+                                <#if file.fileType == 'DIRECTORY'>
+                                    <a href="?base=${base}/${file.filename}">${file.displayFilename}</a>
+                                </#if>
+                            </td>
+                            <td>
+                                <#if file.fileType != 'DIRECTORY'>
+                                    ${file.sizePretty}
+                                </#if>
+                            </td>
+                            <td title="${file.modified}">${file.modifiedPretty}</td>
+                        </tr>
+                    </#list>
+                </table>
+            </div>
+        </div>
+    </body>
+</html>
\ No newline at end of file
diff --git a/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfigTest.java b/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfigTest.java
new file mode 100644
index 0000000..4af0c69
--- /dev/null
+++ b/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointAutoconfigTest.java
@@ -0,0 +1,42 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.core.env.Environment;
+
+import static eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig.LOGGING_FILE;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+public class LogViewEndpointAutoconfigTest {
+
+    @Mock
+    private Environment environment;
+
+    @Mock
+    private LogViewEndpointAutoconfig.EndpointConfiguration configuration;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+    }
+
+    @Test
+    public void shouldCreateBeanForDefaultFile() {
+        when(environment.getRequiredProperty(LOGGING_FILE)).thenReturn("./custom.log");
+        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDefaultFile(environment, configuration), notNullValue());
+    }
+
+    @Test
+    public void shouldCreateBeanForDefaultPath() {
+        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDefaultPath(environment, configuration), notNullValue());
+    }
+
+    @Test
+    public void shouldCreateBeanForDeviatingPath() {
+        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDeviatingPath(environment, configuration), notNullValue());
+    }
+}
\ No newline at end of file
diff --git a/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointTest.java b/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointTest.java
new file mode 100644
index 0000000..fbbb1c9
--- /dev/null
+++ b/lib/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogViewEndpointTest.java
@@ -0,0 +1,432 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.apache.catalina.ssi.ByteArrayServletOutputStream;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.rules.TemporaryFolder;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.ui.ExtendedModelMap;
+import org.springframework.ui.Model;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Date;
+import java.util.List;
+import java.util.zip.GZIPOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@SuppressWarnings("unchecked")
+public class LogViewEndpointTest {
+
+    @Rule
+    public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+    @Rule
+    public ExpectedException expectedException = ExpectedException.none();
+
+    @Mock
+    private HttpServletResponse response;
+
+    private LogViewEndpoint logViewEndpoint;
+
+    private Model model;
+    private long now;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(),
+                new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets());
+        model = new ExtendedModelMap();
+        now = new Date().getTime();
+    }
+
+    @Test
+    public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception {
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        assertThat(model.containsAttribute("files"), is(true));
+        assertThat(getFileEntries(), hasSize(0));
+    }
+
+    @Test
+    public void shouldListSortedByFilename() throws Exception {
+        // given
+        createFile("B.log", "x", now);
+        createFile("A.log", "x", now);
+        createFile("C.log", "x", now);
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        assertThat(getFileNames(), contains("A.log", "B.log", "C.log"));
+    }
+
+    @Test
+    public void shouldListReverseSortedByFilename() throws Exception {
+        // given
+        createFile("B.log", "x", now);
+        createFile("A.log", "x", now);
+        createFile("C.log", "x", now);
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, true, null);
+
+        // then
+        assertThat(getFileNames(), contains("C.log", "B.log", "A.log"));
+    }
+
+    @Test
+    public void shouldListSortedBySize() throws Exception {
+        // given
+        createFile("A.log", "xx", now);
+        createFile("B.log", "x", now);
+        createFile("C.log", "xxx", now);
+
+        // when
+        logViewEndpoint.list(model, SortBy.SIZE, false, null);
+
+        // then
+        assertThat(getFileNames(), contains("B.log", "A.log", "C.log"));
+        assertThat(getFileSizes(), contains(1L, 2L, 3L));
+    }
+
+    @Test
+    public void shouldListSortedByDate() throws Exception {
+        // given
+        // TODO java 8 date api
+        createFile("A.log", "x", now);
+        createFile("B.log", "x", now - 10 * 60 * 1000);
+        createFile("C.log", "x", now - 5 * 60 * 1000);
+
+        // when
+        logViewEndpoint.list(model, SortBy.MODIFIED, false, null);
+
+        // then
+        assertThat(getFileNames(), contains("B.log", "C.log", "A.log"));
+        assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago"));
+    }
+
+    @Test
+    public void shouldSetFileTypeForFile() throws Exception {
+        // given
+        createFile("A.log", "x", now);
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE));
+    }
+
+    @Test
+    public void shouldSetFileTypeForArchive() throws Exception {
+        // given
+        createFile("A.log.tar.gz", "x", now);
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE));
+    }
+
+    @Test
+    public void shouldContainEmptyParentLinkInBaseFolder() throws Exception {
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        assertThat(model.asMap().get("parent"), is(""));
+    }
+
+    @Test
+    public void shouldContainEmptyParentLinkInSubfolder() throws Exception {
+        // given
+        temporaryFolder.newFolder("subfolder");
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder");
+
+        // then
+        assertThat(model.asMap().get("parent"), is(""));
+    }
+
+    @Test
+    public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception {
+        // given
+        temporaryFolder.newFolder("subfolder");
+        temporaryFolder.newFolder("subfolder", "nested");
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested");
+
+        // then
+        assertThat(model.asMap().get("parent"), is("/subfolder"));
+    }
+
+    @Test
+    public void shouldIncludeSubfolderEntry() throws Exception {
+        // given
+        temporaryFolder.newFolder("subfolder");
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, null);
+
+        // then
+        List<FileEntry> fileEntries = getFileEntries();
+        assertThat(fileEntries, hasSize(1));
+        FileEntry fileEntry = fileEntries.get(0);
+        assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY));
+        assertThat(fileEntry.getFilename(), is("subfolder"));
+    }
+
+    @Test
+    public void shouldListZipContent() throws Exception {
+        // given
+        createZipArchive("file.zip", "A.log", "content");
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip");
+
+        // then
+        List<FileEntry> fileEntries = getFileEntries();
+        assertThat(fileEntries, hasSize(1));
+        FileEntry fileEntry = fileEntries.get(0);
+        assertThat(fileEntry.getFilename(), is("A.log"));
+    }
+
+    @Test
+    public void shouldViewZipFileContent() throws Exception {
+        // given
+        createZipArchive("file.zip", "A.log", "content");
+        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();
+
+        // when
+        logViewEndpoint.view("A.log", "file.zip", null, response);
+
+        // then
+        assertThat(new String(outputStream.toByteArray()), is("content"));
+    }
+
+    private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception {
+        try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) {
+            ZipEntry zipEntry = new ZipEntry(contentFileName);
+            zos.putNextEntry(zipEntry);
+            IOUtils.write(content, zos);
+        }
+    }
+
+    @Test(expected = UnsupportedOperationException.class)
+    public void shouldThrowExceptionWhenCallingTailForZip() throws Exception {
+        // given
+        createZipArchive("file.zip", "A.log", "content");
+
+        // when
+        logViewEndpoint.view("A.log", "file.zip", 1, response);
+
+        // then -> exception
+    }
+
+    @Test
+    public void shouldListTarGzContent() throws Exception {
+        // given
+        createTarGzArchive("file.tar.gz", "A.log", "content");
+
+        // when
+        logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz");
+
+        // then
+        List<FileEntry> fileEntries = getFileEntries();
+        assertThat(fileEntries, hasSize(1));
+        FileEntry fileEntry = fileEntries.get(0);
+        assertThat(fileEntry.getFilename(), is("A.log"));
+    }
+
+    @Test
+    public void shouldViewTarGzFileContent() throws Exception {
+        // given
+        createTarGzArchive("file.tar.gz", "A.log", "content");
+        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();
+
+        // when
+        logViewEndpoint.view("A.log", "file.tar.gz", null, response);
+
+        // then
+        assertThat(new String(outputStream.toByteArray()), is("content"));
+    }
+
+    @Test(expected = UnsupportedOperationException.class)
+    public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception {
+        // given
+        createTarGzArchive("file.tar.gz", "A.log", "content");
+
+        // when
+        logViewEndpoint.view("A.log", "file.tar.gz", 1, response);
+
+        // then -> exception
+    }
+
+    private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception {
+
+        try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream(
+                new BufferedOutputStream(new FileOutputStream(
+                        new File(temporaryFolder.getRoot(), archiveFileName)))))) {
+            tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
+            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
+            TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName);
+            archiveEntry.setSize(content.length());
+            tos.putArchiveEntry(archiveEntry);
+            IOUtils.write(content, tos);
+            tos.closeArchiveEntry();
+        }
+    }
+
+    @Test
+    public void shouldRedirectWithoutTrainingSlash() throws IOException {
+        // when
+        logViewEndpoint.redirect(response);
+
+        // then
+        verify(response).sendRedirect("log/");
+    }
+
+    @Test
+    public void shouldEndpointBeSensitive() {
+        assertThat(logViewEndpoint.isSensitive(), is(true));
+    }
+
+    @Test
+    public void shouldReturnContextPath() {
+        assertThat(logViewEndpoint.getPath(), is("/log"));
+    }
+
+    @Test
+    public void shouldReturnNullEndpointType() {
+        assertThat(logViewEndpoint.getEndpointType(), is(nullValue()));
+    }
+
+    @Test
+    public void shouldNotAllowToListFileOutsideRoot() throws Exception {
+        // given
+        expectedException.expect(IllegalArgumentException.class);
+        expectedException.expectMessage(containsString("may not be located outside base path"));
+
+        // when
+        logViewEndpoint.view("../somefile", null, null, null);
+    }
+
+    @Test
+    public void shouldNotAllowToListWithBaseOutsideRoot() throws Exception {
+        // given
+        expectedException.expect(IllegalArgumentException.class);
+        expectedException.expectMessage(containsString("may not be located outside base path"));
+
+        // when
+        logViewEndpoint.view("somefile", "../otherdir", null, null);
+    }
+
+    @Test
+    public void shouldViewFile() throws Exception {
+        // given
+        createFile("file.log", "abc", now);
+        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();
+
+        // when
+        logViewEndpoint.view("file.log", null, null, response);
+
+        // then
+        assertThat(new String(outputStream.toByteArray()), is("abc"));
+    }
+
+    @Test
+    public void shouldTailViewOnlyLastLine() throws Exception {
+        // given
+        createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now);
+        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();
+
+        // when
+        logViewEndpoint.view("file.log", null, 1, response);
+
+        // then
+        assertThat(new String(outputStream.toByteArray()), not(containsString("line1")));
+        assertThat(new String(outputStream.toByteArray()), containsString("line2"));
+    }
+
+    @Test
+    public void shouldSearchInFiles() throws Exception {
+        // given
+        String sep = System.lineSeparator();
+        createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1);
+        createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now);
+        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();
+
+        // when
+        logViewEndpoint.search("line2", response);
+
+        // then
+        String output = new String(outputStream.toByteArray());
+        assertThat(output, containsString("[A.log] A-line2"));
+        assertThat(output, containsString("[B.log] B-line2"));
+        assertThat(output, not(containsString("line1")));
+        assertThat(output, not(containsString("line3")));
+    }
+
+    private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception {
+        ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream();
+        when(response.getOutputStream()).thenReturn(outputStream);
+        return outputStream;
+    }
+
+    private List<String> getFileNames() {
+        return getFileEntries()
+                .stream()
+                .map(FileEntry::getFilename)
+                .collect(toList());
+    }
+
+    private List<Long> getFileSizes() {
+        return getFileEntries()
+                .stream()
+                .map(FileEntry::getSize)
+                .collect(toList());
+    }
+
+    private List<String> getFilePrettyTimes() {
+        return getFileEntries()
+                .stream()
+                .map(FileEntry::getModifiedPretty)
+                .collect(toList());
+    }
+
+    private List<FileEntry> getFileEntries() {
+        return (List<FileEntry>) model.asMap().get("files");
+    }
+
+    private void createFile(String filename, String content, long modified) throws Exception {
+        File file = new File(temporaryFolder.getRoot(), filename);
+        FileUtils.write(file, content);
+        assertThat(file.setLastModified(modified), is(true));
+    }
+
+}
\ No newline at end of file
diff --git a/settings.gradle b/settings.gradle
new file mode 100644
index 0000000..c7e4ec4
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1,5 @@
+include 'lib'
+
+rootProject.children.each {
+    it.buildFileName = it.name + '.gradle'
+}
\ No newline at end of file
diff --git a/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplication.java b/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplication.java
new file mode 100644
index 0000000..e29904f
--- /dev/null
+++ b/src/main/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplication.java
@@ -0,0 +1,12 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class LogviewApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(LogviewApplication.class, args);
+    }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
new file mode 100644
index 0000000..ff33af7
--- /dev/null
+++ b/src/main/resources/application.yml
@@ -0,0 +1,12 @@
+management:
+  context-path: /manage
+logging:
+  path: /tmp/log
+#  file: /tmp/log/custom.log
+
+#endpoints:
+#  logview:
+#    stylesheets:
+#      - http://foo.bar
+#      - http://bar.foo
+#    path: /tmp/log
diff --git a/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplicationTests.java b/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplicationTests.java
new file mode 100644
index 0000000..4adce2c
--- /dev/null
+++ b/src/test/java/eu/hinsch/spring/boot/actuator/logview/LogviewApplicationTests.java
@@ -0,0 +1,18 @@
+package eu.hinsch.spring.boot.actuator.logview;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.web.WebAppConfiguration;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@SpringApplicationConfiguration(classes = LogviewApplication.class)
+@WebAppConfiguration
+public class LogviewApplicationTests {
+
+	@Test
+	public void contextLoads() {
+	}
+
+}

Fixed code: .gradle
.idea
*.iml
build/
out/
language: java
jdk:
  - openjdk8

after_success:
  - ./gradlew lib:jacocoTestReport lib:coveralls
# spring-boot-actuator-logview changelog

## 0.2.12
- support logfile configuration via logging.file property (thanks @oyvindhorneland)

## 0.2.11
- Set missing content type in search result

## 0.2.10
- Set content type in log response (fixes [#21](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/21))
- Prettify file size display (fixes [#23](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/23))

## 0.2.9
- Add configuration option to override stylesheet urls (fixes [#20](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/20))

## 0.2.8
- Remove tail option for files inside archives in UI (lead to 500 error before) (fixes [#17](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/17))

## 0.2.7
- Correctly encode file/dir names in urls (fixes - [#19](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/19))

## 0.2.6
- Fixed display issue with illegal whitespace
- Fix cdn url

## 0.2.5
- allow downloading only the last 50 lines of each file (closes [#13](https://github.com/lukashinsch/spring-boot-actuator-logview/pull/13))

## 0.2.4
- show file content when calling endpoint url without trailing slash (fixes [#11](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/11))
- allow to specify logging path via "endpoints.logview.path" property (fixes [#3](https://github.com/lukashinsch/spring-boot-actuator-logview/issues/3)

## 0.2.3
- don't require trailing slash in endpoint url ("/log" instead of "/log/")

## 0.2.2
- allow viewing logfiles in subfolders inside archives

## 0.2.1
- switch to use dedicated freemarker config to allow loading template from jar
- use spring boot autoconfig

## 0.2
- basic support for searching logfiles (no archives, no subfolders)

## 0.1
- initial release
The MIT License (MIT)

Copyright (c) 2015 Lukas Hinsch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

[![Coverage Status](https://coveralls.io/repos/lukashinsch/spring-boot-actuator-logview/badge.svg?branch=master)](https://coveralls.io/r/lukashinsch/spring-boot-actuator-logview?branch=master)
[![Build Status](https://travis-ci.org/lukashinsch/spring-boot-actuator-logview.svg?branch=master)](https://travis-ci.org/lukashinsch/spring-boot-actuator-logview)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/eu.hinsch/spring-boot-actuator-logview/badge.svg)](https://maven-badges.herokuapp.com/maven-central/eu.hinsch/spring-boot-actuator-logview/)

# spring-boot-actuator-logview
Simple logfile viewer as spring boot actuator endpoint

##Features
* allow quick access to spring-boot web application logfiles
* uses actuator framework to provide management endpoint
* list log folder content
* view individual logfiles
* view content of log archives (*.zip, *.tar.gz)
* browse subdirectories
* search in (non-compressed) files in logging root folder
* tail without reading entire file

![screenshot](img/screenshot.png)

##Howto use
* include library on classpath of spring-boot app
* configure `logging.path`, `logging.file` or `endpoints.logview.path` in spring environment
    * `logging.file` specifies a custom log file. Logviewer will use it's parent directory.
    * `logging.path` specifies a log directory and log filename `spring.log`.
    * `endpoints.logview.path` specifies a directory containing log files in case you use other custom log configurations.
* endpoint will be available under <management-base>/log
* to replace default stylesheet links, set property `endpoints.logview.stylesheets` in yml to list of urls

###Gradle
```groovy
compile 'eu.hinsch:spring-boot-actuator-logview:0.2.12'
```

###Maven
```xml
<dependency>
    <groupId>eu.hinsch</groupId>
    <artifactId>spring-boot-actuator-logview</artifactId>
    <version>0.2.12</version>
</dependency>
```


Note
* lib depends on spring-boot-starter-freemarker, so it may currently not work with another templating engine for the main app
buildscript {
    ext {
        springBootVersion = '1.2.1.RELEASE'
        springLoadedVersion = '1.2.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.springframework:springloaded:${springLoadedVersion}")
        classpath("org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'


jar {
    baseName = 'spring-boot-actuator-logview-sample'
    version = '0.0.1-SNAPSHOT'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile project("lib")

    testCompile("org.springframework.boot:spring-boot-starter-test")
}


idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}
#Fri Mar 13 22:18:34 CET 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-bin.zip
#!/usr/bin/env bash

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn ( ) {
    echo "$*"
}

die ( ) {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
    JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windowz variants

if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*
goto execute

:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'jacoco'
apply plugin: 'com.github.kt3k.coveralls'

ext {
    springBootVersion = '1.2.1.RELEASE'
    libVersion = '0.2.12'
}

jar {
    baseName = 'spring-boot-actuator-logview'
    version = libVersion
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
    compile("org.springframework.boot:spring-boot-starter-freemarker:${springBootVersion}")
    compile("org.springframework.boot:spring-boot-starter-actuator:${springBootVersion}")
    compile("org.ocpsoft.prettytime:prettytime:3.2.7.Final")
    compile("commons-io:commons-io:2.4")
    compile("org.apache.commons:commons-compress:1.9")

    testCompile("org.springframework.boot:spring-boot-starter-test:${springBootVersion}")
}


idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}

jacocoTestReport {
    reports {
        xml.enabled = true // coveralls plugin depends on xml format report
        html.enabled = true
    }
}

test {
    testLogging {
        events "failed"
        exceptionFormat "full" // show assertion errors in build
    }
}

// sign and publish to MC is done only locally so far

if (System.getenv('CI') != 'true') {

    apply plugin: 'signing'
    apply plugin: 'maven'

    group = 'eu.hinsch'
    version = libVersion

    task javadocJar(type: Jar, dependsOn: javadoc) {
        classifier = 'javadoc'
        from tasks.javadoc.destinationDir
    }

    task sourcesJar(type: Jar) {
        from sourceSets.main.allSource
        classifier = 'sources'
    }

    artifacts {
        archives jar
        archives javadocJar
        archives sourcesJar
    }

    signing {
        sign configurations.archives
    }

    uploadArchives {
        repositories {
            mavenDeployer {
                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

                repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
                    authentication(userName: sonatypeUsername, password: sonatypePassword)
                }

                pom.project {
                    name 'spring-boot-actuator-logview'
                    packaging 'jar'
                    description 'simple logfile viewer as spring boot actuator endpoint'
                    url 'https://github.com/lukashinsch/spring-boot-actuator-logview/'

                    scm {
                        url 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
                        connection 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
                        developerConnection 'scm:git@github.com:lukashinsch/spring-boot-actuator-logview.git'
                    }

                    licenses {
                        license {
                            name 'MIT License'
                            url 'http://www.opensource.org/licenses/mit-license.php'
                            distribution 'repo'
                        }
                    }

                    developers {
                        developer {
                            id 'lukashinsch'
                            name 'Lukas Hinsch'
                        }
                    }
                }
            }
        }
    }
}
package eu.hinsch.spring.boot.actuator.logview;

import org.ocpsoft.prettytime.PrettyTime;

import java.nio.file.Path;

/**
* Created by lh on 28/02/15.
*/
public abstract class AbstractFileProvider implements FileProvider {
    protected static final PrettyTime prettyTime = new PrettyTime();

    protected boolean isArchive(Path path) {
        return isZip(path) || isTarGz(path);
    }

    protected boolean isTarGz(Path path) {
        return !path.toFile().isDirectory() && path.getFileName().toString().endsWith(".tar.gz");
    }

    protected boolean isZip(Path path) {
        return !path.toFile().isDirectory() && path.getFileName().toString().endsWith(".zip");
    }
}
package eu.hinsch.spring.boot.actuator.logview;

import org.apache.commons.io.FileUtils;

import java.nio.file.attribute.FileTime;

/**
* Created by lh on 26/02/15.
*/
public class FileEntry {
    private String filename;
    private String displayFilename;
    private FileTime modified;
    private String modifiedPretty;
    private long size;
    private FileType fileType;

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public FileTime getModified() {
        return modified;
    }

    public void setModified(FileTime modified) {
        this.modified = modified;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public String getModifiedPretty() {
        return modifiedPretty;
    }

    public void setModifiedPretty(String modifiedPretty) {
        this.modifiedPretty = modifiedPretty;
    }

    public FileType getFileType() {
        return fileType;
    }

    public void setFileType(FileType fileType) {
        this.fileType = fileType;
    }

    public void setDisplayFilename(String displayFilename) {
        this.displayFilename = displayFilename;
    }

    public String getDisplayFilename() {
        return displayFilename;
    }

    public String getSizePretty() {
        return FileUtils.byteCountToDisplaySize(size);
    }

}
package eu.hinsch.spring.boot.actuator.logview;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.List;

/**
* Created by lh on 28/02/15.
*/
public interface FileProvider {

    boolean canHandle(Path folder);

    List<FileEntry> getFileEntries(Path folder) throws IOException;

    void streamContent(Path folder, String filename, OutputStream stream) throws IOException;

    default void tailContent(Path folder, String filename, OutputStream stream, int lines) throws IOException {
        throw new UnsupportedOperationException("by default no tailing possible");
    }
}
package eu.hinsch.spring.boot.actuator.logview;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
* Created by lh on 28/02/15.
*/
public class FileSystemFileProvider extends AbstractFileProvider {

    @Override
    public boolean canHandle(Path folder) {
        return folder.toFile().isDirectory();
    }

    @Override
    public List<FileEntry> getFileEntries(Path loggingPath) throws IOException {
        final List<FileEntry> files = new ArrayList<>();
        Files.newDirectoryStream(loggingPath)
                .forEach((path) -> files.add(createFileEntry(path)));
        return files;
    }

    private FileEntry createFileEntry(Path path)  {
        final FileEntry fileEntry = new FileEntry();
        try {
            fileEntry.setFilename(URLEncoder.encode(path.getFileName().toString(), "UTF-8"));
            fileEntry.setDisplayFilename(path.getFileName().toString());
            fileEntry.setModified(Files.getLastModifiedTime(path));
            fileEntry.setSize(Files.size(path));
        } catch (IOException e) {
            throw new RuntimeException("unable to retrieve file attribute", e);
        }
        fileEntry.setModifiedPretty(prettyTime.format(new Date(fileEntry.getModified().toMillis())));
        fileEntry.setFileType(getFileType(path));

        return fileEntry;
    }

    private FileType getFileType(Path path) {
        FileType fileType;
        if (path.toFile().isDirectory()) {
            fileType = FileType.DIRECTORY;
        }
        else if (isArchive(path)) {
            fileType = FileType.ARCHIVE;
        }
        else {
            fileType = FileType.FILE;
        }
        return fileType;
    }

    @Override
    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
        IOUtils.copy(new FileInputStream(getFile(folder, filename)), stream);
    }

    private File getFile(Path folder, String filename) {
        return Paths.get(folder.toString(), filename).toFile();
    }

    @Override
    public void tailContent(Path folder, String filename, OutputStream stream, int lines) throws IOException {
        try (ReversedLinesFileReader reader = new ReversedLinesFileReader(getFile(folder, filename))) {
            int i = 0;
            String line;
            List<String> content = new ArrayList<>();
            while ((line = reader.readLine()) != null && i++ < lines) {
                content.add(line);
            }
            Collections.reverse(content);
            IOUtils.writeLines(content, System.lineSeparator(), stream);
        }
    }
}
package eu.hinsch.spring.boot.actuator.logview;

/**
* Created by lh on 26/02/15.
*/
public enum FileType {
    FILE, DIRECTORY, ARCHIVE
}
package eu.hinsch.spring.boot.actuator.logview;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;

/**
 * Created by lh on 23/02/15.
 */
public class LogViewEndpoint implements MvcEndpoint{

    private final List<FileProvider> fileProviders;
    private final Configuration freemarkerConfig;
    private final String loggingPath;
    private final List<String> stylesheets;

    public LogViewEndpoint(String loggingPath, List<String> stylesheets) {
        this.loggingPath = loggingPath;
        this.stylesheets = stylesheets;
        fileProviders = asList(new FileSystemFileProvider(),
                new ZipArchiveFileProvider(),
                new TarGzArchiveFileProvider());
        freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates");
    }

    @RequestMapping
    public void redirect(HttpServletResponse response) throws IOException {
        response.sendRedirect("log/");
    }

    @RequestMapping("/")
    @ResponseBody
    public String list(Model model, // TODO model should no longer be injected
                       @RequestParam(required = false, defaultValue = "FILENAME") SortBy sortBy,
                       @RequestParam(required = false, defaultValue = "false") boolean desc,
                       @RequestParam(required = false) String base) throws IOException, TemplateException {
        Path currentFolder = loggingPath(base);
        securityCheck(currentFolder, null);


        List<FileEntry> files = getFileProvider(currentFolder).getFileEntries(currentFolder);
        List<FileEntry> sortedFiles = sortFiles(files, sortBy, desc);

        model.addAttribute("sortBy", sortBy);
        model.addAttribute("desc", desc);
        model.addAttribute("files", sortedFiles);
        model.addAttribute("currentFolder", currentFolder.toAbsolutePath().toString());
        model.addAttribute("base", base != null ? URLEncoder.encode(base, "UTF-8") : "");
        model.addAttribute("parent", getParent(currentFolder));
        model.addAttribute("stylesheets", stylesheets);

        return FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfig.getTemplate("logview.ftl"), model);
    }

    private FileProvider getFileProvider(Path folder) {
        return fileProviders.stream()
                .filter(provider -> provider.canHandle(folder))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("no file provider found for " + folder.toString()));
    }

    private String getParent(Path loggingPath) {
        Path basePath = loggingPath(null);
        String parent = "";
        if (!basePath.toString().equals(loggingPath.toString())) {
            parent = loggingPath.getParent().toString();
            if (parent.startsWith(basePath.toString())) {
                parent = parent.substring(basePath.toString().length());
            }
        }
        return parent;
    }

    private Path loggingPath(String base) {
        return base != null ? Paths.get(loggingPath, base) : Paths.get(loggingPath);
    }

    private List<FileEntry> sortFiles(List<FileEntry> files, SortBy sortBy, boolean desc) {
        Comparator<FileEntry> comparator = null;
        switch (sortBy) {
            case FILENAME:
                comparator = (a, b) -> a.getFilename().compareTo(b.getFilename());
                break;
            case SIZE:
                comparator = (a, b) -> Long.compare(a.getSize(), b.getSize());
                break;
            case MODIFIED:
                comparator = (a, b) -> Long.compare(a.getModified().toMillis(), b.getModified().toMillis());
                break;
        }
        List<FileEntry> sortedFiles = files.stream().sorted(comparator).collect(toList());

        if (desc) {
            Collections.reverse(sortedFiles);
        }
        return sortedFiles;
    }

    @RequestMapping("/view")
    public void view(@RequestParam String filename,
                     @RequestParam(required = false) String base,
                     @RequestParam(required = false) Integer tailLines,
                     HttpServletResponse response) throws IOException {

        Path path = loggingPath(base);
        securityCheck(path, filename);
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        FileProvider fileProvider = getFileProvider(path);
        if (tailLines != null) {
            fileProvider.tailContent(path, filename, response.getOutputStream(), tailLines);
        }
        else {
            fileProvider.streamContent(path, filename, response.getOutputStream());
        }
    }

    @RequestMapping("/search")
    public void search(@RequestParam String term, HttpServletResponse response) throws IOException {
        Path folder = loggingPath(null);
        List<FileEntry> files = getFileProvider(folder).getFileEntries(folder);
        List<FileEntry> sortedFiles = sortFiles(files, SortBy.MODIFIED, false);

        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        ServletOutputStream outputStream = response.getOutputStream();

        sortedFiles.stream()
                .filter(file -> file.getFileType().equals(FileType.FILE))
                .forEach(file -> searchAndStreamFile(file, term, outputStream));
    }

    private void searchAndStreamFile(FileEntry fileEntry, String term, OutputStream outputStream) {
        Path folder = loggingPath(null);
        try {
            List<String> lines = IOUtils.readLines(new FileInputStream(new File(folder.toFile().toString(), fileEntry.getFilename())))
                    .stream()
                    .filter(line -> line.contains(term))
                    .map(line -> "[" + fileEntry.getFilename() + "] " + line)
                    .collect(toList());
            for (String line : lines) {
                outputStream.write(line.getBytes());
                outputStream.write(System.lineSeparator().getBytes());
            }
        } catch (IOException e) {
            throw new RuntimeException("error reading file", e);
        }
    }

    private void securityCheck(Path base, String filename) {
        try {
            String canonicalLoggingPath = (filename != null ? new File(base.toFile().toString(), filename) : new File(base.toFile().toString())).getCanonicalPath();
            String baseCanonicalPath = new File(loggingPath).getCanonicalPath();
            String errorMessage = "File " + base.toString() + "/" + filename + " may not be located outside base path " + loggingPath;
            Assert.isTrue(canonicalLoggingPath.startsWith(baseCanonicalPath), errorMessage);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public String getPath() {
        return "/log";
    }

    @Override
    public boolean isSensitive() {
        return true;
    }


    @Override
    public Class<? extends Endpoint> getEndpointType() {
        return null;
    }

}
package eu.hinsch.spring.boot.actuator.logview;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

import static java.util.Arrays.asList;

@Configuration
public class LogViewEndpointAutoconfig {

    public static final String LOGGING_FILE = "logging.file";
    public static final String LOGGING_PATH = "logging.path";
    public static final String ENDPOINTS_LOGVIEW_PATH = "endpoints.logview.path";

    @ConditionalOnProperty(LOGGING_FILE)
    @ConditionalOnMissingBean(LogViewEndpoint.class)
    @Bean
    public LogViewEndpoint logViewEndpointWithDefaultFile(Environment environment, EndpointConfiguration configuration) {
        String logDirectory = new File(environment.getRequiredProperty(LOGGING_FILE)).getParentFile().getAbsolutePath();
        return new LogViewEndpoint(logDirectory, configuration.getStylesheets());
    }

    @ConditionalOnProperty(LOGGING_PATH)
    @ConditionalOnMissingBean(LogViewEndpoint.class)
    @Bean
    public LogViewEndpoint logViewEndpointWithDefaultPath(Environment environment, EndpointConfiguration configuration) {
        return new LogViewEndpoint(environment.getRequiredProperty(LOGGING_PATH), configuration.getStylesheets());
    }

    @ConditionalOnProperty(ENDPOINTS_LOGVIEW_PATH)
    @ConditionalOnMissingBean(LogViewEndpoint.class)
    @Bean
    public LogViewEndpoint logViewEndpointWithDeviatingPath(Environment environment, EndpointConfiguration configuration) {
        return new LogViewEndpoint(configuration.getPath(), configuration.getStylesheets());
    }

    @Component
    @ConfigurationProperties(prefix = "endpoints.logview")
    static class EndpointConfiguration {
        private List<String> stylesheets = asList("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css",
                "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css");
        private String path;

        public List<String> getStylesheets() {
            return stylesheets;
        }

        public void setStylesheets(List<String> stylesheets) {
            this.stylesheets = stylesheets;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }
    }
}
package eu.hinsch.spring.boot.actuator.logview;

/**
* Created by lh on 26/02/15.
*/
public enum SortBy {
    FILENAME, SIZE, MODIFIED
}
package eu.hinsch.spring.boot.actuator.logview;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
* Created by lh on 28/02/15.
*/
public class TarGzArchiveFileProvider extends AbstractFileProvider {

    @Override
    public boolean canHandle(Path folder) {
        return isTarGz(folder);
    }

    @Override
    public List<FileEntry> getFileEntries(Path folder) throws IOException {
        TarArchiveInputStream inputStream = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(folder.toFile())));
        TarArchiveEntry entry;
        List<FileEntry> files = new ArrayList<>();
        while ((entry = inputStream.getNextTarEntry()) != null) {
            files.add(createFileEntry(entry));
        }
        return files;
    }

    private static FileEntry createFileEntry(TarArchiveEntry entry) {
        FileEntry fileEntry = new FileEntry();
        try {
            fileEntry.setFilename(URLEncoder.encode(entry.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("encoding error", e);
        }
        fileEntry.setDisplayFilename(entry.getName());
        fileEntry.setSize(entry.getSize());
        fileEntry.setFileType(entry.isDirectory() ? FileType.DIRECTORY : FileType.FILE);
        fileEntry.setModified(FileTime.fromMillis(entry.getLastModifiedDate().getTime()));
        fileEntry.setModifiedPretty(prettyTime.format(new Date(entry.getLastModifiedDate().getTime())));
        return fileEntry;
    }

    @Override
    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(folder.toFile())));
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            if (entry.getName().equals(filename)) {
                // TODO why do we need the byte array in between???
                IOUtils.copy(new ByteArrayInputStream(IOUtils.toByteArray(tarStream)), stream);
            }
        }
    }
}
package eu.hinsch.spring.boot.actuator.logview;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static java.util.stream.Collectors.toList;

/**
* Created by lh on 28/02/15.
*/
public class ZipArchiveFileProvider extends AbstractFileProvider {

    @Override
    public boolean canHandle(Path folder) {
        return isZip(folder);
    }

    @Override
    public List<FileEntry> getFileEntries(Path folder) throws IOException {
        ZipFile zipFile = new ZipFile(folder.toFile());
        return zipFile.stream()
                .map(ZipArchiveFileProvider::createFileEntry)
                .collect(toList());
    }

    private static FileEntry createFileEntry(ZipEntry entry) {
        FileEntry fileEntry = new FileEntry();
        try {
            fileEntry.setFilename(URLEncoder.encode(entry.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("encoding error", e);
        }
        fileEntry.setDisplayFilename(entry.getName());
        fileEntry.setSize(entry.getSize());
        fileEntry.setFileType(entry.isDirectory() ? FileType.DIRECTORY : FileType.FILE);
        fileEntry.setModified(FileTime.fromMillis(entry.getTime()));
        fileEntry.setModifiedPretty(prettyTime.format(new Date(entry.getTime())));
        return fileEntry;
    }

    @Override
    public void streamContent(Path folder, String filename, OutputStream stream) throws IOException {
        ZipFile zipFile = new ZipFile(folder.toFile());
        ZipEntry entry = zipFile.getEntry(filename);
        IOUtils.copy(zipFile.getInputStream(entry), stream);
    }
}
{"properties": [
  {
    "name": "endpoints.logview.path",
    "type": "java.lang.String",
    "description": "Logfile root folder - if logging.path is not used",
    "sourceType": "eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig"
  },
  {
    "name": "endpoints.logview.stylesheets",
    "description": "Stylesheets urls to load (will replace default CDN links)"
  }
]}
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig
<html>
    <head>
        <title>Logfiles</title>
        <#list stylesheets as stylesheet>
        <link rel="stylesheet" href="${stylesheet}">
        </#list>
        <style>
            .form-group {
                margin-right: 10px;
            }
        </style>
    </head>
    <body>
            <div class="container">
                <div class="page-header">
                    <h1>Log file viewer</h1>
                </div>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="form-inline">
                        <form action="search" method="get">
                            <div class="form-group">
                                <label>Current location</label>
                                <p class="form-control-static">${currentFolder}</p>
                            </div>
                            <#if base == "">
                                <div class="form-group">
                                    <label for="term">Search</label>
                                    <input class="form-control" id="term" name="term" type="text"/>
                                </div>
                                <button class="btn btn-default">Search</button>
                            </#if>
                        </form>
                    </div>
                </div>
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th><a href="?sortBy=FILENAME<#if sortBy == 'FILENAME' && desc == false>&desc=true</#if>&base=${base}">Name</a></th>
                            <th><a href="?sortBy=SIZE<#if sortBy == 'SIZE' && desc == false>&desc=true</#if>&base=${base}">Size</a></th>
                            <th><a href="?sortBy=MODIFIED<#if sortBy == 'MODIFIED' && desc == false>&desc=true</#if>&base=${base}">Modified</a></th>
                        </tr>
                    </thead>
                    <#if base != "">
                    <tr>
                        <td><i class="fa fa-folder-o"></i>&nbsp;<a href="?base=${parent}">..</a></td>
                        <td></td>
                        <td></td>
                    </tr>
                    </#if>

                    <#list files as file>
                        <tr>
                            <td>
                                <#if file.fileType == 'FILE'>
                                    <i class="fa fa-file-o"></i>
                                </#if>
                                <#if file.fileType == 'DIRECTORY'>
                                    <i class="fa fa-folder-o"></i>
                                </#if>
                                <#if file.fileType == 'ARCHIVE'>
                                    <i class="fa fa-file-archive-o"></i>
                                </#if>
                                &nbsp;
                                <#if file.fileType == 'FILE'>
                                    <a href="view?filename=${file.filename}&base=${base}">${file.displayFilename}</a>&nbsp;
                                    <#if !base?ends_with(".tar.gz") && !base?ends_with(".zip")>
                                    <a href="view?filename=${file.filename}&base=${base}&tailLines=50" title="Download last 50 lines"><i class="fa fa-angle-double-down"></i></a>
                                    </#if>
                                </#if>
                                <#if file.fileType == 'ARCHIVE'>
                                    <a href="?base=${base}/${file.filename}">${file.displayFilename}</a>
                                </#if>
                                <#if file.fileType == 'DIRECTORY'>
                                    <a href="?base=${base}/${file.filename}">${file.displayFilename}</a>
                                </#if>
                            </td>
                            <td>
                                <#if file.fileType != 'DIRECTORY'>
                                    ${file.sizePretty}
                                </#if>
                            </td>
                            <td title="${file.modified}">${file.modifiedPretty}</td>
                        </tr>
                    </#list>
                </table>
            </div>
        </div>
    </body>
</html>
package eu.hinsch.spring.boot.actuator.logview;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.core.env.Environment;

import static eu.hinsch.spring.boot.actuator.logview.LogViewEndpointAutoconfig.LOGGING_FILE;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

public class LogViewEndpointAutoconfigTest {

    @Mock
    private Environment environment;

    @Mock
    private LogViewEndpointAutoconfig.EndpointConfiguration configuration;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void shouldCreateBeanForDefaultFile() {
        when(environment.getRequiredProperty(LOGGING_FILE)).thenReturn("./custom.log");
        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDefaultFile(environment, configuration), notNullValue());
    }

    @Test
    public void shouldCreateBeanForDefaultPath() {
        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDefaultPath(environment, configuration), notNullValue());
    }

    @Test
    public void shouldCreateBeanForDeviatingPath() {
        assertThat(new LogViewEndpointAutoconfig().logViewEndpointWithDeviatingPath(environment, configuration), notNullValue());
    }
}
package eu.hinsch.spring.boot.actuator.logview;

import org.apache.catalina.ssi.ByteArrayServletOutputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@SuppressWarnings("unchecked")
public class LogViewEndpointTest {

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Mock
    private HttpServletResponse response;

    private LogViewEndpoint logViewEndpoint;

    private Model model;
    private long now;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        logViewEndpoint = new LogViewEndpoint(temporaryFolder.getRoot().getAbsolutePath(),
                new LogViewEndpointAutoconfig.EndpointConfiguration().getStylesheets());
        model = new ExtendedModelMap();
        now = new Date().getTime();
    }

    @Test
    public void shouldReturnEmptyFileListForEmptyDirectory() throws Exception {
        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        assertThat(model.containsAttribute("files"), is(true));
        assertThat(getFileEntries(), hasSize(0));
    }

    @Test
    public void shouldListSortedByFilename() throws Exception {
        // given
        createFile("B.log", "x", now);
        createFile("A.log", "x", now);
        createFile("C.log", "x", now);

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        assertThat(getFileNames(), contains("A.log", "B.log", "C.log"));
    }

    @Test
    public void shouldListReverseSortedByFilename() throws Exception {
        // given
        createFile("B.log", "x", now);
        createFile("A.log", "x", now);
        createFile("C.log", "x", now);

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, true, null);

        // then
        assertThat(getFileNames(), contains("C.log", "B.log", "A.log"));
    }

    @Test
    public void shouldListSortedBySize() throws Exception {
        // given
        createFile("A.log", "xx", now);
        createFile("B.log", "x", now);
        createFile("C.log", "xxx", now);

        // when
        logViewEndpoint.list(model, SortBy.SIZE, false, null);

        // then
        assertThat(getFileNames(), contains("B.log", "A.log", "C.log"));
        assertThat(getFileSizes(), contains(1L, 2L, 3L));
    }

    @Test
    public void shouldListSortedByDate() throws Exception {
        // given
        // TODO java 8 date api
        createFile("A.log", "x", now);
        createFile("B.log", "x", now - 10 * 60 * 1000);
        createFile("C.log", "x", now - 5 * 60 * 1000);

        // when
        logViewEndpoint.list(model, SortBy.MODIFIED, false, null);

        // then
        assertThat(getFileNames(), contains("B.log", "C.log", "A.log"));
        assertThat(getFilePrettyTimes(), contains("10 minutes ago", "5 minutes ago", "moments ago"));
    }

    @Test
    public void shouldSetFileTypeForFile() throws Exception {
        // given
        createFile("A.log", "x", now);

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        assertThat(getFileEntries().get(0).getFileType(), is(FileType.FILE));
    }

    @Test
    public void shouldSetFileTypeForArchive() throws Exception {
        // given
        createFile("A.log.tar.gz", "x", now);

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        assertThat(getFileEntries().get(0).getFileType(), is(FileType.ARCHIVE));
    }

    @Test
    public void shouldContainEmptyParentLinkInBaseFolder() throws Exception {
        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        assertThat(model.asMap().get("parent"), is(""));
    }

    @Test
    public void shouldContainEmptyParentLinkInSubfolder() throws Exception {
        // given
        temporaryFolder.newFolder("subfolder");

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder");

        // then
        assertThat(model.asMap().get("parent"), is(""));
    }

    @Test
    public void shouldContainEmptyParentLinkInNestedSubfolder() throws Exception {
        // given
        temporaryFolder.newFolder("subfolder");
        temporaryFolder.newFolder("subfolder", "nested");

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, "subfolder/nested");

        // then
        assertThat(model.asMap().get("parent"), is("/subfolder"));
    }

    @Test
    public void shouldIncludeSubfolderEntry() throws Exception {
        // given
        temporaryFolder.newFolder("subfolder");

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, null);

        // then
        List<FileEntry> fileEntries = getFileEntries();
        assertThat(fileEntries, hasSize(1));
        FileEntry fileEntry = fileEntries.get(0);
        assertThat(fileEntry.getFileType(), is(FileType.DIRECTORY));
        assertThat(fileEntry.getFilename(), is("subfolder"));
    }

    @Test
    public void shouldListZipContent() throws Exception {
        // given
        createZipArchive("file.zip", "A.log", "content");

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, "file.zip");

        // then
        List<FileEntry> fileEntries = getFileEntries();
        assertThat(fileEntries, hasSize(1));
        FileEntry fileEntry = fileEntries.get(0);
        assertThat(fileEntry.getFilename(), is("A.log"));
    }

    @Test
    public void shouldViewZipFileContent() throws Exception {
        // given
        createZipArchive("file.zip", "A.log", "content");
        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();

        // when
        logViewEndpoint.view("A.log", "file.zip", null, response);

        // then
        assertThat(new String(outputStream.toByteArray()), is("content"));
    }

    private void createZipArchive(String archiveFileName, String contentFileName, String content) throws Exception {
        try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(temporaryFolder.getRoot(), archiveFileName)))) {
            ZipEntry zipEntry = new ZipEntry(contentFileName);
            zos.putNextEntry(zipEntry);
            IOUtils.write(content, zos);
        }
    }

    @Test(expected = UnsupportedOperationException.class)
    public void shouldThrowExceptionWhenCallingTailForZip() throws Exception {
        // given
        createZipArchive("file.zip", "A.log", "content");

        // when
        logViewEndpoint.view("A.log", "file.zip", 1, response);

        // then -> exception
    }

    @Test
    public void shouldListTarGzContent() throws Exception {
        // given
        createTarGzArchive("file.tar.gz", "A.log", "content");

        // when
        logViewEndpoint.list(model, SortBy.FILENAME, false, "file.tar.gz");

        // then
        List<FileEntry> fileEntries = getFileEntries();
        assertThat(fileEntries, hasSize(1));
        FileEntry fileEntry = fileEntries.get(0);
        assertThat(fileEntry.getFilename(), is("A.log"));
    }

    @Test
    public void shouldViewTarGzFileContent() throws Exception {
        // given
        createTarGzArchive("file.tar.gz", "A.log", "content");
        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();

        // when
        logViewEndpoint.view("A.log", "file.tar.gz", null, response);

        // then
        assertThat(new String(outputStream.toByteArray()), is("content"));
    }

    @Test(expected = UnsupportedOperationException.class)
    public void shouldThrowExceptionWhenCallingTailForTarGz() throws Exception {
        // given
        createTarGzArchive("file.tar.gz", "A.log", "content");

        // when
        logViewEndpoint.view("A.log", "file.tar.gz", 1, response);

        // then -> exception
    }

    private void createTarGzArchive(String archiveFileName, String contentFileName, String content) throws Exception {

        try(TarArchiveOutputStream tos = new TarArchiveOutputStream(new GZIPOutputStream(
                new BufferedOutputStream(new FileOutputStream(
                        new File(temporaryFolder.getRoot(), archiveFileName)))))) {
            tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            TarArchiveEntry archiveEntry = new TarArchiveEntry(contentFileName);
            archiveEntry.setSize(content.length());
            tos.putArchiveEntry(archiveEntry);
            IOUtils.write(content, tos);
            tos.closeArchiveEntry();
        }
    }

    @Test
    public void shouldRedirectWithoutTrainingSlash() throws IOException {
        // when
        logViewEndpoint.redirect(response);

        // then
        verify(response).sendRedirect("log/");
    }

    @Test
    public void shouldEndpointBeSensitive() {
        assertThat(logViewEndpoint.isSensitive(), is(true));
    }

    @Test
    public void shouldReturnContextPath() {
        assertThat(logViewEndpoint.getPath(), is("/log"));
    }

    @Test
    public void shouldReturnNullEndpointType() {
        assertThat(logViewEndpoint.getEndpointType(), is(nullValue()));
    }

    @Test
    public void shouldNotAllowToListFileOutsideRoot() throws Exception {
        // given
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage(containsString("may not be located outside base path"));

        // when
        logViewEndpoint.view("../somefile", null, null, null);
    }

    @Test
    public void shouldNotAllowToListWithBaseOutsideRoot() throws Exception {
        // given
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage(containsString("may not be located outside base path"));

        // when
        logViewEndpoint.view("somefile", "../otherdir", null, null);
    }

    @Test
    public void shouldViewFile() throws Exception {
        // given
        createFile("file.log", "abc", now);
        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();

        // when
        logViewEndpoint.view("file.log", null, null, response);

        // then
        assertThat(new String(outputStream.toByteArray()), is("abc"));
    }

    @Test
    public void shouldTailViewOnlyLastLine() throws Exception {
        // given
        createFile("file.log", "line1" + System.lineSeparator() + "line2" + System.lineSeparator(), now);
        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();

        // when
        logViewEndpoint.view("file.log", null, 1, response);

        // then
        assertThat(new String(outputStream.toByteArray()), not(containsString("line1")));
        assertThat(new String(outputStream.toByteArray()), containsString("line2"));
    }

    @Test
    public void shouldSearchInFiles() throws Exception {
        // given
        String sep = System.lineSeparator();
        createFile("A.log", "A-line1" + sep + "A-line2" + sep + "A-line3", now - 1);
        createFile("B.log", "B-line1" + sep + "B-line2" + sep + "B-line3", now);
        ByteArrayServletOutputStream outputStream = mockResponseOutputStream();

        // when
        logViewEndpoint.search("line2", response);

        // then
        String output = new String(outputStream.toByteArray());
        assertThat(output, containsString("[A.log] A-line2"));
        assertThat(output, containsString("[B.log] B-line2"));
        assertThat(output, not(containsString("line1")));
        assertThat(output, not(containsString("line3")));
    }

    private ByteArrayServletOutputStream mockResponseOutputStream() throws Exception {
        ByteArrayServletOutputStream outputStream = new ByteArrayServletOutputStream();
        when(response.getOutputStream()).thenReturn(outputStream);
        return outputStream;
    }

    private List<String> getFileNames() {
        return getFileEntries()
                .stream()
                .map(FileEntry::getFilename)
                .collect(toList());
    }

    private List<Long> getFileSizes() {
        return getFileEntries()
                .stream()
                .map(FileEntry::getSize)
                .collect(toList());
    }

    private List<String> getFilePrettyTimes() {
        return getFileEntries()
                .stream()
                .map(FileEntry::getModifiedPretty)
                .collect(toList());
    }

    private List<FileEntry> getFileEntries() {
        return (List<FileEntry>) model.asMap().get("files");
    }

    private void createFile(String filename, String content, long modified) throws Exception {
        File file = new File(temporaryFolder.getRoot(), filename);
        FileUtils.write(file, content);
        assertThat(file.setLastModified(modified), is(true));
    }

}
include 'lib'

rootProject.children.each {
    it.buildFileName = it.name + '.gradle'
}
package eu.hinsch.spring.boot.actuator.logview;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class LogviewApplication {

    public static void main(String[] args) {
        SpringApplication.run(LogviewApplication.class, args);
    }
}
management:
  context-path: /manage
logging:
  path: /tmp/log
#  file: /tmp/log/custom.log

#endpoints:
#  logview:
#    stylesheets:
#      - http://foo.bar
#      - http://bar.foo
#    path: /tmp/log
package eu.hinsch.spring.boot.actuator.logview;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = LogviewApplication.class)
@WebAppConfiguration
public class LogviewApplicationTests {

	@Test
	public void contextLoads() {
	}

}