Skip to content

Commit

Permalink
Merge pull request #340 from greboid/dev4
Browse files Browse the repository at this point in the history
Stop using addline without timestamp.
  • Loading branch information
csmith committed Jan 15, 2015
2 parents dd997f6 + 0ad1462 commit 1a5a78e
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 40 deletions.
25 changes: 25 additions & 0 deletions logging/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* 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.
*/

dependencies {
testCompile group: 'com.google.jimfs', name: 'jimfs', version: '1.0'
}
1 change: 0 additions & 1 deletion logging/plugin.config
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ defaults:
general.networkfolders=true
advanced.filenamehash=false
general.addtime=true
general.timestamp=[dd/MM/yyyy HH:mm:ss]
general.stripcodes=true
general.channelmodeprefix=true
backbuffer.autobackbuffer=true
Expand Down
40 changes: 31 additions & 9 deletions logging/src/com/dmdirc/addons/logging/HistoryWindow.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,26 @@
import com.dmdirc.ui.messages.BackBufferFactory;
import com.dmdirc.util.io.ReverseFileReader;

import com.google.common.annotations.VisibleForTesting;

import java.io.IOException;
import java.nio.file.Path;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
* Displays an extended history of a window.
*/
public class HistoryWindow extends FrameContainer {

private final Path logFile;
private final DMDircMBassador eventBus;
private final int numLines;

/**
* Creates a new HistoryWindow.
*/
Expand All @@ -54,22 +64,34 @@ public HistoryWindow(
super(parent, "raw", title, title, parent.getConfigManager(), backBufferFactory,
eventBus,
Collections.singletonList(WindowComponent.TEXTAREA.getIdentifier()));
this.logFile = logFile;
this.eventBus = eventBus;
this.numLines = numLines;

initBackBuffer();
final int frameBufferSize = parent.getConfigManager().getOptionInt(
"ui", "frameBufferSize");
try (final ReverseFileReader reader = new ReverseFileReader(logFile)) {
addLine(reader.getLinesAsString(Math.min(frameBufferSize, numLines)), false);
} catch (IOException | SecurityException ex) {
eventBus.publishAsync(
new UserErrorEvent(ErrorLevel.MEDIUM, ex, "Unable to read log file.", ""));
}

outputLoggingBackBuffer(parent.getConfigManager().getOptionInt("ui", "frameBufferSize"));
}

@Override
public Optional<Connection> getConnection() {
return getParent().flatMap(FrameContainer::getConnection);
}

@VisibleForTesting
void outputLoggingBackBuffer(final int limit) {
try (final ReverseFileReader reader = new ReverseFileReader(logFile)) {
final List<String> lines = reader.getLines(Math.min(limit, numLines));
Collections.reverse(lines);
lines.forEach(l -> {
final ParsePosition pos = new ParsePosition(0);
final Date date = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]").parse(l, pos);
final String text = l.substring(pos.getIndex()+1);
addLine(text, date);
});
} catch (IOException | SecurityException ex) {
eventBus.publishAsync(
new UserErrorEvent(ErrorLevel.MEDIUM, ex, "Unable to read log file.", ""));
}
}

}
23 changes: 2 additions & 21 deletions logging/src/com/dmdirc/addons/logging/LoggingManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public class LoggingManager implements ConfigChangeListener {
"EEEE MMMM dd, yyyy - HH:mm:ss");
/** Object for synchronising access to the date forma.t */
private static final Object FORMAT_LOCK = new Object();
private static final DateFormat LOG_FORMAT = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]");
/** This plugin's plugin info. */
private final String domain;
private final PluginInfo pluginInfo;
Expand All @@ -124,8 +125,6 @@ public class LoggingManager implements ConfigChangeListener {
private boolean channelmodeprefix;
private boolean autobackbuffer;
private boolean backbufferTimestamp;
/** Cached string settings. */
private String timestamp;
private String colour;
/** Cached int settings. */
private int historyLines;
Expand Down Expand Up @@ -489,20 +488,7 @@ protected boolean appendLine(final String filename, final String line) {
final StringBuilder finalLine = new StringBuilder();

if (addtime) {
String dateString;
try {
final DateFormat dateFormat = new SimpleDateFormat(timestamp);
dateString = dateFormat.format(new Date()).trim();
} catch (IllegalArgumentException iae) {
// Default to known good format
final DateFormat dateFormat = new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]");
dateString = dateFormat.format(new Date()).trim();

eventBus.publishAsync(new UserErrorEvent(ErrorLevel.LOW, iae,
"Dateformat String '" + timestamp + "' is invalid. For more information: "
+ "http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html",
""));
}
final String dateString = LOG_FORMAT.format(new Date()).trim();
finalLine.append(dateString);
finalLine.append(' ');
}
Expand Down Expand Up @@ -608,7 +594,6 @@ public void setCachedSettings() {
channelmodeprefix = config.getOptionBool(domain, "general.channelmodeprefix");
autobackbuffer = config.getOptionBool(domain, "backbuffer.autobackbuffer");
backbufferTimestamp = config.getOptionBool(domain, "backbuffer.timestamp");
timestamp = config.getOption(domain, "general.timestamp");
historyLines = config.getOptionInt(domain, "history.lines");
colour = config.getOption(domain, "backbuffer.colour");
backbufferLines = config.getOptionInt(domain, "backbuffer.lines");
Expand Down Expand Up @@ -638,10 +623,6 @@ public void showConfig(final ClientPrefsOpenedEvent event) {
pluginInfo.getDomain(), "general.addtime", "Timestamp logs",
"Should a timestamp be added to the log files?",
manager.getConfigManager(), manager.getIdentity()));
general.addSetting(new PreferencesSetting(PreferencesType.TEXT,
pluginInfo.getDomain(), "general.timestamp", "Timestamp format",
"The String to pass to 'SimpleDateFormat' to format the timestamp",
manager.getConfigManager(), manager.getIdentity()));
general.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
pluginInfo.getDomain(), "general.stripcodes", "Strip Control Codes",
"Remove known irc control codes from lines before saving?",
Expand Down
5 changes: 5 additions & 0 deletions logging/test-res/com/dmdirc/addons/logging/logfile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[21/12/2015 12:57:01] RAR
[21/12/2015 12:58:02] RAAR
[21/12/2015 12:59:03] RAAAR
[21/12/2015 13:00:04] RAAAAR
[21/12/2015 13:01:05] RAAAAAR
99 changes: 99 additions & 0 deletions logging/test/com/dmdirc/addons/logging/HistoryWindowTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2006-2015 DMDirc Developers
*
* 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.
*/

package com.dmdirc.addons.logging;

import com.dmdirc.DMDircMBassador;
import com.dmdirc.FrameContainer;
import com.dmdirc.config.ConfigBinder;
import com.dmdirc.events.DisplayPropertyMap;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.ui.messages.BackBuffer;
import com.dmdirc.ui.messages.BackBufferFactory;
import com.dmdirc.ui.messages.IRCDocument;

import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Optional;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static junit.framework.TestCase.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class HistoryWindowTest {

@Mock private IRCDocument document;
@Mock private BackBuffer backBuffer;
@Mock private AggregateConfigProvider config;
@Mock private ConfigBinder configBinder;
@Mock private Connection connection;
@Mock private FrameContainer frameContainer;
@Mock private DMDircMBassador eventBus;
@Mock private BackBufferFactory backBufferFactory;
private HistoryWindow instance;

@Before
public void setUp() throws Exception {
when(backBufferFactory.getBackBuffer(any())).thenReturn(backBuffer);
when(backBuffer.getDocument()).thenReturn(document);
when(config.getBinder()).thenReturn(configBinder);
when(frameContainer.getConfigManager()).thenReturn(config);
when(frameContainer.getConnection()).thenReturn(Optional.of(connection));
instance = new HistoryWindow("Awesome",
Paths.get(getClass().getResource("logfile.txt").toURI()),
frameContainer, eventBus, backBufferFactory, 4);
}

@Test
public void testGetConnection() throws Exception {
assertEquals(Optional.of(connection), instance.getConnection());
}

@Test
public void testOutputLoggingBackBuffer() throws Exception {
instance.outputLoggingBackBuffer(4);
final InOrder inOrder = inOrder(document);
inOrder.verify(document).addText(eq(new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]")
.parse("[21/12/2015 12:58:02]").getTime()), eq
(DisplayPropertyMap.EMPTY), eq("RAAR"));
inOrder.verify(document).addText(eq(new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]")
.parse("[21/12/2015 12:59:03]").getTime()), eq
(DisplayPropertyMap.EMPTY), eq("RAAAR"));
inOrder.verify(document).addText(eq(new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]")
.parse("[21/12/2015 13:00:04]").getTime()), eq
(DisplayPropertyMap.EMPTY), eq("RAAAAR"));
inOrder.verify(document).addText(eq(new SimpleDateFormat("[dd/MM/yyyy HH:mm:ss]")
.parse("[21/12/2015 13:01:05]").getTime()), eq
(DisplayPropertyMap.EMPTY), eq("RAAAAAR"));
inOrder.verifyNoMoreInteractions();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.dmdirc.ui.messages.BackBufferFactory;

import java.util.Arrays;
import java.util.Date;
import java.util.Optional;

/**
Expand Down Expand Up @@ -73,8 +74,8 @@ public Optional<Connection> getConnection() {
* Set the parser to null to stop us holding onto parsers when the server connection is closed.
*/
public void unsetParser() {
addLine("======================", true);
addLine("Unset parser: " + parser, true);
addLine("======================", new Date());
addLine("Unset parser: " + parser, new Date());
parser = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ public boolean addParser(final Parser parser, final Connection connection) {
connection, eventBus, backBufferFactory);
windowManager.addWindow(connection.getWindowModel(), window);
registeredParsers.put(parser, window);
window.addLine("======================", true);
window.addLine("Started Monitoring: " + parser, true);
window.addLine("======================", true);
window.addLine("======================", new Date());
window.addLine("Started Monitoring: " + parser, new Date());
window.addLine("======================", new Date());
return true;
} catch (CallbackNotFoundException ex) {
return false;
Expand All @@ -123,9 +123,9 @@ public boolean removeParser(final Parser parser, final boolean close) {
try {
parser.getCallbackManager().delCallback(DebugInfoListener.class, this);
final DebugWindow window = registeredParsers.get(parser);
window.addLine("======================", true);
window.addLine("No Longer Monitoring: " + parser + " (User Requested)", true);
window.addLine("======================", true);
window.addLine("======================", new Date());
window.addLine("No Longer Monitoring: " + parser + " (User Requested)", new Date());
window.addLine("======================", new Date());
if (close) {
window.close();
}
Expand Down Expand Up @@ -159,7 +159,7 @@ public void handleServerDisconnected(final ServerDisconnectedEvent event) {
public void onDebugInfo(final Parser parser, final Date date, final int level, final String data) {
final DebugWindow window = registeredParsers.get(parser);
if (window != null) {
window.addLine(String.format("[%d] %s%n", level, data), true);
window.addLine(String.format("[%d] %s%n", level, data), new Date());
}
}

Expand Down

0 comments on commit 1a5a78e

Please sign in to comment.