You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by ma...@apache.org on 2018/03/13 07:04:35 UTC
[07/27] logging-chainsaw git commit: Reformat code for consistency
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiver.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiver.java b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiver.java
index 4a733ef..daa0c2c 100644
--- a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiver.java
+++ b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiver.java
@@ -1,12 +1,12 @@
/*
* Copyright 1999,2004 The Apache Software Foundation.
- *
+ *
* 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
@@ -16,42 +16,20 @@
package org.apache.log4j.chainsaw.vfs;
-import java.awt.Container;
-import java.awt.Dimension;
-import java.awt.Frame;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.awt.Toolkit;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JPasswordField;
-import javax.swing.JTextField;
-import javax.swing.SwingUtilities;
-
-import org.apache.commons.vfs.FileObject;
-import org.apache.commons.vfs.FileSystemException;
-import org.apache.commons.vfs.FileSystemManager;
-import org.apache.commons.vfs.FileSystemOptions;
-import org.apache.commons.vfs.RandomAccessContent;
-import org.apache.commons.vfs.VFS;
+import org.apache.commons.vfs.*;
import org.apache.commons.vfs.provider.URLFileName;
import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;
import org.apache.commons.vfs.util.RandomAccessMode;
import org.apache.log4j.chainsaw.receivers.VisualReceiver;
import org.apache.log4j.varia.LogFilePatternReceiver;
+import javax.swing.*;
+import java.awt.*;
+import java.io.*;
+
/**
* A VFS-enabled version of org.apache.log4j.varia.LogFilePatternReceiver.
- *
+ * <p>
* VFSLogFilePatternReceiver can parse and tail log files, converting entries into
* LoggingEvents. If the file doesn't exist when the receiver is initialized, the
* receiver will look for the file once every 10 seconds.
@@ -63,17 +41,17 @@ import org.apache.log4j.varia.LogFilePatternReceiver;
* file systems and the URIs needed to access the file systems.
* <p>
* Because some VFS file systems allow you to provide username/password, this receiver
- * provides an optional GUI dialog for entering the username/password fields instead
+ * provides an optional GUI dialog for entering the username/password fields instead
* of requiring you to hard code usernames and passwords into the URI.
* <p>
- * If the 'promptForUserInfo' param is set to true (default is false),
- * the receiver will wait for a call to 'setContainer', and then display
+ * If the 'promptForUserInfo' param is set to true (default is false),
+ * the receiver will wait for a call to 'setContainer', and then display
* a username/password dialog.
* <p>
- * If you are using this receiver without a GUI, don't set promptForUserInfo
+ * If you are using this receiver without a GUI, don't set promptForUserInfo
* to true - it will block indefinitely waiting for a visual component.
- * <p>
- * If the 'promptForUserInfo' param is set to true, the fileURL should -leave out-
+ * <p>
+ * If the 'promptForUserInfo' param is set to true, the fileURL should -leave out-
* the username/password portion of the VFS-supported URI. Examples:
* <p>
* An sftp URI that would be used with promptForUserInfo=true:
@@ -82,8 +60,8 @@ import org.apache.log4j.varia.LogFilePatternReceiver;
* An sftp URI that would be used with promptForUserInfo=false:
* sftp://username:password@192.168.1.100:22/home/thisuser/logfile.txt
* <p>
- * This receiver relies on java.util.regex features to perform the parsing of text in the
- * log file, however the only regular expression field explicitly supported is
+ * This receiver relies on java.util.regex features to perform the parsing of text in the
+ * log file, however the only regular expression field explicitly supported is
* a glob-style wildcard used to ignore fields in the log file if needed. All other
* fields are parsed by using the supplied keywords.
* <p>
@@ -93,8 +71,8 @@ import org.apache.log4j.varia.LogFilePatternReceiver;
* - specify the pattern (logFormat) used in the log file using keywords, a wildcard character (*) and fixed text<br>
* - 'tail' the file (allows the contents of the file to be continually read and new events processed)<br>
* - supports the parsing of multi-line messages and exceptions
- * - to access
- *<p>
+ * - to access
+ * <p>
* <b>Keywords:</b><br>
* TIMESTAMP<br>
* LOGGER<br>
@@ -114,128 +92,130 @@ import org.apache.log4j.varia.LogFilePatternReceiver;
* Example:<br>
* If your file's patternlayout is this:<br>
* <b>%d %-5p [%t] %C{2} (%F:%L) - %m%n</b>
- *<p>
+ * <p>
* specify this as the log format:<br>
* <b>TIMESTAMP LEVEL [THREAD] CLASS (FILE:LINE) - MESSAGE</b>
- *<p>
+ * <p>
* To define a PROPERTY field, use PROP(key)
* <p>
- * Example:<br>
- * If you used the RELATIVETIME pattern layout character in the file,
- * you can use PROP(RELATIVETIME) in the logFormat definition to assign
+ * Example:<br>
+ * If you used the RELATIVETIME pattern layout character in the file,
+ * you can use PROP(RELATIVETIME) in the logFormat definition to assign
* the RELATIVETIME field as a property on the event.
* <p>
* If your file's patternlayout is this:<br>
* <b>%r [%t] %-5p %c %x - %m%n</b>
- *<p>
+ * <p>
* specify this as the log format:<br>
* <b>PROP(RELATIVETIME) [THREAD] LEVEL LOGGER * - MESSAGE</b>
* <p>
* Note the * - it can be used to ignore a single word or sequence of words in the log file
* (in order for the wildcard to ignore a sequence of words, the text being ignored must be
- * followed by some delimiter, like '-' or '[') - ndc is being ignored in this example.
+ * followed by some delimiter, like '-' or '[') - ndc is being ignored in this example.
* <p>
* Assign a filterExpression in order to only process events which match a filter.
* If a filterExpression is not assigned, all events are processed.
- *<p>
+ * <p>
* <b>Limitations:</b><br>
* - no support for the single-line version of throwable supported by patternlayout<br>
- * (this version of throwable will be included as the last line of the message)<br>
+ * (this version of throwable will be included as the last line of the message)<br>
* - the relativetime patternLayout character must be set as a property: PROP(RELATIVETIME)<br>
* - messages should appear as the last field of the logFormat because the variability in message content<br>
* - exceptions are converted if the exception stack trace (other than the first line of the exception)<br>
- * is stored in the log file with a tab followed by the word 'at' as the first characters in the line<br>
- * - tailing may fail if the file rolls over.
- *<p>
+ * is stored in the log file with a tab followed by the word 'at' as the first characters in the line<br>
+ * - tailing may fail if the file rolls over.
+ * <p>
* <b>Example receiver configuration settings</b> (add these as params, specifying a LogFilePatternReceiver 'plugin'):<br>
* param: "timestampFormat" value="yyyy-MM-d HH:mm:ss,SSS"<br>
* param: "logFormat" value="RELATIVETIME [THREAD] LEVEL LOGGER * - MESSAGE"<br>
* param: "fileURL" value="file:///c:/events.log"<br>
* param: "tailing" value="true"
* param: "promptForUserInfo" value="false"
- *<p>
+ * <p>
* This configuration will be able to process these sample events:<br>
* 710 [ Thread-0] DEBUG first.logger first - <test> <test2>something here</test2> <test3 blah=something/> <test4> <test5>something else</test5> </test4></test><br>
* 880 [ Thread-2] DEBUG first.logger third - <test> <test2>something here</test2> <test3 blah=something/> <test4> <test5>something else</test5> </test4></test><br>
* 880 [ Thread-0] INFO first.logger first - infomsg-0<br>
* java.lang.Exception: someexception-first<br>
- * at Generator2.run(Generator2.java:102)<br>
+ * at Generator2.run(Generator2.java:102)<br>
*
- *@author Scott Deboy
+ * @author Scott Deboy
*/
public class VFSLogFilePatternReceiver extends LogFilePatternReceiver implements VisualReceiver {
- private boolean promptForUserInfo = false;
- private Container container;
- private final Object waitForContainerLock = new Object();
- private boolean autoReconnect;
- private VFSReader vfsReader;
+ private boolean promptForUserInfo = false;
+ private Container container;
+ private final Object waitForContainerLock = new Object();
+ private boolean autoReconnect;
+ private VFSReader vfsReader;
public VFSLogFilePatternReceiver() {
- super();
- }
-
- public void shutdown() {
- getLogger().info("shutdown VFSLogFilePatternReceiver");
- active = false;
- container = null;
- if (vfsReader != null) {
- vfsReader.terminate();
- vfsReader = null;
+ super();
+ }
+
+ public void shutdown() {
+ getLogger().info("shutdown VFSLogFilePatternReceiver");
+ active = false;
+ container = null;
+ if (vfsReader != null) {
+ vfsReader.terminate();
+ vfsReader = null;
+ }
+ }
+
+ /**
+ * If set to true, will cause the receiver to block indefinitely until 'setContainer' has been called,
+ * at which point a username/password dialog will appear.
+ *
+ * @param promptForUserInfo
+ */
+ public void setPromptForUserInfo(boolean promptForUserInfo) {
+ this.promptForUserInfo = promptForUserInfo;
+ }
+
+ public boolean isPromptForUserInfo() {
+ return promptForUserInfo;
}
- }
-
- /**
- * If set to true, will cause the receiver to block indefinitely until 'setContainer' has been called,
- * at which point a username/password dialog will appear.
- *
- * @param promptForUserInfo
- */
- public void setPromptForUserInfo(boolean promptForUserInfo) {
- this.promptForUserInfo = promptForUserInfo;
- }
-
- public boolean isPromptForUserInfo() {
- return promptForUserInfo;
- }
/**
* Accessor
+ *
* @return
*/
public boolean isAutoReconnect() {
- return autoReconnect;
+ return autoReconnect;
}
/**
* Mutator
+ *
* @param autoReconnect
*/
public void setAutoReconnect(boolean autoReconnect) {
this.autoReconnect = autoReconnect;
}
- /**
- * Implementation of VisualReceiver interface - allows this receiver to provide
- * a username/password dialog.
- */
- public void setContainer(Container container) {
- if (promptForUserInfo) {
- synchronized(waitForContainerLock) {
- this.container=container;
- waitForContainerLock.notify();
- }
- }
- }
-
- /**
- * Read and process the log file.
- */
- public void activateOptions() {
- //we don't want to call super.activateOptions, but we do want active to be set to true
- active = true;
- //on receiver restart, only prompt for credentials if we don't already have them
- if (promptForUserInfo && !getFileURL().contains("@")) {
+ /**
+ * Implementation of VisualReceiver interface - allows this receiver to provide
+ * a username/password dialog.
+ */
+ public void setContainer(Container container) {
+ if (promptForUserInfo) {
+ synchronized (waitForContainerLock) {
+ this.container = container;
+ waitForContainerLock.notify();
+ }
+ }
+ }
+
+ /**
+ * Read and process the log file.
+ */
+ public void activateOptions() {
+ //we don't want to call super.activateOptions, but we do want active to be set to true
+ active = true;
+ //on receiver restart, only prompt for credentials if we don't already have them
+ if (promptForUserInfo && !getFileURL().contains("@")) {
/*
if promptforuserinfo is true, wait for a reference to the container
(via the VisualReceiver callback).
@@ -244,116 +224,118 @@ public class VFSLogFilePatternReceiver extends LogFilePatternReceiver implements
wait until the container has been added to a frame
*/
- //get a reference to the container
- new Thread(() -> {
- synchronized(waitForContainerLock) {
- while (container == null) {
- try {
- waitForContainerLock.wait(1000);
- getLogger().debug("waiting for setContainer call");
- } catch (InterruptedException ie){}
- }
- }
-
- Frame containerFrame1;
-if (container instanceof Frame) {
-containerFrame1 = (Frame)container;
-} else {
-synchronized(waitForContainerLock) {
-//loop until the container has a frame
-while ((containerFrame1 = (Frame)SwingUtilities.getAncestorOfClass(Frame.class, container)) == null) {
-try {
-waitForContainerLock.wait(1000);
-getLogger().debug("waiting for container's frame to be available");
-} catch (InterruptedException ie) {}
-}
-}
-}
-final Frame containerFrame = containerFrame1;
- //create the dialog
- SwingUtilities.invokeLater(() -> {
- Frame owner = null;
- if (container != null) {
- owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, containerFrame);
+ //get a reference to the container
+ new Thread(() -> {
+ synchronized (waitForContainerLock) {
+ while (container == null) {
+ try {
+ waitForContainerLock.wait(1000);
+ getLogger().debug("waiting for setContainer call");
+ } catch (InterruptedException ie) {
+ }
+ }
}
- final UserNamePasswordDialog f = new UserNamePasswordDialog(owner);
- f.pack();
- Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
- f.setLocation(d.width / 2, d.height / 2);
- f.setVisible(true);
- if (null == f.getUserName() || null == f.getPassword()) {
- getLogger().info("Username and password not both provided, not using credentials");
- } else {
- String oldURL = getFileURL();
- int index = oldURL.indexOf("://");
- String firstPart = oldURL.substring(0, index);
- String lastPart = oldURL.substring(index + "://".length());
- setFileURL(firstPart + "://" + f.getUserName() + ":" + new String(f.getPassword()) + "@" + lastPart);
+ Frame containerFrame1;
+ if (container instanceof Frame) {
+ containerFrame1 = (Frame) container;
+ } else {
+ synchronized (waitForContainerLock) {
+//loop until the container has a frame
+ while ((containerFrame1 = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, container)) == null) {
+ try {
+ waitForContainerLock.wait(1000);
+ getLogger().debug("waiting for container's frame to be available");
+ } catch (InterruptedException ie) {
+ }
+ }
+ }
+ }
+ final Frame containerFrame = containerFrame1;
+ //create the dialog
+ SwingUtilities.invokeLater(() -> {
+ Frame owner = null;
+ if (container != null) {
+ owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, containerFrame);
+ }
+ final UserNamePasswordDialog f = new UserNamePasswordDialog(owner);
+ f.pack();
+ Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
+ f.setLocation(d.width / 2, d.height / 2);
+ f.setVisible(true);
+ if (null == f.getUserName() || null == f.getPassword()) {
+ getLogger().info("Username and password not both provided, not using credentials");
+ } else {
+ String oldURL = getFileURL();
+ int index = oldURL.indexOf("://");
+ String firstPart = oldURL.substring(0, index);
+ String lastPart = oldURL.substring(index + "://".length());
+ setFileURL(firstPart + "://" + f.getUserName() + ":" + new String(f.getPassword()) + "@" + lastPart);
+
+ setHost(oldURL.substring(0, index + "://".length()));
+ setPath(oldURL.substring(index + "://".length()));
+ }
+ vfsReader = new VFSReader();
+ new Thread(vfsReader).start();
+ });
+ }).start();
+ } else {
+ //starts with protocol:/ but not protocol://
+ String oldURL = getFileURL();
+ if (oldURL != null && oldURL.contains(":/") && !oldURL.contains("://")) {
+ int index = oldURL.indexOf(":/");
+ String lastPart = oldURL.substring(index + ":/".length());
+ int passEndIndex = lastPart.indexOf("@");
+ if (passEndIndex > -1) { //we have a username/password
+ setHost(oldURL.substring(0, index + ":/".length()));
+ setPath(lastPart.substring(passEndIndex + 1));
+ }
+ vfsReader = new VFSReader();
+ new Thread(vfsReader).start();
+ } else if (oldURL != null && oldURL.contains("://")) {
+ //starts with protocol://
+ int index = oldURL.indexOf("://");
+ String lastPart = oldURL.substring(index + "://".length());
+ int passEndIndex = lastPart.indexOf("@");
+ if (passEndIndex > -1) { //we have a username/password
setHost(oldURL.substring(0, index + "://".length()));
- setPath(oldURL.substring(index + "://".length()));
+ setPath(lastPart.substring(passEndIndex + 1));
}
vfsReader = new VFSReader();
new Thread(vfsReader).start();
- });
- }).start();
- } else {
- //starts with protocol:/ but not protocol://
- String oldURL = getFileURL();
- if (oldURL != null && oldURL.contains(":/") && !oldURL.contains("://")) {
- int index = oldURL.indexOf(":/");
- String lastPart = oldURL.substring(index + ":/".length());
- int passEndIndex = lastPart.indexOf("@");
- if (passEndIndex > -1) { //we have a username/password
- setHost(oldURL.substring(0, index + ":/".length()));
- setPath(lastPart.substring(passEndIndex + 1));
- }
- vfsReader = new VFSReader();
- new Thread(vfsReader).start();
- } else if (oldURL != null && oldURL.contains("://")) {
- //starts with protocol://
- int index = oldURL.indexOf("://");
- String lastPart = oldURL.substring(index + "://".length());
- int passEndIndex = lastPart.indexOf("@");
- if (passEndIndex > -1) { //we have a username/password
- setHost(oldURL.substring(0, index + "://".length()));
- setPath(lastPart.substring(passEndIndex + 1));
+ } else {
+ getLogger().info("null URL - unable to parse file");
}
- vfsReader = new VFSReader();
- new Thread(vfsReader).start();
- } else {
- getLogger().info("null URL - unable to parse file");
}
- }
- }
+ }
- private class VFSReader implements Runnable {
- private boolean terminated = false;
- private Reader reader;
- private FileObject fileObject;
+ private class VFSReader implements Runnable {
+ private boolean terminated = false;
+ private Reader reader;
+ private FileObject fileObject;
- public void run() {
- //thread should end when we're no longer active
+ public void run() {
+ //thread should end when we're no longer active
while (reader == null && !terminated) {
- int atIndex = getFileURL().indexOf("@");
- int protocolIndex = getFileURL().indexOf("://");
-
- String loggableFileURL = atIndex > -1? getFileURL().substring(0, protocolIndex + "://".length()) + "username:password" + getFileURL().substring(atIndex) : getFileURL();
+ int atIndex = getFileURL().indexOf("@");
+ int protocolIndex = getFileURL().indexOf("://");
+
+ String loggableFileURL = atIndex > -1 ? getFileURL().substring(0, protocolIndex + "://".length()) + "username:password" + getFileURL().substring(atIndex) : getFileURL();
getLogger().info("attempting to load file: " + loggableFileURL);
try {
FileSystemManager fileSystemManager = VFS.getManager();
FileSystemOptions opts = new FileSystemOptions();
//if jsch not in classpath, can get NoClassDefFoundError here
try {
- SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
+ SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
} catch (NoClassDefFoundError ncdfe) {
- getLogger().warn("JSch not on classpath!", ncdfe);
+ getLogger().warn("JSch not on classpath!", ncdfe);
}
- synchronized(fileSystemManager) {
+ synchronized (fileSystemManager) {
fileObject = fileSystemManager.resolveFile(getFileURL(), opts);
if (fileObject.exists()) {
- reader = new InputStreamReader(fileObject.getContent().getInputStream() , "UTF-8");
+ reader = new InputStreamReader(fileObject.getContent().getInputStream(), "UTF-8");
//now that we have a reader, remove additional portions of the file url (sftp passwords, etc.)
//check to see if the name is a URLFileName..if so, set file name to not include username/pass
if (fileObject.getName() instanceof URLFileName) {
@@ -374,7 +356,8 @@ final Frame containerFrame = containerFrame1;
synchronized (this) {
try {
wait(MISSING_FILE_RETRY_MILLIS);
- } catch (InterruptedException ie) {}
+ } catch (InterruptedException ie) {
+ }
}
}
}
@@ -401,14 +384,14 @@ final Frame containerFrame = containerFrame1;
}
//fileobject was created above, release it and construct a new one
- synchronized(fileSystemManager) {
- if (fileObject != null) {
- fileObject.getFileSystem().getFileSystemManager().closeFileSystem(fileObject.getFileSystem());
- fileObject.close();
- fileObject = null;
+ synchronized (fileSystemManager) {
+ if (fileObject != null) {
+ fileObject.getFileSystem().getFileSystemManager().closeFileSystem(fileObject.getFileSystem());
+ fileObject.close();
+ fileObject = null;
}
-
- fileObject = fileSystemManager.resolveFile(getFileURL(), opts);
+
+ fileObject = fileSystemManager.resolveFile(getFileURL(), opts);
}
//file may not exist..
@@ -453,7 +436,8 @@ final Frame containerFrame = containerFrame1;
synchronized (this) {
wait(getWaitMillis());
}
- } catch (InterruptedException ie) {}
+ } catch (InterruptedException ie) {
+ }
if (isTailing() && fileLarger && !terminated) {
getLogger().debug(getPath() + " - tailing file - file size: " + lastFileSize);
}
@@ -468,89 +452,90 @@ final Frame containerFrame = containerFrame1;
getLogger().info(getPath() + " - exception processing file", e);
}
try {
- synchronized(this) {
+ synchronized (this) {
wait(getWaitMillis());
}
- } catch (InterruptedException ie) {}
+ } catch (InterruptedException ie) {
+ }
}
} while (isAutoReconnect() && !terminated);
getLogger().debug(getPath() + " - processing complete");
}
- public void terminate()
- {
- terminated = true;
- }
- }
-
- public class UserNamePasswordDialog extends JDialog {
- private String userName;
- private char[] password;
- private UserNamePasswordDialog(Frame containerFrame) {
- super(containerFrame, "Login", true);
- JPanel panel = new JPanel(new GridBagLayout());
- GridBagConstraints gc = new GridBagConstraints();
- gc.fill=GridBagConstraints.NONE;
-
- gc.anchor=GridBagConstraints.NORTH;
- gc.gridx=0;
- gc.gridy=0;
- gc.gridwidth=3;
- gc.insets=new Insets(7, 7, 7, 7);
- panel.add(new JLabel("URI: " + getFileURL()), gc);
-
- gc.gridx=0;
- gc.gridy=1;
- gc.gridwidth=1;
- gc.insets=new Insets(2, 2, 2, 2);
- panel.add(new JLabel("Username"), gc);
-
- gc.gridx=1;
- gc.gridy=1;
- gc.gridwidth=2;
- gc.weightx=1.0;
- gc.fill=GridBagConstraints.HORIZONTAL;
-
- final JTextField userNameTextField = new JTextField(15);
- panel.add(userNameTextField, gc);
-
- gc.gridx=0;
- gc.gridy=2;
- gc.gridwidth=1;
- gc.fill=GridBagConstraints.NONE;
-
- panel.add(new JLabel("Password"), gc);
-
- gc.gridx=1;
- gc.gridy=2;
- gc.gridwidth=2;
- gc.fill=GridBagConstraints.HORIZONTAL;
-
- final JPasswordField passwordTextField = new JPasswordField(15);
- panel.add(passwordTextField, gc);
-
- gc.gridy=3;
- gc.anchor=GridBagConstraints.SOUTH;
- gc.fill=GridBagConstraints.NONE;
-
- JButton submitButton = new JButton(" Submit ");
- panel.add(submitButton, gc);
-
- getContentPane().add(panel);
- submitButton.addActionListener(evt -> {
- userName = userNameTextField.getText();
- password = passwordTextField.getPassword();
- getContentPane().setVisible(false);
- UserNamePasswordDialog.this.dispose();
- });
- }
-
- public String getUserName() {
- return userName;
- }
-
- public char[] getPassword() {
- return password;
- }
- }
+ public void terminate() {
+ terminated = true;
+ }
+ }
+
+ public class UserNamePasswordDialog extends JDialog {
+ private String userName;
+ private char[] password;
+
+ private UserNamePasswordDialog(Frame containerFrame) {
+ super(containerFrame, "Login", true);
+ JPanel panel = new JPanel(new GridBagLayout());
+ GridBagConstraints gc = new GridBagConstraints();
+ gc.fill = GridBagConstraints.NONE;
+
+ gc.anchor = GridBagConstraints.NORTH;
+ gc.gridx = 0;
+ gc.gridy = 0;
+ gc.gridwidth = 3;
+ gc.insets = new Insets(7, 7, 7, 7);
+ panel.add(new JLabel("URI: " + getFileURL()), gc);
+
+ gc.gridx = 0;
+ gc.gridy = 1;
+ gc.gridwidth = 1;
+ gc.insets = new Insets(2, 2, 2, 2);
+ panel.add(new JLabel("Username"), gc);
+
+ gc.gridx = 1;
+ gc.gridy = 1;
+ gc.gridwidth = 2;
+ gc.weightx = 1.0;
+ gc.fill = GridBagConstraints.HORIZONTAL;
+
+ final JTextField userNameTextField = new JTextField(15);
+ panel.add(userNameTextField, gc);
+
+ gc.gridx = 0;
+ gc.gridy = 2;
+ gc.gridwidth = 1;
+ gc.fill = GridBagConstraints.NONE;
+
+ panel.add(new JLabel("Password"), gc);
+
+ gc.gridx = 1;
+ gc.gridy = 2;
+ gc.gridwidth = 2;
+ gc.fill = GridBagConstraints.HORIZONTAL;
+
+ final JPasswordField passwordTextField = new JPasswordField(15);
+ panel.add(passwordTextField, gc);
+
+ gc.gridy = 3;
+ gc.anchor = GridBagConstraints.SOUTH;
+ gc.fill = GridBagConstraints.NONE;
+
+ JButton submitButton = new JButton(" Submit ");
+ panel.add(submitButton, gc);
+
+ getContentPane().add(panel);
+ submitButton.addActionListener(evt -> {
+ userName = userNameTextField.getText();
+ password = passwordTextField.getPassword();
+ getContentPane().setVisible(false);
+ UserNamePasswordDialog.this.dispose();
+ });
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public char[] getPassword() {
+ return password;
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
index a99d248..c3985e3 100644
--- a/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
+++ b/src/main/java/org/apache/log4j/chainsaw/vfs/VFSLogFilePatternReceiverBeanInfo.java
@@ -23,34 +23,33 @@ import java.beans.SimpleBeanInfo;
/**
* BeanInfo class for the meta-data of the VFSLogFilePatternReceiver.
- *
*/
public class VFSLogFilePatternReceiverBeanInfo extends SimpleBeanInfo {
- /* (non-Javadoc)
- * @see java.beans.BeanInfo#getPropertyDescriptors()
- */
- public PropertyDescriptor[] getPropertyDescriptors() {
- try {
- return new PropertyDescriptor[] {
- new PropertyDescriptor("fileURL", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor(
- "timestampFormat", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("logFormat", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("name", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("tailing", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("autoReconnect", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("waitMillis", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("appendNonMatches", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("customLevelDefinitions", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor(
- "filterExpression", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor(
- "promptForUserInfo", VFSLogFilePatternReceiver.class),
- new PropertyDescriptor("group", VFSLogFilePatternReceiver.class),
- };
- } catch (Exception e) {
- }
+ /* (non-Javadoc)
+ * @see java.beans.BeanInfo#getPropertyDescriptors()
+ */
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ return new PropertyDescriptor[]{
+ new PropertyDescriptor("fileURL", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor(
+ "timestampFormat", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("logFormat", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("name", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("tailing", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("autoReconnect", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("waitMillis", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("appendNonMatches", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("customLevelDefinitions", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor(
+ "filterExpression", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor(
+ "promptForUserInfo", VFSLogFilePatternReceiver.class),
+ new PropertyDescriptor("group", VFSLogFilePatternReceiver.class),
+ };
+ } catch (Exception e) {
+ }
- return null;
- }
+ return null;
+ }
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/xstream/TableColumnConverter.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/xstream/TableColumnConverter.java b/src/main/java/org/apache/log4j/chainsaw/xstream/TableColumnConverter.java
index 7a4db60..55e2a5f 100644
--- a/src/main/java/org/apache/log4j/chainsaw/xstream/TableColumnConverter.java
+++ b/src/main/java/org/apache/log4j/chainsaw/xstream/TableColumnConverter.java
@@ -16,22 +16,21 @@
*/
package org.apache.log4j.chainsaw.xstream;
-import javax.swing.table.TableColumn;
-
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import javax.swing.table.TableColumn;
+
/**
* XStream Converter implementation that deals with TableColumns settings
- *
+ *
+ * @author psmith
* @see Converter
* @see "XStream"
* @see TableColumn
- * @author psmith
- *
*/
public class TableColumnConverter implements Converter {
@@ -40,7 +39,7 @@ public class TableColumnConverter implements Converter {
}
public void marshal(Object source, HierarchicalStreamWriter writer,
- MarshallingContext context) {
+ MarshallingContext context) {
TableColumn column = (TableColumn) source;
writer.addAttribute("width", column.getWidth() + "");
writer.addAttribute("modelIndex", column.getModelIndex() + "");
@@ -48,12 +47,12 @@ public class TableColumnConverter implements Converter {
}
public Object unmarshal(HierarchicalStreamReader reader,
- UnmarshallingContext context) {
+ UnmarshallingContext context) {
TableColumn column = new TableColumn();
column.setWidth(Integer.parseInt(reader.getAttribute("width")));
column.setPreferredWidth(column.getWidth());
column.setModelIndex(Integer
- .parseInt(reader.getAttribute("modelIndex")));
+ .parseInt(reader.getAttribute("modelIndex")));
column.setHeaderValue(reader.getAttribute("headerValue"));
return column;
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfDeviceModel.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfDeviceModel.java b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfDeviceModel.java
index 27572b7..7b4f166 100644
--- a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfDeviceModel.java
+++ b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfDeviceModel.java
@@ -16,24 +16,23 @@
*/
package org.apache.log4j.chainsaw.zeroconf;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import javax.swing.table.AbstractTableModel;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
public class ZeroConfDeviceModel extends AbstractTableModel implements ServiceListener {
private List<ServiceInfo> deviceList = new ArrayList<>();
private ZeroConfPreferenceModel zeroConfPreferenceModel;
private transient ZeroConfPlugin plugin;
-
+
public ZeroConfDeviceModel() {
}
-
+
public int getRowCount() {
return deviceList.size();
}
@@ -45,23 +44,24 @@ public class ZeroConfDeviceModel extends AbstractTableModel implements ServiceLi
public ServiceInfo getServiceInfoAtRow(int row) {
return deviceList.get(row);
}
+
public Object getValueAt(int rowIndex, int columnIndex) {
ServiceInfo info = deviceList.get(rowIndex);
- if(info == null) {
+ if (info == null) {
return "";
}
- switch(columnIndex) {
- case 0:
+ switch (columnIndex) {
+ case 0:
return getAutoConnectHandle(info);
- case 1:
+ case 1:
return info.getAddress().getHostName() + ":" + info.getPort();
- case 2:
- return zeroConfPreferenceModel.getAutoConnectDevices().contains(getAutoConnectHandle(info))?Boolean.TRUE:Boolean.FALSE;
- case 3:
- return plugin.isConnectedTo(info)?"Connected":"Not Connected";
+ case 2:
+ return zeroConfPreferenceModel.getAutoConnectDevices().contains(getAutoConnectHandle(info)) ? Boolean.TRUE : Boolean.FALSE;
+ case 3:
+ return plugin.isConnectedTo(info) ? "Connected" : "Not Connected";
// return plugin.isConnectedTo(info)?new ImageIcon(ChainsawIcons.ANIM_NET_CONNECT):new ImageIcon();
default:
- return "";
+ return "";
}
}
@@ -73,9 +73,9 @@ public class ZeroConfDeviceModel extends AbstractTableModel implements ServiceLi
}
public void serviceRemoved(ServiceEvent event) {
- for (Iterator<ServiceInfo> iter = deviceList.iterator(); iter.hasNext();) {
+ for (Iterator<ServiceInfo> iter = deviceList.iterator(); iter.hasNext(); ) {
ServiceInfo info = iter.next();
- if(info.getName().equals(event.getName())) {
+ if (info.getName().equals(event.getName())) {
iter.remove();
}
}
@@ -88,22 +88,22 @@ public class ZeroConfDeviceModel extends AbstractTableModel implements ServiceLi
}
public void setZeroConfPreferenceModel(
- ZeroConfPreferenceModel zeroConfPreferenceModel) {
+ ZeroConfPreferenceModel zeroConfPreferenceModel) {
this.zeroConfPreferenceModel = zeroConfPreferenceModel;
}
public String getColumnName(int column) {
- switch(column) {
- case 0:
+ switch (column) {
+ case 0:
return "ZeroConf name";
- case 1:
+ case 1:
return "Address:Port";
- case 2:
+ case 2:
return "Auto-connect";
- case 3:
+ case 3:
return "Connection Status";
default:
- return "";
+ return "";
}
}
@@ -112,29 +112,29 @@ public class ZeroConfDeviceModel extends AbstractTableModel implements ServiceLi
}
public Class getColumnClass(int columnIndex) {
- switch(columnIndex) {
- case 2:
- return Boolean.class;
- default:
- return super.getColumnClass(columnIndex);
+ switch (columnIndex) {
+ case 2:
+ return Boolean.class;
+ default:
+ return super.getColumnClass(columnIndex);
}
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
- if(columnIndex!=2 || !(aValue instanceof Boolean)) {
+ if (columnIndex != 2 || !(aValue instanceof Boolean)) {
return;
}
boolean autoConnect = (Boolean) aValue;
Object device = this.deviceList.get(rowIndex);
String autoConnectHandle = getAutoConnectHandle((ServiceInfo) device);
- if(autoConnect) {
+ if (autoConnect) {
zeroConfPreferenceModel.getAutoConnectDevices().add(autoConnectHandle);
- }else {
+ } else {
zeroConfPreferenceModel.getAutoConnectDevices().remove(autoConnectHandle);
}
fireTableDataChanged();
}
-
+
void setZeroConfPluginParent(ZeroConfPlugin parent) {
this.plugin = parent;
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPlugin.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPlugin.java b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPlugin.java
index 7f08c25..3f8ccf7 100644
--- a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPlugin.java
+++ b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPlugin.java
@@ -16,26 +16,8 @@
*/
package org.apache.log4j.chainsaw.zeroconf;
-import java.awt.BorderLayout;
-import java.awt.Component;
-import java.awt.event.ActionEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import javax.jmdns.JmDNS;
-import javax.jmdns.ServiceEvent;
-import javax.jmdns.ServiceInfo;
-import javax.jmdns.ServiceListener;
-import javax.swing.*;
-
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.io.xml.DomDriver;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
@@ -48,33 +30,38 @@ import org.apache.log4j.chainsaw.plugins.GUIPluginSkeleton;
import org.apache.log4j.chainsaw.prefs.SettingsManager;
import org.apache.log4j.chainsaw.vfs.VFSLogFilePatternReceiver;
import org.apache.log4j.helpers.LogLog;
-import org.apache.log4j.net.MulticastReceiver;
-import org.apache.log4j.net.SocketHubReceiver;
-import org.apache.log4j.net.SocketReceiver;
-import org.apache.log4j.net.UDPReceiver;
-import org.apache.log4j.net.XMLSocketReceiver;
-import org.apache.log4j.net.ZeroConfSupport;
+import org.apache.log4j.net.*;
import org.apache.log4j.plugins.Plugin;
import org.apache.log4j.plugins.PluginEvent;
import org.apache.log4j.plugins.PluginListener;
import org.apache.log4j.plugins.Receiver;
import org.apache.log4j.spi.LoggerRepositoryEx;
-import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.io.xml.DomDriver;
+import javax.jmdns.JmDNS;
+import javax.jmdns.ServiceEvent;
+import javax.jmdns.ServiceInfo;
+import javax.jmdns.ServiceListener;
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.util.*;
/**
* This plugin is designed to detect specific Zeroconf zones (Rendevouz/Bonjour,
* whatever people are calling it) and allow the user to double click on
* 'devices' to try and connect to them with no configuration needed.
- *
+ * <p>
* TODO need to handle
- * NON-log4j devices that may be broadcast in the interested zones
+ * NON-log4j devices that may be broadcast in the interested zones
* TODO add the
* default Zone, and the list of user-specified zones to a preferenceModel
- *
+ *
* @author psmith
- *
*/
public class ZeroConfPlugin extends GUIPluginSkeleton {
@@ -83,23 +70,23 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
private ZeroConfDeviceModel discoveredDevices = new ZeroConfDeviceModel();
private JTable deviceTable = new JTable(discoveredDevices);
-
+
private final JScrollPane scrollPane = new JScrollPane(deviceTable);
private ZeroConfPreferenceModel preferenceModel;
-
+
private final Map<ServiceInfo, Plugin> serviceInfoToReceiveMap = new HashMap<>();
private JMenu connectToMenu = new JMenu("Connect to");
private JMenuItem helpItem = new JMenuItem(new AbstractAction("Learn more about ZeroConf...",
- ChainsawIcons.ICON_HELP) {
+ ChainsawIcons.ICON_HELP) {
public void actionPerformed(ActionEvent e) {
HelpManager.getInstance()
- .showHelpForClass(ZeroConfPlugin.class);
+ .showHelpForClass(ZeroConfPlugin.class);
}
- });
-
+ });
+
private JMenuItem nothingToConnectTo = new JMenuItem("No devices discovered");
private static final String MULTICAST_APPENDER_SERVICE_NAME = "_log4j_xml_mcast_appender.local.";
private static final String UDP_APPENDER_SERVICE_NAME = "_log4j_xml_udp_appender.local.";
@@ -133,7 +120,7 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
try {
stream.toXML(preferenceModel, new FileWriter(fileLocation));
} catch (Exception e) {
- LOG.error("Failed to save ZeroConfPlugin configuration file",e);
+ LOG.error("Failed to save ZeroConfPlugin configuration file", e);
}
}
@@ -149,7 +136,7 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
deviceTable.addMouseListener(new ConnectorMouseListener());
-
+
JToolBar toolbar = new JToolBar();
SmallButton helpButton = new SmallButton(helpItem.getAction());
helpButton.setText(helpItem.getText());
@@ -157,47 +144,47 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
toolbar.setFloatable(false);
add(toolbar, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
-
+
injectMenu();
-
- ((LoggerRepositoryEx)LogManager.getLoggerRepository()).getPluginRegistry().addPluginListener(new PluginListener() {
+
+ ((LoggerRepositoryEx) LogManager.getLoggerRepository()).getPluginRegistry().addPluginListener(new PluginListener() {
public void pluginStarted(PluginEvent e) {
-
+
}
public void pluginStopped(PluginEvent e) {
Plugin plugin = e.getPlugin();
- synchronized(serviceInfoToReceiveMap) {
- for (Iterator<Map.Entry<ServiceInfo, Plugin>> iter = serviceInfoToReceiveMap.entrySet().iterator(); iter.hasNext();) {
+ synchronized (serviceInfoToReceiveMap) {
+ for (Iterator<Map.Entry<ServiceInfo, Plugin>> iter = serviceInfoToReceiveMap.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry<ServiceInfo, Plugin> entry = iter.next();
- if(entry.getValue() == plugin) {
- iter.remove();
+ if (entry.getValue() == plugin) {
+ iter.remove();
}
}
}
// need to make sure that the menu item tracking this item has it's icon and enabled state updade
discoveredDevices.fireTableDataChanged();
- }});
+ }
+ });
File fileLocation = getPreferenceFileLocation();
XStream stream = new XStream(new DomDriver());
if (fileLocation.exists()) {
try {
this.preferenceModel = (ZeroConfPreferenceModel) stream
- .fromXML(new FileReader(fileLocation));
+ .fromXML(new FileReader(fileLocation));
} catch (Exception e) {
- LOG.error("Failed to load ZeroConfPlugin configuration file",e);
+ LOG.error("Failed to load ZeroConfPlugin configuration file", e);
}
- }else {
+ } else {
this.preferenceModel = new ZeroConfPreferenceModel();
}
discoveredDevices.setZeroConfPreferenceModel(preferenceModel);
discoveredDevices.setZeroConfPluginParent(this);
}
- private void registerServiceListenersForAppenders()
- {
+ private void registerServiceListenersForAppenders() {
Set<String> serviceNames = new HashSet<>();
serviceNames.add(MULTICAST_APPENDER_SERVICE_NAME);
serviceNames.add(SOCKET_APPENDER_SERVICE_NAME);
@@ -210,8 +197,8 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
for (Object serviceName1 : serviceNames) {
String serviceName = serviceName1.toString();
jmDNS.addServiceListener(
- serviceName,
- new ZeroConfServiceListener());
+ serviceName,
+ new ZeroConfServiceListener());
jmDNS.addServiceListener(serviceName, discoveredDevices);
}
@@ -221,31 +208,30 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
/**
* Attempts to find a JFrame container as a parent,and addse a "Connect to" menu
- *
*/
private void injectMenu() {
-
+
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
- if(frame == null) {
+ if (frame == null) {
LOG.info("Could not locate parent JFrame to add menu to");
- }else {
+ } else {
JMenuBar menuBar = frame.getJMenuBar();
- if(menuBar==null ) {
+ if (menuBar == null) {
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
}
insertToLeftOfHelp(menuBar, connectToMenu);
connectToMenu.add(nothingToConnectTo);
-
+
discoveredDevices.addTableModelListener(e -> {
- if(discoveredDevices.getRowCount()==0) {
- connectToMenu.add(nothingToConnectTo,0);
- }else if(discoveredDevices.getRowCount()>0) {
+ if (discoveredDevices.getRowCount() == 0) {
+ connectToMenu.add(nothingToConnectTo, 0);
+ } else if (discoveredDevices.getRowCount() > 0) {
connectToMenu.remove(nothingToConnectTo);
}
});
-
+
nothingToConnectTo.setEnabled(false);
connectToMenu.addSeparator();
@@ -256,14 +242,15 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
/**
* Hack method to locate the JMenu that is the Help menu, and inserts the new menu
* just to the left of it.
+ *
* @param menuBar
* @param item
*/
private void insertToLeftOfHelp(JMenuBar menuBar, JMenu item) {
for (int i = 0; i < menuBar.getMenuCount(); i++) {
JMenu menu = menuBar.getMenu(i);
- if(menu.getText().equalsIgnoreCase("help")) {
- menuBar.add(item, i-1);
+ if (menu.getText().equalsIgnoreCase("help")) {
+ menuBar.add(item, i - 1);
}
}
LOG.warn("menu '" + item.getText() + "' was NOT added because the 'Help' menu could not be located");
@@ -273,21 +260,23 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
* When a device is discovered, we create a menu item for it so it can be connected to via that
* GUI mechanism, and also if the device is one of the auto-connect devices then a background thread
* is created to connect the device.
+ *
* @param info
*/
private void deviceDiscovered(final ServiceInfo info) {
final String name = info.getName();
// TODO currently adding ALL devices to autoConnectlist
// preferenceModel.addAutoConnectDevice(name);
-
-
+
+
JMenuItem connectToDeviceMenuItem = new JMenuItem(new AbstractAction(info.getName()) {
public void actionPerformed(ActionEvent e) {
connectTo(info);
- }});
-
- if(discoveredDevices.getRowCount()>0) {
+ }
+ });
+
+ if (discoveredDevices.getRowCount() > 0) {
Component[] menuComponents = connectToMenu.getMenuComponents();
boolean located = false;
for (int i = 0; i < menuComponents.length; i++) {
@@ -301,11 +290,11 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
}
}
}
- if(!located) {
- connectToMenu.insert(connectToDeviceMenuItem,0);
+ if (!located) {
+ connectToMenu.insert(connectToDeviceMenuItem, 0);
}
- }else {
- connectToMenu.insert(connectToDeviceMenuItem,0);
+ } else {
+ connectToMenu.insert(connectToDeviceMenuItem, 0);
}
// if the device name is one of the autoconnect devices, then connect immediately
if (preferenceModel != null && preferenceModel.getAutoConnectDevices() != null && preferenceModel.getAutoConnectDevices().contains(name)) {
@@ -315,9 +304,10 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
}).start();
}
}
-
+
/**
* When a device is removed or disappears we need to remove any JMenu item associated with it.
+ *
* @param name
*/
private void deviceRemoved(String name) {
@@ -332,11 +322,10 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
}
}
}
-
+
/**
* Listens out on the JmDNS/ZeroConf network for new devices that appear
* and adds/removes these device information from the list/model.
- *
*/
private class ZeroConfServiceListener implements ServiceListener {
@@ -348,9 +337,9 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
* thread, so I'm thinking it probably should be a background thread
*/
Runnable runnable = () -> ZeroConfPlugin.this.jmDNS.requestServiceInfo(event
- .getType(), event.getName());
+ .getType(), event.getName());
Thread thread = new Thread(runnable,
- "ChainsawZeroConfRequestResolutionThread");
+ "ChainsawZeroConfRequestResolutionThread");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
@@ -377,11 +366,11 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = deviceTable.rowAtPoint(e.getPoint());
- if(deviceTable.columnAtPoint(e.getPoint())==2) {
+ if (deviceTable.columnAtPoint(e.getPoint()) == 2) {
return;
}
ServiceInfo info = discoveredDevices.getServiceInfoAtRow(row);
-
+
if (!isConnectedTo(info)) {
connectTo(info);
} else {
@@ -417,31 +406,35 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
}
private void disconnectFrom(ServiceInfo info) {
- if(!isConnectedTo(info)) {
+ if (!isConnectedTo(info)) {
return; // not connected, who cares
}
Plugin plugin;
synchronized (serviceInfoToReceiveMap) {
plugin = serviceInfoToReceiveMap.get(info);
}
- ((LoggerRepositoryEx)LogManager.getLoggerRepository()).getPluginRegistry().stopPlugin(plugin.getName());
-
+ ((LoggerRepositoryEx) LogManager.getLoggerRepository()).getPluginRegistry().stopPlugin(plugin.getName());
+
JMenuItem item = locateMatchingMenuItem(info.getName());
- if (item!=null) {
+ if (item != null) {
item.setIcon(null);
item.setEnabled(true);
}
}
+
/**
* returns true if the serviceInfo record already has a matching connected receiver
+ *
* @param info
* @return
*/
boolean isConnectedTo(ServiceInfo info) {
return serviceInfoToReceiveMap.containsKey(info);
}
+
/**
* Starts a receiver to the appender referenced within the ServiceInfo
+ *
* @param info
*/
private void connectTo(ServiceInfo info) {
@@ -452,18 +445,18 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
if (receiver == null) {
return;
}
- ((LoggerRepositoryEx)LogManager.getLoggerRepository()).getPluginRegistry().addPlugin(receiver);
+ ((LoggerRepositoryEx) LogManager.getLoggerRepository()).getPluginRegistry().addPlugin(receiver);
receiver.activateOptions();
LOG.info("Receiver '" + receiver.getName() + "' has been started");
-
+
// ServiceInfo obeys equals() and hashCode() contracts, so this should be safe.
synchronized (serviceInfoToReceiveMap) {
serviceInfoToReceiveMap.put(info, receiver);
}
-
+
// this instance of the menu item needs to be disabled, and have an icon added
JMenuItem item = locateMatchingMenuItem(info.getName());
- if (item!=null) {
+ if (item != null) {
item.setIcon(new ImageIcon(ChainsawIcons.ANIM_NET_CONNECT));
item.setEnabled(false);
}
@@ -478,8 +471,7 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
String name = info.getName();
String decoderClass = info.getPropertyString("decoder");
- if (NEW_UDP_APPENDER_SERVICE_NAME.equals(zone))
- {
+ if (NEW_UDP_APPENDER_SERVICE_NAME.equals(zone)) {
UDPReceiver receiver = new UDPReceiver();
receiver.setPort(port);
receiver.setName(name + "-receiver");
@@ -493,16 +485,14 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
//text/plain = VFSLogFilePatternReceiver (if structured=false)
String contentType = info.getPropertyString("contentType").toLowerCase();
//won't work with log4j2, as Chainsaw depends on log4j1.x
- if ("application/octet-stream".equals(contentType))
- {
+ if ("application/octet-stream".equals(contentType)) {
SocketReceiver receiver = new SocketReceiver();
receiver.setPort(port);
receiver.setName(name + "-receiver");
return receiver;
}
//this will work - regular text log files are fine
- if ("text/plain".equals(contentType))
- {
+ if ("text/plain".equals(contentType)) {
VFSLogFilePatternReceiver receiver = new VFSLogFilePatternReceiver();
receiver.setAppendNonMatches(true);
receiver.setFileURL(info.getPropertyString("fileURI"));
@@ -572,7 +562,7 @@ public class ZeroConfPlugin extends GUIPluginSkeleton {
/**
* Finds the matching JMenuItem based on name, may return null if there is no match.
- *
+ *
* @param name
* @return
*/
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPreferenceModel.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPreferenceModel.java b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPreferenceModel.java
index 4b31690..53b35a5 100644
--- a/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPreferenceModel.java
+++ b/src/main/java/org/apache/log4j/chainsaw/zeroconf/ZeroConfPreferenceModel.java
@@ -25,14 +25,14 @@ public class ZeroConfPreferenceModel {
private List<String> monitoredZones = new ArrayList<>();
private Set<String> autoConnectDevices = new HashSet<>();
-
+
// TODO expose addPropertyChangeListener
-
+
public void addAutoConnectDevice(String deviceName) {
// TODO fire property changes
autoConnectDevices.add(deviceName);
}
-
+
public void addMonitoredZone(String zone) {
// TODO fire property change events
monitoredZones.add(zone);
@@ -57,6 +57,6 @@ public class ZeroConfPreferenceModel {
public void removeAutoConnectDevice(String device) {
autoConnectDevices.remove(device);
}
-
-
+
+
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/db/ConnectionSource.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/db/ConnectionSource.java b/src/main/java/org/apache/log4j/db/ConnectionSource.java
index 12c3495..dbee20e 100644
--- a/src/main/java/org/apache/log4j/db/ConnectionSource.java
+++ b/src/main/java/org/apache/log4j/db/ConnectionSource.java
@@ -5,9 +5,9 @@
* The ASF licenses this file to You 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.
@@ -25,45 +25,46 @@ import java.sql.SQLException;
/**
- * The {@code ConnectionSource} interface provides a pluggable means of
- * transparently obtaining JDBC {@link java.sql.Connection}s for log4j classes
- * that require the use of a {@link java.sql.Connection}.
+ * The {@code ConnectionSource} interface provides a pluggable means of
+ * transparently obtaining JDBC {@link java.sql.Connection}s for log4j classes
+ * that require the use of a {@link java.sql.Connection}.
*
- * @author <a href="mailto:rdecampo@twcny.rr.com">Ray DeCampo</a>
+ * @author <a href="mailto:rdecampo@twcny.rr.com">Ray DeCampo</a>
*/
public interface ConnectionSource extends Component, OptionHandler {
- int UNKNOWN_DIALECT = 0;
- int POSTGRES_DIALECT = 1;
- int MYSQL_DIALECT = 2;
- int ORACLE_DIALECT = 3;
- int MSSQL_DIALECT = 4;
- int HSQL_DIALECT = 5;
- /**
- * Obtain a {@link java.sql.Connection} for use. The client is
- * responsible for closing the {@link java.sql.Connection} when it is no
- * longer required.
- *
- * @throws SQLException if a {@link java.sql.Connection} could not be
- * obtained
- */
- Connection getConnection() throws SQLException;
+ int UNKNOWN_DIALECT = 0;
+ int POSTGRES_DIALECT = 1;
+ int MYSQL_DIALECT = 2;
+ int ORACLE_DIALECT = 3;
+ int MSSQL_DIALECT = 4;
+ int HSQL_DIALECT = 5;
+
+ /**
+ * Obtain a {@link java.sql.Connection} for use. The client is
+ * responsible for closing the {@link java.sql.Connection} when it is no
+ * longer required.
+ *
+ * @throws SQLException if a {@link java.sql.Connection} could not be
+ * obtained
+ */
+ Connection getConnection() throws SQLException;
+
+ /**
+ * Get the SQL dialect that should be used for this connection. Note that the
+ * dialect is not needed if the JDBC driver supports the getGeneratedKeys
+ * method.
+ */
+ int getSQLDialectCode();
+
+ /**
+ * If the connection supports the JDBC 3.0 getGeneratedKeys method, then
+ * we do not need any specific dialect support.
+ */
+ boolean supportsGetGeneratedKeys();
- /**
- * Get the SQL dialect that should be used for this connection. Note that the
- * dialect is not needed if the JDBC driver supports the getGeneratedKeys
- * method.
- */
- int getSQLDialectCode();
-
- /**
- * If the connection supports the JDBC 3.0 getGeneratedKeys method, then
- * we do not need any specific dialect support.
- */
- boolean supportsGetGeneratedKeys();
-
- /**
- * If the connection does not support batch updates, we will avoid using them.
- */
- boolean supportsBatchUpdates();
+ /**
+ * If the connection does not support batch updates, we will avoid using them.
+ */
+ boolean supportsBatchUpdates();
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/db/ConnectionSourceSkeleton.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/db/ConnectionSourceSkeleton.java b/src/main/java/org/apache/log4j/db/ConnectionSourceSkeleton.java
index 943075c..5d184d8 100644
--- a/src/main/java/org/apache/log4j/db/ConnectionSourceSkeleton.java
+++ b/src/main/java/org/apache/log4j/db/ConnectionSourceSkeleton.java
@@ -17,133 +17,133 @@
package org.apache.log4j.db;
+import org.apache.log4j.db.dialect.Util;
+import org.apache.log4j.spi.ComponentBase;
+
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
-import org.apache.log4j.db.dialect.Util;
-import org.apache.log4j.spi.ComponentBase;
-
/**
* @author Ceki Gülcü
*/
public abstract class ConnectionSourceSkeleton extends ComponentBase implements ConnectionSource {
-
- private Boolean overriddenSupportsGetGeneratedKeys = null;
-
- private String user = null;
- private String password = null;
-
- // initially we have an unkonw dialect
- private int dialectCode = UNKNOWN_DIALECT;
- private boolean supportsGetGeneratedKeys = false;
- private boolean supportsBatchUpdates = false;
-
-
- /**
- * Learn relevant information about this connection source.
- *
- */
- public void discoverConnnectionProperties() {
- Connection connection = null;
- try {
- connection = getConnection();
- if (connection == null) {
- getLogger().warn("Could not get a conneciton");
- return;
- }
- DatabaseMetaData meta = connection.getMetaData();
- Util util = new Util();
- util.setLoggerRepository(repository);
- if (overriddenSupportsGetGeneratedKeys != null) {
- supportsGetGeneratedKeys = overriddenSupportsGetGeneratedKeys;
- } else {
- supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta);
- }
- supportsBatchUpdates = util.supportsBatchUpdates(meta);
- dialectCode = Util.discoverSQLDialect(meta);
- } catch (SQLException se) {
- getLogger().warn("Could not discover the dialect to use.", se);
- } finally {
- DBHelper.closeConnection(connection);
+
+ private Boolean overriddenSupportsGetGeneratedKeys = null;
+
+ private String user = null;
+ private String password = null;
+
+ // initially we have an unkonw dialect
+ private int dialectCode = UNKNOWN_DIALECT;
+ private boolean supportsGetGeneratedKeys = false;
+ private boolean supportsBatchUpdates = false;
+
+
+ /**
+ * Learn relevant information about this connection source.
+ */
+ public void discoverConnnectionProperties() {
+ Connection connection = null;
+ try {
+ connection = getConnection();
+ if (connection == null) {
+ getLogger().warn("Could not get a conneciton");
+ return;
+ }
+ DatabaseMetaData meta = connection.getMetaData();
+ Util util = new Util();
+ util.setLoggerRepository(repository);
+ if (overriddenSupportsGetGeneratedKeys != null) {
+ supportsGetGeneratedKeys = overriddenSupportsGetGeneratedKeys;
+ } else {
+ supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta);
+ }
+ supportsBatchUpdates = util.supportsBatchUpdates(meta);
+ dialectCode = Util.discoverSQLDialect(meta);
+ } catch (SQLException se) {
+ getLogger().warn("Could not discover the dialect to use.", se);
+ } finally {
+ DBHelper.closeConnection(connection);
+ }
+ }
+
+ /**
+ * Does this connection support the JDBC Connection.getGeneratedKeys method?
+ */
+ public final boolean supportsGetGeneratedKeys() {
+ return supportsGetGeneratedKeys;
+ }
+
+ public final int getSQLDialectCode() {
+ return dialectCode;
+ }
+
+ /**
+ * Get the password for this connection source.
+ */
+ public final String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the password.
+ *
+ * @param password The password to set
+ */
+ public final void setPassword(final String password) {
+ this.password = password;
+ }
+
+ /**
+ * Get the user for this connection source.
+ */
+ public final String getUser() {
+ return user;
+ }
+
+ /**
+ * Sets the username.
+ *
+ * @param username The username to set
+ */
+ public final void setUser(final String username) {
+ this.user = username;
+ }
+
+ /**
+ * Returns the "overridden" value of "supportsGetGeneratedKeys" property of
+ * the JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys
+ * does not work because it returns the ROWID, not the value of the sequence.
+ *
+ * @return A non null string, with "true" or "false" value, if overridden,
+ * <code>null</code> if not overridden.
+ */
+ public String getOverriddenSupportsGetGeneratedKeys() {
+ return overriddenSupportsGetGeneratedKeys != null ? overriddenSupportsGetGeneratedKeys
+ .toString()
+ : null;
+ }
+
+ /**
+ * Sets the "overridden" value of "supportsGetGeneratedKeys" property of the
+ * JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys
+ * does not work because it returns the ROWID, not the value of the sequence.
+ *
+ * @param overriddenSupportsGetGeneratedKeys A non null string, with "true" or "false" value, if overridden,
+ * <code>null</code> if not overridden.
+ */
+ public void setOverriddenSupportsGetGeneratedKeys(
+ String overriddenSupportsGetGeneratedKeys) {
+ this.overriddenSupportsGetGeneratedKeys = Boolean
+ .valueOf(overriddenSupportsGetGeneratedKeys);
+ }
+
+ /**
+ * Does this connection support batch updates?
+ */
+ public final boolean supportsBatchUpdates() {
+ return supportsBatchUpdates;
}
- }
-
- /**
- * Does this connection support the JDBC Connection.getGeneratedKeys method?
- */
- public final boolean supportsGetGeneratedKeys() {
- return supportsGetGeneratedKeys;
- }
-
- public final int getSQLDialectCode() {
- return dialectCode;
- }
-
- /**
- * Get the password for this connection source.
- */
- public final String getPassword() {
- return password;
- }
-
- /**
- * Sets the password.
- * @param password The password to set
- */
- public final void setPassword(final String password) {
- this.password = password;
- }
-
- /**
- * Get the user for this connection source.
- */
- public final String getUser() {
- return user;
- }
-
- /**
- * Sets the username.
- * @param username The username to set
- */
- public final void setUser(final String username) {
- this.user = username;
- }
-
- /**
- * Returns the "overridden" value of "supportsGetGeneratedKeys" property of
- * the JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys
- * does not work because it returns the ROWID, not the value of the sequence.
- *
- * @return A non null string, with "true" or "false" value, if overridden,
- * <code>null</code> if not overridden.
- */
- public String getOverriddenSupportsGetGeneratedKeys() {
- return overriddenSupportsGetGeneratedKeys != null ? overriddenSupportsGetGeneratedKeys
- .toString()
- : null;
- }
-
- /**
- * Sets the "overridden" value of "supportsGetGeneratedKeys" property of the
- * JDBC driver. In certain cases, getting (e.g. Oracle 10g) generated keys
- * does not work because it returns the ROWID, not the value of the sequence.
- *
- * @param overriddenSupportsGetGeneratedKeys
- * A non null string, with "true" or "false" value, if overridden,
- * <code>null</code> if not overridden.
- */
- public void setOverriddenSupportsGetGeneratedKeys(
- String overriddenSupportsGetGeneratedKeys) {
- this.overriddenSupportsGetGeneratedKeys = Boolean
- .valueOf(overriddenSupportsGetGeneratedKeys);
- }
-
- /**
- * Does this connection support batch updates?
- */
- public final boolean supportsBatchUpdates() {
- return supportsBatchUpdates;
- }
}
http://git-wip-us.apache.org/repos/asf/logging-chainsaw/blob/96ebd9ad/src/main/java/org/apache/log4j/db/CustomSQLDBReceiver.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/log4j/db/CustomSQLDBReceiver.java b/src/main/java/org/apache/log4j/db/CustomSQLDBReceiver.java
index dc7fcce..47ad2ab 100644
--- a/src/main/java/org/apache/log4j/db/CustomSQLDBReceiver.java
+++ b/src/main/java/org/apache/log4j/db/CustomSQLDBReceiver.java
@@ -5,9 +5,9 @@
* The ASF licenses this file to You 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.
@@ -17,14 +17,6 @@
package org.apache.log4j.db;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Hashtable;
-import java.util.Properties;
-import java.util.StringTokenizer;
-
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.plugins.Pauseable;
@@ -39,10 +31,18 @@ import org.apache.log4j.xml.DOMConfigurator;
import org.apache.log4j.xml.UnrecognizedElementHandler;
import org.w3c.dom.Element;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Hashtable;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
/**
* Converts log data stored in a database into LoggingEvents.
* <p>
- * <b>NOTE:</b> This receiver cannot yet be created through Chainsaw's receiver panel.
+ * <b>NOTE:</b> This receiver cannot yet be created through Chainsaw's receiver panel.
* It must be created through an XML configuration file.
* <p>
* This receiver supports database configuration via ConnectionSource, in the
@@ -58,7 +58,7 @@ import org.w3c.dom.Element;
* other numeric value, the SQL will be executed on a recurring basis every
* 'refreshMillis' milliseconds.
* <p>
- * The receiver closes the connection and acquires a new connection on each
+ * The receiver closes the connection and acquires a new connection on each
* execution of the SQL (use pooled connections if possible).
* <p>
* If the SQL will be executing on a recurring basis, specify the IDField param -
@@ -128,6 +128,7 @@ import org.w3c.dom.Element;
* concat("{{application,databaselogs,hostname,mymachine, log4jid,",
* COUNTER,"}}") as PROPERTIES, "" as THROWABLE from logtable
* <p>
+ *
* @author Scott Deboy <sdeboy@apache.org>
* <p>
*/
@@ -139,7 +140,7 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
/**
* By default we refresh data every 1000 milliseconds.
- *
+ *
* @see #setRefreshMillis
*/
static int DEFAULT_REFRESH_MILLIS = 1000;
@@ -165,28 +166,27 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
private Job customReceiverJob;
public void activateOptions() {
-
- if(connectionSource == null) {
- throw new IllegalStateException(
- "CustomSQLDBReceiver cannot function without a connection source");
- }
- whereExists = (sqlStatement.toUpperCase().contains(WHERE_CLAUSE));
-
- customReceiverJob = new CustomReceiverJob();
-
- if(this.repository == null) {
- throw new IllegalStateException(
- "CustomSQLDBReceiver cannot function without a reference to its owning repository");
- }
-
-
-
- if (repository instanceof LoggerRepositoryEx) {
- Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler();
-
- scheduler.schedule(
- customReceiverJob, System.currentTimeMillis() + 500, refreshMillis);
- }
+
+ if (connectionSource == null) {
+ throw new IllegalStateException(
+ "CustomSQLDBReceiver cannot function without a connection source");
+ }
+ whereExists = (sqlStatement.toUpperCase().contains(WHERE_CLAUSE));
+
+ customReceiverJob = new CustomReceiverJob();
+
+ if (this.repository == null) {
+ throw new IllegalStateException(
+ "CustomSQLDBReceiver cannot function without a reference to its owning repository");
+ }
+
+
+ if (repository instanceof LoggerRepositoryEx) {
+ Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler();
+
+ scheduler.schedule(
+ customReceiverJob, System.currentTimeMillis() + 500, refreshMillis);
+ }
}
@@ -217,8 +217,7 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
}
/**
- * @param connectionSource
- * The connectionSource to set.
+ * @param connectionSource The connectionSource to set.
*/
public void setConnectionSource(ConnectionSource connectionSource) {
this.connectionSource = connectionSource;
@@ -243,15 +242,15 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
/*
* (non-Javadoc)
- *
+ *
* @see org.apache.log4j.plugins.Plugin#shutdown()
*/
public void shutdown() {
getLogger().info("removing receiverJob from the Scheduler.");
- if(this.repository instanceof LoggerRepositoryEx) {
- Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler();
- scheduler.delete(customReceiverJob);
+ if (this.repository instanceof LoggerRepositoryEx) {
+ Scheduler scheduler = ((LoggerRepositoryEx) repository).getScheduler();
+ scheduler.delete(customReceiverJob);
}
lastID = -1;
@@ -305,10 +304,10 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
String currentSQLStatement;
if (whereExists) {
currentSQLStatement = sqlStatement + AND_CLAUSE + idField
- + " > " + lastID;
+ + " > " + lastID;
} else {
currentSQLStatement = sqlStatement + WHERE_CLAUSE + idField
- + " > " + lastID;
+ + " > " + lastID;
}
ResultSet rs = statement.executeQuery(currentSQLStatement);
@@ -342,21 +341,21 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
// or
// just name, value
if ((mdcString.contains("{{"))
- && (mdcString.contains("}}"))) {
+ && (mdcString.contains("}}"))) {
mdcString = mdcString
- .substring(mdcString.indexOf("{{") + 2,
- mdcString.indexOf("}}"));
+ .substring(mdcString.indexOf("{{") + 2,
+ mdcString.indexOf("}}"));
}
StringTokenizer tok = new StringTokenizer(mdcString,
- ",");
+ ",");
while (tok.countTokens() > 1) {
mdc.put(tok.nextToken(), tok.nextToken());
}
}
- throwable = new String[] { rs.getString("THROWABLE") };
+ throwable = new String[]{rs.getString("THROWABLE")};
className = rs.getString("CLASS");
methodName = rs.getString("METHOD");
fileName = rs.getString("FILE");
@@ -375,14 +374,14 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
// support properties being wrapped in {{name,
// value}} or just name, value
if ((propertiesString.contains("{{"))
- && (propertiesString.contains("}}"))) {
+ && (propertiesString.contains("}}"))) {
propertiesString = propertiesString.substring(
- propertiesString.indexOf("{{") + 2,
- propertiesString.indexOf("}}"));
+ propertiesString.indexOf("{{") + 2,
+ propertiesString.indexOf("}}"));
}
StringTokenizer tok2 = new StringTokenizer(
- propertiesString, ",");
+ propertiesString, ",");
while (tok2.countTokens() > 1) {
String tokenName = tok2.nextToken();
String value = tok2.nextToken();
@@ -403,21 +402,21 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
Level levelImpl = Level.toLevel(level);
- LocationInfo locationInfo = new LocationInfo(fileName,
- className, methodName, lineNumber);
-
- ThrowableInformation throwableInfo = new ThrowableInformation(
- throwable);
-
- properties.putAll(mdc);
-
- LoggingEvent event = new LoggingEvent(eventLogger.getName(),
- eventLogger, timeStamp, levelImpl, message,
- threadName,
- throwableInfo,
- ndc,
- locationInfo,
- properties);
+ LocationInfo locationInfo = new LocationInfo(fileName,
+ className, methodName, lineNumber);
+
+ ThrowableInformation throwableInfo = new ThrowableInformation(
+ throwable);
+
+ properties.putAll(mdc);
+
+ LoggingEvent event = new LoggingEvent(eventLogger.getName(),
+ eventLogger, timeStamp, levelImpl, message,
+ threadName,
+ throwableInfo,
+ ndc,
+ locationInfo,
+ properties);
doPost(event);
}
@@ -429,7 +428,7 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
statement.close();
} catch (SQLException sqle) {
getLogger()
- .error("*************Problem receiving events", sqle);
+ .error("*************Problem receiving events", sqle);
} finally {
closeConnection();
}
@@ -449,18 +448,18 @@ public class CustomSQLDBReceiver extends Receiver implements Pauseable, Unrecogn
/**
* {@inheritDoc}
*/
- public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception {
+ public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception {
if ("connectionSource".equals(element.getNodeName())) {
Object instance =
- DOMConfigurator.parseElement(element, props, ConnectionSource.class);
+ DOMConfigurator.parseElement(element, props, ConnectionSource.class);
if (instance instanceof ConnectionSource) {
- ConnectionSource source = (ConnectionSource) instance;
- source.activateOptions();
- setConnectionSource(source);
+ ConnectionSource source = (ConnectionSource) instance;
+ source.activateOptions();
+ setConnectionSource(source);
}
return true;
}
return false;
- }
-
+ }
+
}