Java tutorial
/* * Copyright 2014 Andrew Tytula. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kajj.tools.logviewer; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.io.input.ReversedLinesFileReader; import org.springframework.stereotype.Repository; /** * A repository for retrieving logs from a file. * * @author Andrew Tytula */ @Repository public class LogRepository { private static final File LOG_DIRECTORY = new File("../logs/"); /** * Returns the last <code>numberOfLines</code> lines from the log file. * * @param fileName the name of the log file. * @param numberOfLines the number of lines to return. * @return The last <code>numberOfLines</code> lines in the log file. * @throws IOException if an I/O exception occurs reading the log file. */ public List<String> getTailLog(final String fileName, final int numberOfLines) throws IOException { final File logFile = new File(LOG_DIRECTORY, fileName); final ReversedLinesFileReader reader = new ReversedLinesFileReader(logFile); final LinkedList<String> logs = new LinkedList<>(); for (int i = 0; i < numberOfLines; i++) { final String line = reader.readLine(); if (line == null) { break; } logs.addFirst(line); } return logs; } /** * Returns a list of file names that can be accessed by the repository. * * @return the list of file names */ public List<String> getLogFileNames() { return Arrays.asList(LOG_DIRECTORY.list()); } }