From ff2e4c957bac866acacab608a4e9c7087acaf291 Mon Sep 17 00:00:00 2001 From: Zorglube Date: Fri, 29 Oct 2021 16:56:41 +0200 Subject: [PATCH] Move project to JDK 11, first commit Signed-off-by: Zorglube --- audit-client/pom.xml | 100 ++- .../logback/audit/client/AuditAppender.java | 42 +- .../audit/client/AuditAppenderBase.java | 121 +-- .../logback/audit/client/AuditConstants.java | 24 +- .../ch/qos/logback/audit/client/Auditor.java | 80 +- .../logback/audit/client/AuditorFacade.java | 137 ++-- .../logback/audit/client/AuditorFactory.java | 280 ++++--- .../qos/logback/audit/client/AuditorImpl.java | 76 +- .../audit/client/ListAuditAppender.java | 52 +- .../audit/client/NOPAuditAppender.java | 31 +- .../audit/client/SLF4JAuditAppender.java | 57 +- .../audit/client/joran/JoranConfigurator.java | 45 +- .../joran/action/AuditAppenderAction.java | 137 ++-- .../client/joran/action/AuditorAction.java | 70 +- .../logback/audit/client/net/Connector.java | 110 ++- .../audit/client/net/SocketAuditAppender.java | 463 ++++++----- audit-common/pom.xml | 88 +- .../ch/qos/logback/audit/Application.java | 134 ++- .../java/ch/qos/logback/audit/AuditEvent.java | 338 ++++---- .../qos/logback/audit/AuditEventBuilder.java | 36 +- .../logback/audit/AuditEventBuilderImpl.java | 105 +-- .../ch/qos/logback/audit/AuditException.java | 24 +- .../logback/audit/InternalAuditContants.java | 8 +- .../java/ch/qos/logback/audit/Predicate.java | 32 +- audit-examples/pom.xml | 69 +- .../src/main/java/examples/BabyStep.java | 22 +- .../src/main/java/examples/SecondStep.java | 22 +- .../java/examples/access/AccessException.java | 20 +- .../access/AccessRightsAdministrator.java | 194 +++-- .../examples/access/AccessRightsChecker.java | 146 ++-- .../java/examples/access/AuditHelper.java | 25 +- .../main/java/examples/access/Permission.java | 74 +- .../java/examples/access/PermissionMap.java | 39 +- .../src/main/java/examples/access/User.java | 27 +- audit-server-generator/pom.xml | 86 +- audit-server/pom.xml | 35 +- .../audit/persistent/AuditEventDAO.java | 160 ++-- .../audit/persistent/AuditEventShaper.java | 20 +- .../audit/persistent/NullAEShaper.java | 13 +- .../logback/audit/persistent/Persistor.java | 386 +++++---- .../audit/persistent/SQLServerAEShaper.java | 79 +- .../audit/server/AuditEventHandler.java | 17 +- .../audit/server/AuditEventHandlerBase.java | 41 +- .../audit/server/AuditEventPersistor.java | 31 +- .../logback/audit/server/AuditListener.java | 10 +- .../qos/logback/audit/server/AuditServer.java | 176 ++-- .../audit/server/AuditServerConstants.java | 40 +- .../audit/server/ServletContextListener.java | 92 +-- .../qos/logback/audit/server/SocketNode.java | 205 +++-- .../logback/audit/server/TableCreator.java | 66 +- .../audit/server/helper/ResourceUtil.java | 80 +- audit-site/pom.xml | 112 +-- pom.xml | 764 +++++++++--------- 53 files changed, 2757 insertions(+), 2884 deletions(-) diff --git a/audit-client/pom.xml b/audit-client/pom.xml index 23a2dba..8af79f1 100644 --- a/audit-client/pom.xml +++ b/audit-client/pom.xml @@ -1,66 +1,64 @@ + + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + ch.qos.logback + audit-parent + 0.7-SNAPSHOT + - - ch.qos.logback - audit-parent - 0.6 - + 4.0.0 - 4.0.0 + audit-client + jar + Logback Audit Client - ch.qos.logback - audit-client - jar - Logback Audit Client + + + ch.qos.logback + audit-common + - - - ch.qos.logback - audit-common - + + ch.qos.logback + logback-core + - - ch.qos.logback - logback-core - + + org.slf4j + slf4j-api + - - org.slf4j - slf4j-api - + + org.slf4j + slf4j-simple + test + - - org.slf4j - slf4j-simple - test - + - + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/*AllTest.java + **/PackageTest.java + **/SizeBasedRollingTest.java + + + + - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/*AllTest.java - **/PackageTest.java - **/SizeBasedRollingTest.java - - - - - - + \ No newline at end of file diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppender.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppender.java index 3bbc414..08fe0dc 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppender.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppender.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -21,24 +21,24 @@ public interface AuditAppender extends ContextAware, LifeCycle { - /** - * Get the name of this appender. The name uniquely identifies the appender. - */ - public String getName(); + /** + * Get the name of this appender. The name uniquely identifies the appender. + */ + String getName(); - /** - * Set the name of this appender. The name is used by other components to - * identify this appender. - * - */ - public void setName(String name); - - /** - * This is where an appender accomplishes its work. Note that the argument - * is of type Object. - * @param event - */ - void doAppend(AuditEvent event) throws AuditException; + /** + * Set the name of this appender. The name is used by other components to + * identify this appender. + * + */ + void setName(String name); + + /** + * This is where an appender accomplishes its work. Note that the argument is of + * type Object. + * + * @param event + */ + void doAppend(AuditEvent event) throws AuditException; - } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppenderBase.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppenderBase.java index 6db9587..b20eed7 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppenderBase.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditAppenderBase.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,61 +18,62 @@ import ch.qos.logback.audit.AuditException; import ch.qos.logback.core.spi.ContextAwareBase; -abstract public class AuditAppenderBase extends ContextAwareBase implements - AuditAppender { - - protected boolean started = false; - - //static final int NOT_STARTED_ERROR_COUNT_LIMIT = 5; - //int notStartedErrorCount = 0; - - - /** - * Appenders are named. - */ - protected String name; - - public synchronized void doAppend(AuditEvent auditEvent) - throws AuditException { - - try { - - if (!this.started) { - throw new AuditException( - "Attempted to append to non started appender [" + name + "]."); - } - - // ok, we now invoke derived class' implementation of append - this.append(auditEvent); - - } catch (Exception e) { - if (e instanceof AuditException) { - throw (AuditException) e; - } else { - throw new AuditException("Failed to audit an event", e); - } - } - } - - abstract protected void append(AuditEvent auditEvent) throws AuditException; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public void start() { - started = true; - } - - public void stop() { - started = false; - } - - public boolean isStarted() { - return started; - } +abstract public class AuditAppenderBase extends ContextAwareBase implements AuditAppender { + + protected boolean started = false; + + // static final int NOT_STARTED_ERROR_COUNT_LIMIT = 5; + // int notStartedErrorCount = 0; + + /** + * Appenders are named. + */ + protected String name; + + @Override + public synchronized void doAppend(final AuditEvent auditEvent) throws AuditException { + + try { + + if (!started) { + throw new AuditException("Attempted to append to non started appender [" + name + "]."); + } + + // ok, we now invoke derived class' implementation of append + append(auditEvent); + + } catch (final Exception e) { + if (e instanceof AuditException) { + throw (AuditException) e; + } + throw new AuditException("Failed to audit an event", e); + } + } + + abstract protected void append(AuditEvent auditEvent) throws AuditException; + + @Override + public String getName() { + return name; + } + + @Override + public void setName(final String name) { + this.name = name; + } + + @Override + public void start() { + started = true; + } + + @Override + public void stop() { + started = false; + } + + @Override + public boolean isStarted() { + return started; + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditConstants.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditConstants.java index b37b6da..392cd94 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditConstants.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditConstants.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -15,13 +15,13 @@ package ch.qos.logback.audit.client; public interface AuditConstants { - // TYPES - static final String SUBJECT_TYPE = "SUBJECT_TYPE"; - static final String CRUD_TYPE = "CRUD_TYPE"; - - // CRUD_TYPES - static final String CREATE = "CREATE"; - static final String READ = "READ"; - static final String UPDATE = "UPDATE"; - static final String DELETE = "DELETE"; + // TYPES + String SUBJECT_TYPE = "SUBJECT_TYPE"; + String CRUD_TYPE = "CRUD_TYPE"; + + // CRUD_TYPES + String CREATE = "CREATE"; + String READ = "READ"; + String UPDATE = "UPDATE"; + String DELETE = "DELETE"; } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/Auditor.java b/audit-client/src/main/java/ch/qos/logback/audit/client/Auditor.java index 8b1f006..9c36fa9 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/Auditor.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/Auditor.java @@ -1,19 +1,21 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.audit.client; +import java.util.Objects; + import ch.qos.logback.audit.Application; import ch.qos.logback.audit.AuditEvent; import ch.qos.logback.audit.AuditEventBuilder; @@ -23,48 +25,48 @@ public class Auditor extends ContextBase { - AuditAppender auditAppender; - Application clientApplication; + AuditAppender auditAppender; + Application clientApplication; + + public AuditEventBuilder newAuditEventBuilder() { + final AuditEventBuilder ab = new AuditEventBuilderImpl(); + ab.setClientApplication(clientApplication); + return ab; + } - public AuditEventBuilder newAuditEventBuilder() { - AuditEventBuilderImpl ab = new AuditEventBuilderImpl(); - ab.setClientApplication(clientApplication); - return ab; - } + public void log(final AuditEvent auditEvent) throws AuditException { + auditAppender.doAppend(auditEvent); + } - public void log(AuditEvent auditEvent) throws AuditException { - auditAppender.doAppend(auditEvent); - } + public void log(final AuditEventBuilder builder) throws AuditException { + final AuditEvent auditEvent = builder.build(); + auditAppender.doAppend(auditEvent); + } - public void log(AuditEventBuilder builder) throws AuditException { - AuditEvent auditEvent = builder.build(); - auditAppender.doAppend(auditEvent); - } - - public AuditAppender getAuditAppender() { - return auditAppender; - } + public AuditAppender getAuditAppender() { + return auditAppender; + } - public void setAuditAppender(AuditAppender auditAppender) { - this.auditAppender = auditAppender; - } + public void setAuditAppender(final AuditAppender auditAppender) { + this.auditAppender = auditAppender; + } - public void shutdown() { - if (auditAppender != null) { - auditAppender.stop(); - } - auditAppender = null; - } + public void shutdown() { + if (Objects.nonNull(auditAppender)) { + auditAppender.stop(); + } + auditAppender = null; + } - public Application getClientApplication() { - return clientApplication; - } + public Application getClientApplication() { + return clientApplication; + } - public void setClientApplication(Application capp) { - if(this.clientApplication != null) { - throw new IllegalStateException("Client application has been set already."); - } - this.clientApplication = capp; - } + public void setClientApplication(final Application capp) { + if (Objects.nonNull(clientApplication)) { + throw new IllegalStateException("Client application has been set already."); + } + clientApplication = capp; + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFacade.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFacade.java index 4372fe5..e387845 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFacade.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFacade.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -16,6 +16,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,78 +27,74 @@ import ch.qos.logback.audit.Predicate; public class AuditorFacade { - final Logger logger = LoggerFactory.getLogger(AuditorFacade.class); - - final String object; - final String verb; - final String subject; - Application originatingApplication; - Map predicateMap; + final Logger logger = LoggerFactory.getLogger(AuditorFacade.class); - public AuditorFacade(String subject, String verb, String object) { - this.subject = subject; - this.verb = verb; - this.object = object; - } + final String object; + final String verb; + final String subject; + Application originatingApplication; + Map predicateMap; - public void audit() throws AuditException { - Auditor auditor = AuditorFactory.getAuditor(); + public AuditorFacade(final String subject, final String verb, final String object) { + this.subject = subject; + this.verb = verb; + this.object = object; + } - AuditEventBuilder builder = auditor.newAuditEventBuilder(); - builder.setObject(object); - builder.setVerb(verb); - builder.setSubject(subject); - if (predicateMap != null) { - builder.setPredicateMap(predicateMap); - } - if (originatingApplication != null) { - builder.setOriginatingApplication(originatingApplication); - } - auditor.log(builder); - } + public void audit() throws AuditException { + final Auditor auditor = AuditorFactory.getAuditor(); - public AuditorFacade setPredicateMap(Map predicateMap) { - this.predicateMap = predicateMap; - return this; - } + final AuditEventBuilder builder = auditor.newAuditEventBuilder(); + builder.setObject(object); + builder.setVerb(verb); + builder.setSubject(subject); + if (Objects.nonNull(predicateMap)) { + builder.setPredicateMap(predicateMap); + } + if (Objects.nonNull(originatingApplication)) { + builder.setOriginatingApplication(originatingApplication); + } + auditor.log(builder); + } - /** - * Add a predicate. - * - * @param predicate - * @return - */ - public AuditorFacade add(Predicate predicate) { - if (predicate == null) { - throw new IllegalArgumentException( - "The predicate parameter cannot be null"); - } - return add(predicate.getName(), predicate.getValue()); - } + public AuditorFacade setPredicateMap(final Map predicateMap) { + this.predicateMap = predicateMap; + return this; + } - /** - * Add a predicate through two parameters, key and value. - * - * @param key - * @param value - * @return - */ - public AuditorFacade add(String key, String value) { - if (predicateMap == null) { - predicateMap = new HashMap(); - } - predicateMap.put(key, value); - return this; - } + /** + * Add a predicate. + * + * @param predicate + * @return + */ + public AuditorFacade add(final Predicate predicate) { + if (Objects.isNull(predicate)) { + throw new IllegalArgumentException("The predicate parameter cannot be null"); + } + return add(predicate.getName(), predicate.getValue()); + } - /** - * Set the originating application name. - * - * @param originatingApplication - * @return - */ - public AuditorFacade originating(Application originatingApplication) { - this.originatingApplication = originatingApplication; - return this; - } + /** + * Add a predicate through two parameters, key and value. + * + * @param key + * @param value + * @return + */ + public AuditorFacade add(final String key, final String value) { + Objects.>requireNonNullElse(predicateMap, new HashMap<>()).put(key, value); + return this; + } + + /** + * Set the originating application name. + * + * @param originatingApplication + * @return + */ + public AuditorFacade originating(final Application originatingApplication) { + this.originatingApplication = originatingApplication; + return this; + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFactory.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFactory.java index 54381d1..1169e25 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFactory.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorFactory.java @@ -1,19 +1,22 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.audit.client; +import static java.util.Objects.isNull; +import static java.util.Objects.nonNull; + import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; @@ -31,147 +34,134 @@ public class AuditorFactory { - static final String DEFAULT_AUDITOR_NAME = "default"; - static final String AUTOCONFIG_FILE = "logback-audit.xml"; - static final String TEST_AUTOCONFIG_FILE = "logback-audit-test.xml"; - - static final public String AUTOCONFIG_FILE_PROPERTY = "logback.audit.autoconfig.file"; - - static final public String NULL_CLIENT_APPLICATON_URL = "http://audit.qos.ch/codes.html#nullClientApp"; - static final public String NULL_AUDIT_APPENDER_URL = "http://audit.qos.ch/codes.html#nullAuditAppender"; - - static Auditor defaultAuditor; - - static Application clientApplication; - - static void checkSanity(Auditor auditor) throws AuditException { - StatusManager sm = auditor.getStatusManager(); - StatusChecker checker = new StatusChecker(sm); - if (checker.getHighestLevel(0) > Status.INFO) { - StatusPrinter.print(sm); - } - - if (auditor.getClientApplication() == null) { - throw new AuditException("Client application has not been set"); - } - - if (auditor.getAuditAppender() == null) { - throw new AuditException("No audit appender. Please see " - + NULL_AUDIT_APPENDER_URL); - } - } - - public static void setApplicationName(String name) throws AuditException { - if(clientApplication != null && clientApplication.getName().equals(name)) { - // don't configure again - return; - } - if (clientApplication != null && !clientApplication.getName().equals(name)) { - throw new IllegalStateException("Application name " - + clientApplication.getName() + " once set cannot be renamed."); - } - - if (OptionHelper.isEmpty(name)) { - throw new IllegalArgumentException( - "Application name cannot be null or empty"); - } else { - - // logger.info("Naming client application as [" + name + "]"); - } - - try { - InetAddress address = InetAddress.getLocalHost(); - String fqdn = address.getCanonicalHostName(); - // logger("Client application host is ["+fqdn+"]."); - Application aplication = new Application(name, fqdn); - // all is nice and dandy - clientApplication = aplication; - } catch (UnknownHostException e) { - throw new IllegalStateException( - "Failed to determine the hostname for this host", e); - } - - // defaultAuditor.close(); - defaultAuditor = new Auditor(); - defaultAuditor.setClientApplication(clientApplication); - defaultAuditor.setName(DEFAULT_AUDITOR_NAME); - autoConfig(defaultAuditor); - checkSanity(defaultAuditor); - } - - /** - * Get the default auditor. If it has not been previously configured, this - * method will also configure the default auditor. In case of problems, this - * method may throw an exception. - * - * @return - * @throws AuditException - */ - public static Auditor getAuditor() { - return defaultAuditor; - } - - public static void autoConfig(Auditor auditor) throws AuditException { - ClassLoader tccl = Loader.getTCL(); - autoConfig(auditor, tccl); - } - - public static void configureByResource(Auditor auditor, URL url) - throws AuditException { - if (url == null) { - throw new IllegalArgumentException("URL argument cannot be null"); - } - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(auditor); - - try { - configurator.doConfigure(url); - } catch (JoranException e) { - throw new AuditException("Configuration failure in " + url, e); - } - - } - - public static void autoConfig(Auditor auditor, ClassLoader classLoader) - throws AuditException { - - String autoConfigFileByProperty = System - .getProperty(AUTOCONFIG_FILE_PROPERTY); - String pathPrefix = clientApplication.getName() + "/"; - URL url = null; - - if (autoConfigFileByProperty != null) { - url = Loader.getResource(pathPrefix + autoConfigFileByProperty, - classLoader); - - } else { - url = Loader.getResource(pathPrefix + TEST_AUTOCONFIG_FILE, classLoader); - if (url == null) { - url = Loader.getResource(pathPrefix + AUTOCONFIG_FILE, classLoader); - } - } - if (url != null) { - configureByResource(auditor, url); - } else { - String errMsg; - if (autoConfigFileByProperty != null) { - errMsg = "Failed to find configuration file [" + pathPrefix - + autoConfigFileByProperty + "]."; - } else { - errMsg = "Failed to find logback-audit configuration files [" - + pathPrefix + TEST_AUTOCONFIG_FILE + "] or [" + pathPrefix - + AUTOCONFIG_FILE + "]."; - } - throw new AuditException(errMsg); - } - } - - static public void reset() { - clientApplication = null; - if (defaultAuditor != null) { - defaultAuditor.shutdown(); - } - defaultAuditor = null; - } + static final String DEFAULT_AUDITOR_NAME = "default"; + static final String AUTOCONFIG_FILE = "logback-audit.xml"; + static final String TEST_AUTOCONFIG_FILE = "logback-audit-test.xml"; + + static final public String AUTOCONFIG_FILE_PROPERTY = "logback.audit.autoconfig.file"; + + static final public String NULL_CLIENT_APPLICATON_URL = "http://audit.qos.ch/codes.html#nullClientApp"; + static final public String NULL_AUDIT_APPENDER_URL = "http://audit.qos.ch/codes.html#nullAuditAppender"; + + static Auditor defaultAuditor; + + static Application clientApplication; + + static void checkSanity(final Auditor auditor) throws AuditException { + final StatusManager sm = auditor.getStatusManager(); + final StatusChecker checker = new StatusChecker(sm); + if (checker.getHighestLevel(0) > Status.INFO) { + StatusPrinter.print(sm); + } + + if (auditor.getClientApplication() == null) { + throw new AuditException("Client application has not been set"); + } + + if (auditor.getAuditAppender() == null) { + throw new AuditException("No audit appender. Please see " + NULL_AUDIT_APPENDER_URL); + } + } + + public static void setApplicationName(final String name) throws AuditException { + if (nonNull(clientApplication) && clientApplication.getName().equals(name)) { + // don't configure again + return; + } + if (nonNull(clientApplication) && !clientApplication.getName().equals(name)) { + throw new IllegalStateException( + "Application name " + clientApplication.getName() + " once set cannot be renamed."); + } + + if (OptionHelper.isEmpty(name)) { + throw new IllegalArgumentException("Application name cannot be null or empty"); + } + + try { + final InetAddress address = InetAddress.getLocalHost(); + final String fqdn = address.getCanonicalHostName(); + // logger("Client application host is ["+fqdn+"]."); + final Application aplication = new Application(name, fqdn); + // all is nice and dandy + clientApplication = aplication; + } catch (final UnknownHostException e) { + throw new IllegalStateException("Failed to determine the hostname for this host", e); + } + + // defaultAuditor.close(); + defaultAuditor = new Auditor(); + defaultAuditor.setClientApplication(clientApplication); + defaultAuditor.setName(DEFAULT_AUDITOR_NAME); + autoConfig(defaultAuditor); + checkSanity(defaultAuditor); + } + + /** + * Get the default auditor. If it has not been previously configured, this + * method will also configure the default auditor. In case of problems, this + * method may throw an exception. + * + * @return + * @throws AuditException + */ + public static Auditor getAuditor() { + return defaultAuditor; + } + + public static void autoConfig(final Auditor auditor) throws AuditException { + final ClassLoader tccl = Loader.getTCL(); + autoConfig(auditor, tccl); + } + + public static void configureByResource(final Auditor auditor, final URL url) throws AuditException { + if (isNull(url)) { + throw new IllegalArgumentException("URL argument cannot be null"); + } + final JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(auditor); + + try { + configurator.doConfigure(url); + } catch (final JoranException e) { + throw new AuditException("Configuration failure in " + url, e); + } + + } + + public static void autoConfig(final Auditor auditor, final ClassLoader classLoader) throws AuditException { + + final String autoConfigFileByProperty = System.getProperty(AUTOCONFIG_FILE_PROPERTY); + final String pathPrefix = clientApplication.getName() + "/"; + URL url = null; + + if (autoConfigFileByProperty != null) { + url = Loader.getResource(pathPrefix + autoConfigFileByProperty, classLoader); + + } else { + url = Loader.getResource(pathPrefix + TEST_AUTOCONFIG_FILE, classLoader); + if (isNull(url)) { + url = Loader.getResource(pathPrefix + AUTOCONFIG_FILE, classLoader); + } + } + if (isNull(url)) { + String errMsg; + if (nonNull(autoConfigFileByProperty)) { + errMsg = "Failed to find configuration file [" + pathPrefix + autoConfigFileByProperty + "]."; + } else { + errMsg = "Failed to find logback-audit configuration files [" + pathPrefix + TEST_AUTOCONFIG_FILE + + "] or [" + pathPrefix + AUTOCONFIG_FILE + "]."; + } + throw new AuditException(errMsg); + } + configureByResource(auditor, url); + } + + static public void reset() { + clientApplication = null; + if (nonNull(defaultAuditor)) { + defaultAuditor.shutdown(); + } + defaultAuditor = null; + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorImpl.java b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorImpl.java index c00b7d1..b2a361d 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorImpl.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/AuditorImpl.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -21,40 +21,40 @@ import ch.qos.logback.core.Appender; import ch.qos.logback.core.spi.AppenderAttachableImpl; -public class AuditorImpl { - - AppenderAttachableImpl aai = new AppenderAttachableImpl(); - - public void log(AuditEvent auditEvent) throws AuditException { - int writes = aai.appendLoopOnAppenders(auditEvent); - // No appenders in hierarchy - if (writes == 0) { - throw new AuditException("no appender defined"); - } - } - - public void addAppender(Appender newAppender) { - aai.addAppender(newAppender); - } - - public void detachAndStopAllAppenders() { - aai.detachAndStopAllAppenders(); - } - - public boolean detachAppender(Appender appender) { - return aai.detachAppender(appender); - } - - public Appender getAppender(String name) { - return aai.getAppender(name); - } - - public boolean isAttached(Appender appender) { - return aai.isAttached(appender); - } - - public Iterator iteratorForAppenders() { - return aai.iteratorForAppenders(); - } +public class AuditorImpl { + + AppenderAttachableImpl aai = new AppenderAttachableImpl<>(); + + public void log(final AuditEvent auditEvent) throws AuditException { + final int writes = aai.appendLoopOnAppenders(auditEvent); + // No appenders in hierarchy + if (writes == 0) { + throw new AuditException("no appender defined"); + } + } + + public void addAppender(final Appender newAppender) { + aai.addAppender(newAppender); + } + + public void detachAndStopAllAppenders() { + aai.detachAndStopAllAppenders(); + } + + public boolean detachAppender(final Appender appender) { + return aai.detachAppender(appender); + } + + public Appender getAppender(final String name) { + return aai.getAppender(name); + } + + public boolean isAttached(final Appender appender) { + return aai.isAttached(appender); + } + + public Iterator iteratorForAppenders() { + return aai.iteratorForAppenders(); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/ListAuditAppender.java b/audit-client/src/main/java/ch/qos/logback/audit/client/ListAuditAppender.java index 0c10115..69c301d 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/ListAuditAppender.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/ListAuditAppender.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -22,29 +22,27 @@ public class ListAuditAppender extends AuditAppenderBase { - List auditEventList = null; - - - @Override - protected void append(AuditEvent auditEvent) throws AuditException { - auditEventList.add(auditEvent); - } - - @Override - public void start() { - auditEventList = new ArrayList(); - super.start(); - } - - - @Override - public void stop() { - auditEventList = null; - super.stop(); - } - - public List getAuditEventList() { - return auditEventList; - } + List auditEventList = null; + + @Override + protected void append(final AuditEvent auditEvent) throws AuditException { + auditEventList.add(auditEvent); + } + + @Override + public void start() { + auditEventList = new ArrayList<>(); + super.start(); + } + + @Override + public void stop() { + auditEventList = null; + super.stop(); + } + + public List getAuditEventList() { + return auditEventList; + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/NOPAuditAppender.java b/audit-client/src/main/java/ch/qos/logback/audit/client/NOPAuditAppender.java index 29a6559..d39f471 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/NOPAuditAppender.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/NOPAuditAppender.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -19,19 +19,18 @@ public class NOPAuditAppender extends AuditAppenderBase { - @Override - protected void append(AuditEvent auditEvent) throws AuditException { - } - - @Override - public void start() { - super.start(); - } + @Override + protected void append(final AuditEvent auditEvent) throws AuditException { + } - - @Override - public void stop() { - super.stop(); - } + @Override + public void start() { + super.start(); + } + + @Override + public void stop() { + super.stop(); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/SLF4JAuditAppender.java b/audit-client/src/main/java/ch/qos/logback/audit/client/SLF4JAuditAppender.java index aede86d..04fbd6c 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/SLF4JAuditAppender.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/SLF4JAuditAppender.java @@ -1,19 +1,21 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.audit.client; +import java.util.Objects; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,28 +24,29 @@ public class SLF4JAuditAppender extends AuditAppenderBase { - final static String DEFAULT_LOGGER_NAME = "audit"; - String loggerName = DEFAULT_LOGGER_NAME; - Logger logger; - - @Override - protected void append(AuditEvent auditEvent) throws AuditException { - logger.info(auditEvent.toString()); - } - - public String getLoggerName() { - return loggerName; - } - - public void setLoggerName(String loggerName) { - if(loggerName == null) { - throw new IllegalArgumentException("loggerName cannot be null"); - } - this.loggerName = loggerName; - } - - public void start() { - logger = LoggerFactory.getLogger("audit"); - super.start(); - } + final static String DEFAULT_LOGGER_NAME = "audit"; + String loggerName = DEFAULT_LOGGER_NAME; + Logger logger; + + @Override + protected void append(final AuditEvent auditEvent) throws AuditException { + logger.info(auditEvent.toString()); + } + + public String getLoggerName() { + return loggerName; + } + + public void setLoggerName(final String loggerName) { + if (Objects.isNull(loggerName)) { + throw new IllegalArgumentException("loggerName cannot be null"); + } + this.loggerName = loggerName; + } + + @Override + public void start() { + logger = LoggerFactory.getLogger("audit"); + super.start(); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/JoranConfigurator.java b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/JoranConfigurator.java index 5b5d407..043fccf 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/JoranConfigurator.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/JoranConfigurator.java @@ -1,20 +1,19 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.audit.client.joran; - import ch.qos.logback.audit.client.joran.action.AuditAppenderAction; import ch.qos.logback.audit.client.joran.action.AuditorAction; import ch.qos.logback.core.joran.GenericConfigurator; @@ -24,31 +23,29 @@ import ch.qos.logback.core.joran.spi.Pattern; import ch.qos.logback.core.joran.spi.RuleStore; - - /** * JoranConfigurator for the audit module. - * + * * @author Ceki Gülcü */ public class JoranConfigurator extends GenericConfigurator { - @Override - public void addInstanceRules(RuleStore rs) { - rs.addRule(new Pattern("auditor"), new AuditorAction()); - rs.addRule(new Pattern("auditor/appender"), new AuditAppenderAction()); - } - - @Override - protected void addImplicitRules(Interpreter interpreter) { - // The following line adds the capability to parse nested components - NestedComplexPropertyIA nestedComplexPropertyIA = new NestedComplexPropertyIA(); - nestedComplexPropertyIA.setContext(context); - interpreter.addImplicitAction(nestedComplexPropertyIA); - - NestedBasicPropertyIA nestedBasicIA = new NestedBasicPropertyIA(); - nestedBasicIA.setContext(context); - interpreter.addImplicitAction(nestedBasicIA); - } + @Override + public void addInstanceRules(final RuleStore rs) { + rs.addRule(new Pattern("auditor"), new AuditorAction()); + rs.addRule(new Pattern("auditor/appender"), new AuditAppenderAction()); + } + + @Override + protected void addImplicitRules(final Interpreter interpreter) { + // The following line adds the capability to parse nested components + final NestedComplexPropertyIA nestedComplexPropertyIA = new NestedComplexPropertyIA(); + nestedComplexPropertyIA.setContext(context); + interpreter.addImplicitAction(nestedComplexPropertyIA); + + final NestedBasicPropertyIA nestedBasicIA = new NestedBasicPropertyIA(); + nestedBasicIA.setContext(context); + interpreter.addImplicitAction(nestedBasicIA); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditAppenderAction.java b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditAppenderAction.java index e3f3b3d..b12ca64 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditAppenderAction.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditAppenderAction.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -26,74 +26,67 @@ public class AuditAppenderAction extends Action { - AuditAppender auditAppender; - private boolean inError = false; - - @Override - public void begin(InterpretationContext ec, String name, Attributes attributes) - throws ActionException { - String className = attributes.getValue(CLASS_ATTRIBUTE); - - // We are just beginning, reset variables - auditAppender = null; - inError = false; - - try { - addInfo("About to instantiate appender of type ["+className+"]"); - - auditAppender = (AuditAppender) OptionHelper.instantiateByClassName( - className, ch.qos.logback.audit.client.AuditAppender.class, context); - - auditAppender.setContext(context); - - String appenderName = attributes.getValue(NAME_ATTRIBUTE); - - if (OptionHelper.isEmpty(appenderName)) { - addWarn( - "No appender name given for appender of type " + className + "]."); - } else { - auditAppender.setName(appenderName); - addInfo("Naming appender as [" + appenderName + "]"); - } - - //getLogger().debug("Pushing appender on to the object stack."); - ec.pushObject(auditAppender); - } catch (Exception oops) { - inError = true; - addError( - "Could not create an Appender of type ["+className+"].", oops); - throw new ActionException(oops); - } - } - - @Override - public void end(InterpretationContext ec, String name) throws ActionException { - if (inError) { - return; - } - Object o = ec.peekObject(); - - if (o != auditAppender) { - addWarn( - "The object at the of the stack is not the appender named [" - + auditAppender.getName() + "] pushed earlier."); - } else { - addInfo( - "Popping appender named [" + auditAppender.getName() - + "] from the object stack"); - ec.popObject(); - } - - addInfo( - "Setting auditor's appender to appender named [" + auditAppender.getName() - + "]"); - - if (auditAppender instanceof LifeCycle) { - ((LifeCycle) auditAppender).start(); - } - - Auditor ac = (Auditor) context; - ac.setAuditAppender(auditAppender); - } + AuditAppender auditAppender; + private boolean inError = false; + + @Override + public void begin(final InterpretationContext ec, final String name, final Attributes attributes) + throws ActionException { + final String className = attributes.getValue(CLASS_ATTRIBUTE); + + // We are just beginning, reset variables + auditAppender = null; + inError = false; + + try { + addInfo("About to instantiate appender of type [" + className + "]"); + + auditAppender = (AuditAppender) OptionHelper.instantiateByClassName(className, AuditAppender.class, + context); + + auditAppender.setContext(context); + + final String appenderName = attributes.getValue(NAME_ATTRIBUTE); + + if (OptionHelper.isEmpty(appenderName)) { + addWarn("No appender name given for appender of type " + className + "]."); + } else { + auditAppender.setName(appenderName); + addInfo("Naming appender as [" + appenderName + "]"); + } + + // getLogger().debug("Pushing appender on to the object stack."); + ec.pushObject(auditAppender); + } catch (final Exception oops) { + inError = true; + addError("Could not create an Appender of type [" + className + "].", oops); + throw new ActionException(oops); + } + } + + @Override + public void end(final InterpretationContext ec, final String name) throws ActionException { + if (inError) { + return; + } + final Object o = ec.peekObject(); + + if (o != auditAppender) { + addWarn("The object at the of the stack is not the appender named [" + auditAppender.getName() + + "] pushed earlier."); + } else { + addInfo("Popping appender named [" + auditAppender.getName() + "] from the object stack"); + ec.popObject(); + } + + addInfo("Setting auditor's appender to appender named [" + auditAppender.getName() + "]"); + + if (auditAppender instanceof LifeCycle) { + ((LifeCycle) auditAppender).start(); + } + + final Auditor ac = (Auditor) context; + ac.setAuditAppender(auditAppender); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java index 1b8e694..0b33245 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/joran/action/AuditorAction.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -22,35 +22,37 @@ import ch.qos.logback.core.util.StatusPrinter; public class AuditorAction extends Action { - static final String INTERNAL_DEBUG_ATTR = "debug"; - boolean debugMode = false; - - public void begin(InterpretationContext ec, String name, Attributes attributes) throws ActionException { - String debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR); - - if ((debugAttrib == null) || debugAttrib.equals("") - || debugAttrib.equals("false") || debugAttrib.equals("null")) { - addInfo("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); - } else { - debugMode = true; - } - -// if ((nameAttrib == null) || nameAttrib.equals("")) { -// String errMsg = "Empty " + NAME_ATTRIBUTE + " attribute."; -// addError(errMsg); -// throw new ActionException(ActionException.SKIP_CHILDREN); -// } - - // the context is appender attachable, so it is pushed on top of the stack - ec.pushObject(getContext()); - } - - public void end(InterpretationContext ec, String name) { - if (debugMode) { - addInfo("End of configuration."); - StatusPrinter.print(context); - } - - ec.popObject(); - } + static final String INTERNAL_DEBUG_ATTR = "debug"; + boolean debugMode = false; + + @Override + public void begin(final InterpretationContext ec, final String name, final Attributes attributes) throws ActionException { + final String debugAttrib = attributes.getValue(INTERNAL_DEBUG_ATTR); + + if (debugAttrib == null || debugAttrib.equals("") + || debugAttrib.equals("false") || debugAttrib.equals("null")) { + addInfo("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); + } else { + debugMode = true; + } + + // if ((nameAttrib == null) || nameAttrib.equals("")) { + // String errMsg = "Empty " + NAME_ATTRIBUTE + " attribute."; + // addError(errMsg); + // throw new ActionException(ActionException.SKIP_CHILDREN); + // } + + // the context is appender attachable, so it is pushed on top of the stack + ec.pushObject(getContext()); + } + + @Override + public void end(final InterpretationContext ec, final String name) { + if (debugMode) { + addInfo("End of configuration."); + StatusPrinter.print(context); + } + + ec.popObject(); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/net/Connector.java b/audit-client/src/main/java/ch/qos/logback/audit/client/net/Connector.java index f0d69e2..001cb42 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/net/Connector.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/net/Connector.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -24,59 +24,55 @@ public class Connector extends ContextAwareBase implements Runnable { - Logger logger = LoggerFactory.getLogger(Connector.class); - - SocketAuditAppender socketAuditAppender; - boolean closed = false; - Thread thread; - - Connector(SocketAuditAppender socketAuditAppender) { - this.socketAuditAppender = socketAuditAppender; - } - - - public Thread getThread() { - return thread; - } - - public void setThread(Thread thread) { - this.thread = thread; - } - - public void setClosed(boolean closed) { - this.closed = closed; - } - - - public void run() { - - addInfo("Entering Connector.run() method."); - - Socket socket; - - while (!closed) { - try { - Thread.sleep(socketAuditAppender.getReconnectionDelay()); - // if the connector has been closed while we were sleeping - // there is no need to attempt a connection to the remote - // host - if(closed) { - break; - } - socket = new Socket(socketAuditAppender.getAddress(), - socketAuditAppender.getPort()); - socketAuditAppender.connect(socket); - // Connection established. Exiting connector thread. - break; - } catch (InterruptedException e) { - return; - } catch (java.net.ConnectException e) { - // continue - } catch (IOException e) { - // continue - } - } - addInfo("Exiting Connector.run() method."); - } + Logger logger = LoggerFactory.getLogger(Connector.class); + + SocketAuditAppender socketAuditAppender; + boolean closed = false; + Thread thread; + + Connector(final SocketAuditAppender socketAuditAppender) { + this.socketAuditAppender = socketAuditAppender; + } + + public Thread getThread() { + return thread; + } + + public void setThread(final Thread thread) { + this.thread = thread; + } + + public void setClosed(final boolean closed) { + this.closed = closed; + } + + @Override + public void run() { + + addInfo("Entering Connector.run() method."); + + Socket socket; + + while (!closed) { + try { + Thread.sleep(socketAuditAppender.getReconnectionDelay()); + // if the connector has been closed while we were sleeping + // there is no need to attempt a connection to the remote + // host + if (closed) { + break; + } + socket = new Socket(socketAuditAppender.getAddress(), socketAuditAppender.getPort()); + socketAuditAppender.connect(socket); + // Connection established. Exiting connector thread. + break; + } catch (final InterruptedException e) { + return; + } catch (final IOException e) { + // continue + } + } + addInfo("Exiting Connector.run() method."); + } } diff --git a/audit-client/src/main/java/ch/qos/logback/audit/client/net/SocketAuditAppender.java b/audit-client/src/main/java/ch/qos/logback/audit/client/net/SocketAuditAppender.java index 7fe06a9..15a32f5 100644 --- a/audit-client/src/main/java/ch/qos/logback/audit/client/net/SocketAuditAppender.java +++ b/audit-client/src/main/java/ch/qos/logback/audit/client/net/SocketAuditAppender.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -19,6 +19,7 @@ import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; +import java.util.Objects; import ch.qos.logback.audit.AuditEvent; import ch.qos.logback.audit.AuditException; @@ -27,239 +28,227 @@ public class SocketAuditAppender extends AuditAppenderBase { - static final String NO_HOST_URL = InternalAuditContants.CODES_URL - + "#NO_HOST_URL"; - - static final String FAILIED_WRITE_URL = InternalAuditContants.CODES_URL - + "#FAILIED_WRITE_URL"; - - /** - * The default port number of remote logging server (9630). - */ - static final int DEFAULT_PORT = 9630; - - private String remoteHost; - - private InetAddress address; - private int port = DEFAULT_PORT; - - private ObjectOutputStream oos; - private ObjectInputStream ois; - - private int reconnectionDelay = 2000; - - protected int counter = 0; - - // reset the ObjectOutputStream every RESET_FREQUENCY calls - private static final int RESET_FREQUENCY = 200; - - Connector connector; - - /** - * Start this appender. - */ - public void start() { - int errorCount = 0; - if (port == 0) { - errorCount++; - addError("No port was configured for appender" + name); - } - - if (address == null) { - errorCount++; - addError("No remote address was configured for appender " + name); - } - - if (errorCount == 0) { - connect(address, port); - } - } - - @Override - public void stop() { - super.stop(); - cleanUp(); - if (connector != null) { - connector.setClosed(true); - Thread connectorThread = connector.getThread(); - try { - connectorThread.join(5000); - } catch (InterruptedException e) { - addError("Failed to join connector thread", e); - } - connector = null; - } - - } - - void connect(Socket socket) { - try { - // First, close the previous connection if any. - cleanUp(); - - oos = new ObjectOutputStream(socket.getOutputStream()); - ois = new ObjectInputStream(socket.getInputStream()); - super.started = true; - } catch (IOException e) { - String msg = "Failed to open a stream on the socket for remmote logback server at [" - + address.getHostName() + "] at port " + port; - addError(msg, e); - } - } - - void connect(InetAddress address, int port) { - try { - // First, close the previous connection if any. - cleanUp(); - Socket socket = new Socket(address, port); - connect(socket); - } catch (IOException e) { - String msg = "Could not connect to remote logback server at [" - + address.getHostName() + "] at port " + port; - addError(msg, e); - if (reconnectionDelay > 0) { - fireConnector(); - } - } - } - - /** - * Drop the connection to the remote host and release the underlying connector - * thread if it has been created - */ - public void cleanUp() { - if (oos != null) { - try { - oos.close(); - } catch (IOException e) { - addError("Could not close oos.", e); - } - oos = null; - } - if (ois != null) { - try { - ois.close(); - } catch (IOException e) { - addError("Could not close oos.", e); - } - ois = null; - } - } - - @Override - protected void append(AuditEvent auditEvent) throws AuditException { - - if(!started) { - return; - } - - if (auditEvent == null) - return; - - if (oos != null) { - try { - oos.writeObject(auditEvent); - oos.flush(); - - if (++counter >= RESET_FREQUENCY) { - counter = 0; - // Failing to reset the object output stream every now and - // then creates a serious memory leak. - oos.reset(); - } - } catch (IOException e) { - oos = null; - this.started = false; - fireConnector(); - throw new AuditException("Failed sending audit event to host \"" - + remoteHost + "\" down. For more information, please visit " - + FAILIED_WRITE_URL, e); - } - } - - try { - Object incoming = ois.readObject(); - if (incoming instanceof Exception) { - if (incoming instanceof AuditException) { - AuditException ae = (AuditException) incoming; - throw ae; - } else { - throw new AuditException("Server incurred an exception", - (Exception) incoming); - } - } else if (incoming instanceof Boolean) { - Boolean ack = (Boolean) incoming; - if (ack.booleanValue()) { - // System.out.println("ACKED"); - } else { - throw new AuditException("Acknowledgement failure"); - } - } else { - throw new AuditException("Incoming object [" + incoming - + "] outside of protocol"); - } - } catch (IOException e) { - throw new AuditException("Failed reading acknowledgement", e); - } catch (ClassNotFoundException e) { - throw new AuditException("Unexpecteed object type while acknowledgement", - e); - } - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getRemoteHost() { - return remoteHost; - } - - protected static InetAddress getAddressByName(String host) { - try { - return InetAddress.getByName(host); - } catch (Exception e) { - // addError("Could not find address of [" + host + "].", e); - return null; - } - } - - void fireConnector() { - if (connector == null) { - addInfo("Firing a connector thread"); - connector = new Connector(this); - connector.setContext(this.getContext()); - Thread connectorThread = new Thread(connector); - connectorThread.setDaemon(true); - connectorThread.setName("SAA-ConnectorThread"); - connectorThread.setPriority(Thread.MIN_PRIORITY); - connector.setThread(connectorThread); - connectorThread.start(); - } - } - - InetAddress getAddress() { - return address; - } - - public int getReconnectionDelay() { - return reconnectionDelay; - } - - public void setReconnectionDelay(int reconnectionDelay) { - this.reconnectionDelay = reconnectionDelay; - } - - /** - * The RemoteHost option takes a string value which should be the host - * name of the server where a {@link SocketNode} is running. - */ - public void setRemoteHost(String host) { - address = getAddressByName(host); - remoteHost = host; - } + static final String NO_HOST_URL = InternalAuditContants.CODES_URL + "#NO_HOST_URL"; + + static final String FAILIED_WRITE_URL = InternalAuditContants.CODES_URL + "#FAILIED_WRITE_URL"; + + /** + * The default port number of remote logging server (9630). + */ + static final int DEFAULT_PORT = 9630; + + private String remoteHost; + + private InetAddress address; + private int port = DEFAULT_PORT; + + private ObjectOutputStream oos; + private ObjectInputStream ois; + + private int reconnectionDelay = 2000; + + protected int counter = 0; + + // reset the ObjectOutputStream every RESET_FREQUENCY calls + private static final int RESET_FREQUENCY = 200; + + Connector connector; + + /** + * Start this appender. + */ + @Override + public void start() { + int errorCount = 0; + if (port == 0) { + errorCount++; + addError("No port was configured for appender " + name); + } + + if (address == null) { + errorCount++; + addError("No remote address was configured for appender " + name); + } + + if (errorCount == 0) { + connect(address, port); + } + } + + @Override + public void stop() { + super.stop(); + cleanUp(); + if (Objects.nonNull(connector)) { + connector.setClosed(true); + final Thread connectorThread = connector.getThread(); + try { + connectorThread.join(5000); + } catch (final InterruptedException e) { + addError("Failed to join connector thread", e); + } + connector = null; + } + + } + + void connect(final Socket socket) { + try { + // First, close the previous connection if any. + cleanUp(); + + oos = new ObjectOutputStream(socket.getOutputStream()); + ois = new ObjectInputStream(socket.getInputStream()); + super.started = true; + } catch (final IOException e) { + addError(String.format( + "Failed to open a stream on the socket for remmote logback server at [%s] at port [%d]", + address.getHostName(), port), e); + } + } + + void connect(final InetAddress address, final int port) { + try { + // First, close the previous connection if any. + cleanUp(); + final Socket socket = new Socket(address, port); + connect(socket); + } catch (final IOException e) { + addError(String.format("Could not connect to remote logback server at [%s] at port [%d]", + address.getHostName(), port), e); + if (reconnectionDelay > 0) { + fireConnector(); + } + } + } + + /** + * Drop the connection to the remote host and release the underlying connector + * thread if it has been created + */ + public void cleanUp() { + if (Objects.nonNull(oos)) { + try { + oos.close(); + } catch (final IOException e) { + addError("Could not close oos.", e); + } + oos = null; + } + if (Objects.nonNull(ois)) { + try { + ois.close(); + } catch (final IOException e) { + addError("Could not close oos.", e); + } + ois = null; + } + } + + @Override + protected void append(final AuditEvent auditEvent) throws AuditException { + + if (!started || Objects.isNull(auditEvent)) { + return; + } + + if (Objects.nonNull(oos)) { + try { + oos.writeObject(auditEvent); + oos.flush(); + + if (++counter >= RESET_FREQUENCY) { + counter = 0; + // Failing to reset the object output stream every now and + // then creates a serious memory leak. + oos.reset(); + } + } catch (final IOException e) { + oos = null; + started = false; + fireConnector(); + throw new AuditException("Failed sending audit event to host \"" + remoteHost + + "\" down. For more information, please visit " + FAILIED_WRITE_URL, e); + } + } + + try { + final Object incoming = ois.readObject(); + if (incoming instanceof Exception) { + if (incoming instanceof AuditException) { + final AuditException ae = (AuditException) incoming; + throw ae; + } + throw new AuditException("Server incurred an exception", (Exception) incoming); + } + if (!(incoming instanceof Boolean)) { + throw new AuditException("Incoming object [" + incoming + "] outside of protocol"); + } + final Boolean ack = (Boolean) incoming; + if (!ack) { + throw new AuditException("Acknowledgement failure"); + } + } catch (final IOException e) { + throw new AuditException("Failed reading acknowledgement", e); + } catch (final ClassNotFoundException e) { + throw new AuditException("Unexpecteed object type while acknowledgement", e); + } + } + + public int getPort() { + return port; + } + + public void setPort(final int port) { + this.port = port; + } + + public String getRemoteHost() { + return remoteHost; + } + + protected static InetAddress getAddressByName(final String host) { + try { + return InetAddress.getByName(host); + } catch (final Exception e) { + // addError("Could not find address of [" + host + "].", e); + return null; + } + } + + void fireConnector() { + if (Objects.isNull(connector)) { + addInfo("Firing a connector thread"); + connector = new Connector(this); + connector.setContext(getContext()); + final Thread connectorThread = new Thread(connector); + connectorThread.setDaemon(true); + connectorThread.setName("SAA-ConnectorThread"); + connectorThread.setPriority(Thread.MIN_PRIORITY); + connector.setThread(connectorThread); + connectorThread.start(); + } + } + + InetAddress getAddress() { + return address; + } + + public int getReconnectionDelay() { + return reconnectionDelay; + } + + public void setReconnectionDelay(final int reconnectionDelay) { + this.reconnectionDelay = reconnectionDelay; + } + + /** + * The RemoteHost option takes a string value which should be the host + * name of the server where a {@link SocketNode} is running. + */ + public void setRemoteHost(final String host) { + address = getAddressByName(host); + remoteHost = host; + } } diff --git a/audit-common/pom.xml b/audit-common/pom.xml index 9079470..1e401e0 100644 --- a/audit-common/pom.xml +++ b/audit-common/pom.xml @@ -1,50 +1,44 @@ + - - - - - - ch.qos.logback - audit-parent - 0.6 - - - 4.0.0 - - ch.qos.logback - audit-common - jar - Logback Audit Common - - - - ch.qos.logback - logback-core - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/AllTest.java - **/PackageTest.java - **/SizeBasedRollingTest.java - - - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + + ch.qos.logback + audit-parent + 0.7-SNAPSHOT + + + 4.0.0 + + audit-common + jar + Logback Audit Common + + + + ch.qos.logback + logback-core + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/AllTest.java + **/PackageTest.java + **/SizeBasedRollingTest.java + + + + + \ No newline at end of file diff --git a/audit-common/src/main/java/ch/qos/logback/audit/Application.java b/audit-common/src/main/java/ch/qos/logback/audit/Application.java index c76d129..ae3d188 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/Application.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/Application.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -15,79 +15,65 @@ package ch.qos.logback.audit; import java.io.Serializable; +import java.util.Objects; public class Application implements Serializable { - private static final long serialVersionUID = 62706289462L; - - String name; - String ipAddress; - - // Hibernate requires a default Constructor - public Application() { - } - - public Application(String name, String ipAddress) { - this.name = name; - this.ipAddress = ipAddress; - } - - public String getIpAddress() { - return ipAddress; - } - - // Hibernate needs to be able to set the ipAdress - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - public String getName() { - return name; - } - - // Hibernate needs to be able to set the name - public void setName(String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((ipAddress == null) ? 0 : ipAddress.hashCode()); - result = PRIME * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Application other = (Application) obj; - if (ipAddress == null) { - if (other.ipAddress != null) - return false; - } else if (!ipAddress.equals(other.ipAddress)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - String retValue = ""; - - retValue = "Appl(" + "name=" + this.name + ", ip=" + this.ipAddress + ")"; - - return retValue; - } + private static final long serialVersionUID = 62706289462L; + + String name; + String ipAddress; + + // Hibernate requires a default Constructor + public Application() { + } + + public Application(final String name, final String ipAddress) { + this.name = name; + this.ipAddress = ipAddress; + } + + public String getIpAddress() { + return ipAddress; + } + + // Hibernate needs to be able to set the ipAdress + public void setIpAddress(final String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getName() { + return name; + } + + // Hibernate needs to be able to set the name + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hash(ipAddress, name); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final Application other = (Application) obj; + if (!Objects.equals(ipAddress, other.ipAddress) || !Objects.equals(name, other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + return "Appl(" + "name=" + name + ", ip=" + ipAddress + ")"; + } } diff --git a/audit-common/src/main/java/ch/qos/logback/audit/AuditEvent.java b/audit-common/src/main/java/ch/qos/logback/audit/AuditEvent.java index ce72246..dedaf9b 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/AuditEvent.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/AuditEvent.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,200 +18,148 @@ import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; +import java.util.Objects; public class AuditEvent implements Serializable { - private static final long serialVersionUID = 6641931592187864466L; - - Long id; - private Timestamp timestamp; - String subject; - String verb; - String object; - Map predicateMap = new HashMap(); - - Application originatingApplication; - Application clientApplication; - - AuditEvent() { - timestamp = new Timestamp(System.currentTimeMillis()); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - - public String getObject() { - return object; - } - - /** - * Only AuditEventBuilder can set properties of an AuditEvent. - * - * @param verb - */ - public void setObject(String object) { - this.object = object; - } - - public String getSubject() { - return subject; - } - - /** - * Only AuditEventBuilder can set properties of an AuditEvent. - * - * @param verb - */ - public void setSubject(String subject) { - this.subject = subject; - } - - public String getVerb() { - return verb; - } - - /** - * Only AuditEventBuilder can set properties of an AuditEvent. - * - * @param verb - */ - public void setVerb(String verb) { - this.verb = verb; - } - - public Application getClientApplication() { - return clientApplication; - } - - public void setClientApplication(Application clientApplication) { - this.clientApplication = clientApplication; - } - - public Application getOriginatingApplication() { - return originatingApplication; - } - - public void setOriginatingApplication(Application originatingApplication) { - this.originatingApplication = originatingApplication; - } - - /** - * Only AuditEventBuilder can set properties of an AuditEvent. - * - * @param verb - */ - public void addPredicate(Predicate predicate) { - predicateMap.put(predicate.getName(), predicate.getValue()); - } - - public void setPredicateMap(Map predicateMap) { - this.predicateMap = predicateMap; - } - - public Map getPredicateMap() { - return predicateMap; - } - - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + ((id == null) ? 0 : id.hashCode()); - result = PRIME * result + ((timestamp == null) ? 0 : timestamp.hashCode()); - result = PRIME * result + ((subject == null) ? 0 : subject.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final AuditEvent other = (AuditEvent) obj; - - // timestamp cannot be null - if (!timestamp.equals(other.timestamp)) { - return false; - } - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) { - return false; - } - - if (subject == null) { - if (other.subject != null) - return false; - } else if (!subject.equals(other.subject)) { - return false; - } - - if (verb == null) { - if (other.verb != null) - return false; - } else if (!verb.equals(other.verb)) { - return false; - } - if (object == null) { - if (other.object != null) - return false; - } else if (!object.equals(other.object)) { - return false; - } - - if (clientApplication == null) { - if (other.clientApplication != null) - return false; - } else if (!clientApplication.equals(other.clientApplication)) { - return false; - } - - if (originatingApplication == null) { - if (other.originatingApplication != null) - return false; - } else if (!originatingApplication.equals(other.originatingApplication)) { - return false; - } - - if (predicateMap == null) { - if (other.predicateMap != null) - return false; - } else if (!predicateMap.equals(other.predicateMap)) { - return false; - } - - return true; - } - - public String toString() { - - String retValue = ""; - - retValue = "AuditEvent(id=" + this.id + ", timestamp=" + this.timestamp - + ", subject=" + this.subject + ", verb=" + this.verb + ", object=" - + this.object + ", predicateMap = " + this.predicateMap - + ", originatingApplication=" + this.originatingApplication - + ", clientApplication=" + this.clientApplication + ")"; - - return retValue; - } + private static final long serialVersionUID = 6641931592187864466L; + + Long id; + private Timestamp timestamp; + String subject; + String verb; + String object; + Map predicateMap = new HashMap<>(); + + Application originatingApplication; + Application clientApplication; + + AuditEvent() { + timestamp = new Timestamp(System.currentTimeMillis()); + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public Timestamp getTimestamp() { + return timestamp; + } + + public void setTimestamp(final Timestamp timestamp) { + this.timestamp = timestamp; + } + + public String getObject() { + return object; + } + + /** + * Only AuditEventBuilder can set properties of an AuditEvent. + * + * @param verb + */ + public void setObject(final String object) { + this.object = object; + } + + public String getSubject() { + return subject; + } + + /** + * Only AuditEventBuilder can set properties of an AuditEvent. + * + * @param verb + */ + public void setSubject(final String subject) { + this.subject = subject; + } + + public String getVerb() { + return verb; + } + + /** + * Only AuditEventBuilder can set properties of an AuditEvent. + * + * @param verb + */ + public void setVerb(final String verb) { + this.verb = verb; + } + + public Application getClientApplication() { + return clientApplication; + } + + public void setClientApplication(final Application clientApplication) { + this.clientApplication = clientApplication; + } + + public Application getOriginatingApplication() { + return originatingApplication; + } + + public void setOriginatingApplication(final Application originatingApplication) { + this.originatingApplication = originatingApplication; + } + + /** + * Only AuditEventBuilder can set properties of an AuditEvent. + * + * @param verb + */ + public void addPredicate(final Predicate predicate) { + predicateMap.put(predicate.getName(), predicate.getValue()); + } + + public void setPredicateMap(final Map predicateMap) { + this.predicateMap = predicateMap; + } + + public Map getPredicateMap() { + return predicateMap; + } + + @Override + public int hashCode() { + return Objects.hash(id, timestamp, subject); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (Objects.isNull(obj) || getClass() != obj.getClass()) { + return false; + } + final AuditEvent other = (AuditEvent) obj; + + // timestamp cannot be null + if (!timestamp.equals(other.timestamp) || !Objects.equals(id, other.id) + || !Objects.equals(subject, other.subject) || !Objects.equals(verb, other.verb)) { + return false; + } + if (!Objects.equals(object, other.object) || !Objects.equals(clientApplication, other.clientApplication) + || !Objects.equals(originatingApplication, other.originatingApplication) + || !Objects.equals(predicateMap, other.predicateMap)) { + return false; + } + + return true; + } + + @Override + public String toString() { + return "AuditEvent(id=" + id + ", timestamp=" + timestamp + ", subject=" + subject + ", verb=" + verb + + ", object=" + object + ", predicateMap = " + predicateMap + ", originatingApplication=" + + originatingApplication + ", clientApplication=" + clientApplication + ")"; + } } diff --git a/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilder.java b/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilder.java index 839906a..4895b7e 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilder.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilder.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -19,16 +19,24 @@ public interface AuditEventBuilder { - public void setObject(String object); - public void setSubject(String subject); - public void setVerb(String verb); - public void setPredicateMap(Map predicateMap); - public void add(Predicate predicate); - public void add(List predicateList); - - public void addPredicate(String key, String value); - public void setClientApplication(Application clientApp); - public void setOriginatingApplication(Application originatingApplication); - public AuditEvent build(); + void setObject(String object); + + void setSubject(String subject); + + void setVerb(String verb); + + void setPredicateMap(Map predicateMap); + + void add(Predicate predicate); + + void add(List predicateList); + + void addPredicate(String key, String value); + + void setClientApplication(Application clientApp); + + void setOriginatingApplication(Application originatingApplication); + + AuditEvent build(); } \ No newline at end of file diff --git a/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilderImpl.java b/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilderImpl.java index df1e648..fe7fd1b 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilderImpl.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/AuditEventBuilderImpl.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,53 +18,62 @@ import java.util.Map; public class AuditEventBuilderImpl implements AuditEventBuilder { - - AuditEvent auditEvent = new AuditEvent(); - - public void setSubject(String subject) { - auditEvent.setSubject(subject); - } - - public void setVerb(String verb) { - auditEvent.setVerb(verb); - } - - public void setObject(String object) { - auditEvent.setObject(object); - } - - public void setPredicateMap(Map predicateMap) { - auditEvent.setPredicateMap(predicateMap); - } + AuditEvent auditEvent = new AuditEvent(); - public void addPredicate(String key, String value) { - Predicate predicate = new Predicate(key, value); - auditEvent.addPredicate(predicate); - } - - public void add(Predicate predicate) { - auditEvent.addPredicate(predicate); - } + @Override + public void setSubject(final String subject) { + auditEvent.setSubject(subject); + } - public void add(List predicateList) { - throw new UnsupportedOperationException("this operation is not yet supported"); - } + @Override + public void setVerb(final String verb) { + auditEvent.setVerb(verb); + } + + @Override + public void setObject(final String object) { + auditEvent.setObject(object); + } + + @Override + public void setPredicateMap(final Map predicateMap) { + auditEvent.setPredicateMap(predicateMap); + } + + @Override + public void addPredicate(final String key, final String value) { + auditEvent.addPredicate(new Predicate(key, value)); + } + + @Override + public void add(final Predicate predicate) { + auditEvent.addPredicate(predicate); + } + + @Override + public void add(final List predicateList) { + throw new UnsupportedOperationException("this operation is not yet supported"); + } + + @Override + public void setClientApplication(final Application clientApplication) { + auditEvent.setClientApplication(clientApplication); + } + + @Override + public void setOriginatingApplication(final Application originatingApplication) { + auditEvent.setOriginatingApplication(originatingApplication); + } + + /* + * (non-Javadoc) + * + * @see ch.qos.logback.audit.AuditEventBuilder#build() + */ + @Override + public AuditEvent build() { + return auditEvent; + } - - public void setClientApplication(Application clientApplication) { - auditEvent.setClientApplication(clientApplication); - } - - public void setOriginatingApplication(Application originatingApplication) { - auditEvent.setOriginatingApplication(originatingApplication); - } - - /* (non-Javadoc) - * @see ch.qos.logback.audit.AuditEventBuilder#build() - */ - public AuditEvent build() { - return auditEvent; - } - } diff --git a/audit-common/src/main/java/ch/qos/logback/audit/AuditException.java b/audit-common/src/main/java/ch/qos/logback/audit/AuditException.java index 6cf91a1..32944e3 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/AuditException.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/AuditException.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -16,14 +16,14 @@ public class AuditException extends Exception { - private static final long serialVersionUID = -8812426046267093174L; + private static final long serialVersionUID = -8812426046267093174L; + + public AuditException(final String msg) { + super(msg); + } + + public AuditException(final String msg, final Throwable t) { + super(msg, t); + } - public AuditException(String msg) { - super(msg); - } - - public AuditException(String msg, Throwable t) { - super(msg, t); - } - } diff --git a/audit-common/src/main/java/ch/qos/logback/audit/InternalAuditContants.java b/audit-common/src/main/java/ch/qos/logback/audit/InternalAuditContants.java index cbfe59e..7a03c13 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/InternalAuditContants.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/InternalAuditContants.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -16,5 +16,5 @@ public class InternalAuditContants { - public static final String CODES_URL = "http://audit.qos.ch/codes.html"; + public static final String CODES_URL = "http://audit.qos.ch/codes.html"; } diff --git a/audit-common/src/main/java/ch/qos/logback/audit/Predicate.java b/audit-common/src/main/java/ch/qos/logback/audit/Predicate.java index 46f466f..bb9631f 100644 --- a/audit-common/src/main/java/ch/qos/logback/audit/Predicate.java +++ b/audit-common/src/main/java/ch/qos/logback/audit/Predicate.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -16,19 +16,19 @@ public class Predicate { - final String name; - final String value; - - public Predicate (String name, String value) { - this.name = name; - this.value = value; - } + final String name; + final String value; - public String getName() { - return name; - } + public Predicate(final String name, final String value) { + this.name = name; + this.value = value; + } - public String getValue() { - return value; - } + public String getName() { + return name; + } + + public String getValue() { + return value; + } } diff --git a/audit-examples/pom.xml b/audit-examples/pom.xml index b802ec2..6cfd730 100644 --- a/audit-examples/pom.xml +++ b/audit-examples/pom.xml @@ -1,60 +1,57 @@ + - ch.qos.logback audit-parent - 0.6 + 0.7-SNAPSHOT 4.0.0 - ch.qos.logback audit-examples jar Logback Audit Examples - - - ch.qos.logback - audit-client - - - org.slf4j - slf4j-simple - test - + + ch.qos.logback + audit-client + + + org.slf4j + slf4j-simple + test + - + - - maven-antrun-plugin - - - compile - - - - - - - - - - - - run - - - - + + maven-antrun-plugin + + + compile + + + + + + + + + + + + run + + + + - \ No newline at end of file diff --git a/audit-examples/src/main/java/examples/BabyStep.java b/audit-examples/src/main/java/examples/BabyStep.java index 224e62b..4d03e26 100644 --- a/audit-examples/src/main/java/examples/BabyStep.java +++ b/audit-examples/src/main/java/examples/BabyStep.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,12 +20,12 @@ public class BabyStep { - public static void main(String[] args) throws AuditException { - // First set the application name. Setting the application will - // also cause logback-audit to configure itself. - AuditorFactory.setApplicationName("BabyStep"); - // One the application name is set and logback-audit is configured, you - // can start auditing - new AuditorFacade("baby", "take", "step").audit(); - } + public static void main(final String[] args) throws AuditException { + // First set the application name. Setting the application will + // also cause logback-audit to configure itself. + AuditorFactory.setApplicationName("BabyStep"); + // One the application name is set and logback-audit is configured, you + // can start auditing + new AuditorFacade("baby", "take", "step").audit(); + } } diff --git a/audit-examples/src/main/java/examples/SecondStep.java b/audit-examples/src/main/java/examples/SecondStep.java index 1992faa..51e94f6 100644 --- a/audit-examples/src/main/java/examples/SecondStep.java +++ b/audit-examples/src/main/java/examples/SecondStep.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,12 +20,12 @@ public class SecondStep { - public static void main(String[] args) throws AuditException { - // First set the application name. Setting the application will - // also cause logback-audit to configure itself. - AuditorFactory.setApplicationName("SecondStep"); - // One the application name is set and logback-audit is configured, you - // can start auditing - new AuditorFacade("baby", "take", "step").audit(); - } + public static void main(final String[] args) throws AuditException { + // First set the application name. Setting the application will + // also cause logback-audit to configure itself. + AuditorFactory.setApplicationName("SecondStep"); + // One the application name is set and logback-audit is configured, you + // can start auditing + new AuditorFacade("baby", "take", "step").audit(); + } } diff --git a/audit-examples/src/main/java/examples/access/AccessException.java b/audit-examples/src/main/java/examples/access/AccessException.java index 5ce9a96..ae00e6d 100644 --- a/audit-examples/src/main/java/examples/access/AccessException.java +++ b/audit-examples/src/main/java/examples/access/AccessException.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -15,14 +15,14 @@ package examples.access; public class AccessException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AccessException(String message) { - super(message); - } + public AccessException(final String message) { + super(message); + } - public AccessException(String message, Throwable cause) { - super(message, cause); - } + public AccessException(final String message, final Throwable cause) { + super(message, cause); + } } diff --git a/audit-examples/src/main/java/examples/access/AccessRightsAdministrator.java b/audit-examples/src/main/java/examples/access/AccessRightsAdministrator.java index c92b32d..42f0cd9 100644 --- a/audit-examples/src/main/java/examples/access/AccessRightsAdministrator.java +++ b/audit-examples/src/main/java/examples/access/AccessRightsAdministrator.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,105 +20,101 @@ /** * A simple application illustrating calls to the logback-audit API. - * + * * @author Ceki Gulcu */ public class AccessRightsAdministrator { - static String ACCESS_RIGHTS_ADMIN_APPLICATION_NAME = "AccessRightsAdmin"; - - static String ADD_PERMISSION_VERB = "ADD_PERMISSION"; - static String REMOVE_PERMISSION_VERB = "REMOVE_PERMISSION"; - - final PermissionMap permissionMap = new PermissionMap(); - - /** - * Add a permission to a user. - * - * @param user - * @param permission - * @throws AccessException - * thrown in case of error while adding a permission - */ - public void addPermission(User user, Permission permission) - throws AccessException { - - // add the permission - permissionMap.addPermission(user, permission); - - // let us now audit the code - - // The following will create an AuditEvent with a subject equal to the - // user's name, a verb equal to ADD_PERMISSION, an the object - // equal to the name of permission passed as argument - AuditorFacade auditorFacade = new AuditorFacade(user.getName(), - ADD_PERMISSION_VERB, permission.getName()); - try { - // send the AuditEvent through an appender (usually to a server) - auditorFacade.audit(); - } catch (AuditException e) { - // if an AuditException occurs, rethrow it as - // an application failure (AccessException) - throw new AccessException("Audit failure", e); - } - } - - /** - * Remove a permission from a user. - * - * @param user - * @param permission - * @throws AccessException - * thrown in case of error while removing a permission - */ - public void removePermission(User user, Permission permission) - throws AccessException { - permissionMap.removePermission(user, permission); - - AuditorFacade auditorFacade = new AuditorFacade(user.getName(), - REMOVE_PERMISSION_VERB, permission.getName()); - AuditHelper.audit(auditorFacade); - - } - - public static void main(String[] args) throws AuditException, AccessException { - AuditorFactory.setApplicationName(ACCESS_RIGHTS_ADMIN_APPLICATION_NAME); - AccessRightsAdministrator ara = new AccessRightsAdministrator(); - - // let us simulate a session adding and removing permissions using - // the AccessRightsAdministration instance just created - - // create 4 users, Alice, Bob, Carol and Dave - User alice = new User("alice"); - User bob = new User("bob"); - User carol = new User("carol"); - User dave = new User("dave"); - - // let us create 5 permission instances - Permission adminPerm = new Permission("administrator"); - Permission createPerm = new Permission("create"); - Permission commentPerm = new Permission("comment"); - Permission votePerm = new Permission("vote"); - Permission browsePerm = new Permission("browse"); - - // grant Alice admin permissions - ara.addPermission(alice, adminPerm); - - // grant Bob create, comment and voting permissions - ara.addPermission(bob, createPerm); - ara.addPermission(bob, commentPerm); - ara.addPermission(bob, votePerm); - - // grant Carol browsing permissions - ara.addPermission(carol, browsePerm); - - // grant Dave browsing permissions - ara.addPermission(dave, browsePerm); - - // remove permissions granted to Bob - ara.removePermission(bob, createPerm); - ara.removePermission(bob, commentPerm); - ara.removePermission(bob, votePerm); - } + static String ACCESS_RIGHTS_ADMIN_APPLICATION_NAME = "AccessRightsAdmin"; + + static String ADD_PERMISSION_VERB = "ADD_PERMISSION"; + static String REMOVE_PERMISSION_VERB = "REMOVE_PERMISSION"; + + final PermissionMap permissionMap = new PermissionMap(); + + /** + * Add a permission to a user. + * + * @param user + * @param permission + * @throws AccessException thrown in case of error while adding a permission + */ + public void addPermission(final User user, final Permission permission) throws AccessException { + + // add the permission + permissionMap.addPermission(user, permission); + + // let us now audit the code + + // The following will create an AuditEvent with a subject equal to the + // user's name, a verb equal to ADD_PERMISSION, an the object + // equal to the name of permission passed as argument + final AuditorFacade auditorFacade = new AuditorFacade(user.getName(), ADD_PERMISSION_VERB, + permission.getName()); + try { + // send the AuditEvent through an appender (usually to a server) + auditorFacade.audit(); + } catch (final AuditException e) { + // if an AuditException occurs, rethrow it as + // an application failure (AccessException) + throw new AccessException("Audit failure", e); + } + } + + /** + * Remove a permission from a user. + * + * @param user + * @param permission + * @throws AccessException thrown in case of error while removing a permission + */ + public void removePermission(final User user, final Permission permission) throws AccessException { + permissionMap.removePermission(user, permission); + + final AuditorFacade auditorFacade = new AuditorFacade(user.getName(), REMOVE_PERMISSION_VERB, + permission.getName()); + AuditHelper.audit(auditorFacade); + + } + + public static void main(final String[] args) throws AuditException, AccessException { + AuditorFactory.setApplicationName(ACCESS_RIGHTS_ADMIN_APPLICATION_NAME); + final AccessRightsAdministrator ara = new AccessRightsAdministrator(); + + // let us simulate a session adding and removing permissions using + // the AccessRightsAdministration instance just created + + // create 4 users, Alice, Bob, Carol and Dave + final User alice = new User("alice"); + final User bob = new User("bob"); + final User carol = new User("carol"); + final User dave = new User("dave"); + + // let us create 5 permission instances + final Permission adminPerm = new Permission("administrator"); + final Permission createPerm = new Permission("create"); + final Permission commentPerm = new Permission("comment"); + final Permission votePerm = new Permission("vote"); + final Permission browsePerm = new Permission("browse"); + + // grant Alice admin permissions + ara.addPermission(alice, adminPerm); + + // grant Bob create, comment and voting permissions + ara.addPermission(bob, createPerm); + ara.addPermission(bob, commentPerm); + ara.addPermission(bob, votePerm); + + // grant Carol browsing permissions + ara.addPermission(carol, browsePerm); + + // grant Dave browsing permissions + ara.addPermission(dave, browsePerm); + + // remove permissions granted to Bob + ara.removePermission(bob, createPerm); + ara.removePermission(bob, commentPerm); + ara.removePermission(bob, votePerm); + } } diff --git a/audit-examples/src/main/java/examples/access/AccessRightsChecker.java b/audit-examples/src/main/java/examples/access/AccessRightsChecker.java index cf61242..e1b3518 100644 --- a/audit-examples/src/main/java/examples/access/AccessRightsChecker.java +++ b/audit-examples/src/main/java/examples/access/AccessRightsChecker.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,81 +20,79 @@ /** * As the name indicates, checks whether a user possesses a given permission. - * + * * AccessRightsChecker is also a stand-alone java application, simulating a very * simple and short simulation of invocation of a AccessRightsChecker - * + * * @author Ceki Gulcu */ public class AccessRightsChecker { - /** - * Constant used to identify this application. - */ - static String ACCESS_RIGHTS_CHECKER_APPLICATION_NAME = "AccessRightsChecker"; - - /* - * The permissionMap used internally by AccessRightsChecker - */ - final PermissionMap permissionMap; - - public AccessRightsChecker(PermissionMap permissionMap) { - this.permissionMap = permissionMap; - } - - /** - * Does the user have the permission passed as parameter? - * - * @param user the user to check against - * @param permission the permission to check - * @return true if the user has the permission, false otherwise. - * @throws AccessException - * thrown if there is a problem checking user permissions - */ - public boolean hasPermission(User user, Permission permission) - throws AccessException { - boolean allowed = permissionMap.hasPermission(user, permission); - if (!allowed) { - AuditorFacade auditorFacade = new AuditorFacade(user.getName(), - "ACCESS_DENIED", permission.getName()); - AuditHelper.audit(auditorFacade); - } - return allowed; - } - - public static void main(String[] args) throws AuditException, AccessException { - // Initialize logback-audit framework with the file - // AccessRightsChecker/logback-audit.xml - AuditorFactory.setApplicationName(ACCESS_RIGHTS_CHECKER_APPLICATION_NAME); - - // create an empty PermissionMap - PermissionMap pm = new PermissionMap(); - - // Create users Bob, Carol and Dave - User bob = new User("Bob"); - User carol = new User("Carol"); - User dave = new User("Dave"); - - // create a browse permission - Permission browsePerm = new Permission("browse"); - - // grant Dave browse permission - pm.addPermission(dave, browsePerm); - - // create an AccessRightsChecker with the permissionMap - // just instantiated - AccessRightsChecker arc = new AccessRightsChecker(pm); - - // Bob does not have browse permissions. Thus, the call - // will be audited. - arc.hasPermission(bob, browsePerm); - - // Carol does not have browse permissions. Thus, the call - // will be audited. - arc.hasPermission(carol, browsePerm); - - // Dave does have browse permissions - arc.hasPermission(dave, browsePerm); - - } + /** + * Constant used to identify this application. + */ + static String ACCESS_RIGHTS_CHECKER_APPLICATION_NAME = "AccessRightsChecker"; + + /* + * The permissionMap used internally by AccessRightsChecker + */ + final PermissionMap permissionMap; + + public AccessRightsChecker(final PermissionMap permissionMap) { + this.permissionMap = permissionMap; + } + + /** + * Does the user have the permission passed as parameter? + * + * @param user the user to check against + * @param permission the permission to check + * @return true if the user has the permission, false otherwise. + * @throws AccessException thrown if there is a problem checking user + * permissions + */ + public boolean hasPermission(final User user, final Permission permission) throws AccessException { + final boolean allowed = permissionMap.hasPermission(user, permission); + if (!allowed) { + final AuditorFacade auditorFacade = new AuditorFacade(user.getName(), "ACCESS_DENIED", + permission.getName()); + AuditHelper.audit(auditorFacade); + } + return allowed; + } + + public static void main(final String[] args) throws AuditException, AccessException { + // Initialize logback-audit framework with the file + // AccessRightsChecker/logback-audit.xml + AuditorFactory.setApplicationName(ACCESS_RIGHTS_CHECKER_APPLICATION_NAME); + + // create an empty PermissionMap + final PermissionMap pm = new PermissionMap(); + + // Create users Bob, Carol and Dave + final User bob = new User("Bob"); + final User carol = new User("Carol"); + final User dave = new User("Dave"); + + // create a browse permission + final Permission browsePerm = new Permission("browse"); + + // grant Dave browse permission + pm.addPermission(dave, browsePerm); + + // create an AccessRightsChecker with the permissionMap + // just instantiated + final AccessRightsChecker arc = new AccessRightsChecker(pm); + + // Bob does not have browse permissions. Thus, the call + // will be audited. + arc.hasPermission(bob, browsePerm); + + // Carol does not have browse permissions. Thus, the call + // will be audited. + arc.hasPermission(carol, browsePerm); + + // Dave does have browse permissions + arc.hasPermission(dave, browsePerm); + } } diff --git a/audit-examples/src/main/java/examples/access/AuditHelper.java b/audit-examples/src/main/java/examples/access/AuditHelper.java index 9c8f447..3f0e844 100644 --- a/audit-examples/src/main/java/examples/access/AuditHelper.java +++ b/audit-examples/src/main/java/examples/access/AuditHelper.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -17,19 +17,18 @@ import ch.qos.logback.audit.AuditException; import ch.qos.logback.audit.client.AuditorFacade; - /** - * - * + * + * * @author Ceki Gulcu */ public class AuditHelper { - static void audit(AuditorFacade auditorFacade) throws AccessException { - try { - auditorFacade.audit(); - } catch (AuditException e) { - throw new AccessException("Audit failure", e); - } - } + static void audit(final AuditorFacade auditorFacade) throws AccessException { + try { + auditorFacade.audit(); + } catch (final AuditException e) { + throw new AccessException("Audit failure", e); + } + } } diff --git a/audit-examples/src/main/java/examples/access/Permission.java b/audit-examples/src/main/java/examples/access/Permission.java index 8c03cab..b64ad58 100644 --- a/audit-examples/src/main/java/examples/access/Permission.java +++ b/audit-examples/src/main/java/examples/access/Permission.java @@ -1,55 +1,51 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package examples.access; +import java.util.Objects; + public class Permission { - final String name; - - public Permission(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Permission other = (Permission) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - + final String name; + + public Permission(final String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final Permission other = (Permission) obj; + if (!Objects.equals(name, other.name)) { + return false; + } + return true; + } + } diff --git a/audit-examples/src/main/java/examples/access/PermissionMap.java b/audit-examples/src/main/java/examples/access/PermissionMap.java index be35053..9f06db8 100644 --- a/audit-examples/src/main/java/examples/access/PermissionMap.java +++ b/audit-examples/src/main/java/examples/access/PermissionMap.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,32 +18,21 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; public class PermissionMap { - Map> map = new HashMap>(); + Map> map = new HashMap<>(); - void addPermission(User u, Permission p) { - List permissionList = map.get(u.getName()); - if (permissionList == null) { - permissionList = new ArrayList(); - } - permissionList.add(p); - } + void addPermission(final User u, final Permission p) { + Objects.>requireNonNullElse(map.get(u.getName()), new ArrayList<>()).add(p); + } - void removePermission(User u, Permission p) { - List permissionList = map.get(u.getName()); - if (permissionList == null) { - return; - } - permissionList.remove(p); - } + void removePermission(final User u, final Permission p) { + Objects.>requireNonNullElse(map.get(u.getName()), new ArrayList<>()).remove(p); + } - boolean hasPermission(User u, Permission p) { - List permissionList = map.get(u.getName()); - if (permissionList == null) { - return false; - } - return permissionList.contains(p); - } + boolean hasPermission(final User u, final Permission p) { + return Objects.>requireNonNullElse(map.get(u.getName()), new ArrayList<>()).contains(p); + } } diff --git a/audit-examples/src/main/java/examples/access/User.java b/audit-examples/src/main/java/examples/access/User.java index c2ddbd8..4ef9ed9 100644 --- a/audit-examples/src/main/java/examples/access/User.java +++ b/audit-examples/src/main/java/examples/access/User.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -16,15 +16,14 @@ public class User { - String name; - - public User(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - + String name; + + public User(final String name) { + this.name = name; + } + + public String getName() { + return name; + } + } diff --git a/audit-server-generator/pom.xml b/audit-server-generator/pom.xml index 7115738..e53ce73 100644 --- a/audit-server-generator/pom.xml +++ b/audit-server-generator/pom.xml @@ -1,48 +1,48 @@ + - - 4.0.0 + 4.0.0 - ch.qos.logback - audit-server-generator - pom - audit-server-generator - 0.5-SNAPSHOT + ch.qos.logback + audit-server-generator + pom + audit-server-generator + 0.7-SNAPSHOT - - - - org.apache.maven.plugins - maven-antrun-plugin - - - compile - generate-resources - - - - - - - - - run - - - - - - ant - ant-antlr - 1.6.5 - - - antlr - antlrall - 2.7.4 - - - - - + + + + org.apache.maven.plugins + maven-antrun-plugin + + + compile + generate-resources + + + + + + + + + run + + + + + + ant + ant-antlr + + + antlr + antlrall + + + + + \ No newline at end of file diff --git a/audit-server/pom.xml b/audit-server/pom.xml index f08e4e6..77d9e33 100755 --- a/audit-server/pom.xml +++ b/audit-server/pom.xml @@ -1,15 +1,16 @@ - - + + ch.qos.logback audit-parent - 0.6 + 0.7-SNAPSHOT 4.0.0 - ch.qos.logback audit-server jar Logback Audit Server Runtime @@ -48,26 +49,19 @@ logback-core provided - + ch.qos.logback logback-classic test - + hsqldb hsqldb - 1.8.0.7 @@ -101,11 +95,8 @@ 1.0 - - - @@ -123,16 +114,6 @@ - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - diff --git a/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventDAO.java b/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventDAO.java index 2f1656d..8a49782 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventDAO.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventDAO.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -28,83 +28,79 @@ import ch.qos.logback.audit.AuditEvent; public class AuditEventDAO extends Persistor { - - final static String AE_CLASS = AuditEvent.class.getName(); - - static public AuditEvent findById(Long id) throws HibernateException { - Session s = null; - try { - s = openSession(); - return (AuditEvent) s.get(AuditEvent.class, id); - } finally { - close(s); - } - } - - @SuppressWarnings("unchecked") - static public List findAll() throws HibernateException { - Session s = null; - try { - s = openSession(); - Criteria criteria = s.createCriteria(AuditEvent.class); - return criteria.list(); - } finally { - close(s); - } - } - - // SELECT grp.subject_count, grp.subject FROM - // (SELECT count(subject) as subject_count, subject from audit_event GROUP BY - // subject) AS grp - // ORDER BY grp.subject_count DESC; - - @SuppressWarnings("unchecked") - static public List findMaxSubject() throws HibernateException { - Session s = null; - try { - s = openSession(); - -// Query q = s.createQuery("select grp.sc, grp.sub from ( " + -// -// " select count(subject) as sub, subject from " -// + AuditEvent.class.getName() + " GROUP BY subject) AS grp"); - - Query q = s.createQuery("select count(ae.subject), ae.subject FROM "+ AE_CLASS + " AS ae "+ - "GROUP BY ae.subject ORDER BY count(ae.subject) desc"); - ScrollableResults sr = q.scroll(); - List l = new ArrayList(); - int i = 0; - while(sr.next()) { - System.out.println(i++); - Object[] oa = sr.get(); - l.add(oa); - } - - return l; - } finally { - close(s); - } - } - - @SuppressWarnings("unchecked") - static public List findMaxObject() throws HibernateException { - Session s = null; - try { - s = openSession(); - - //Query q = s.createQuery("select count(ae.subject), ae.subject FROM "+ AE_CLASS + " AS ae "+ - //"GROUP BY ae.subject ORDER BY count(ae.subject) desc"); - - Criteria crit = s.createCriteria(AuditEvent.class); - crit.setProjection(Projections.projectionList() - .add(Projections.count("object").as("gcount")) - .add(Projections.groupProperty("object")) - ); - crit.addOrder(Order.desc("gcount")); - crit.setMaxResults(10); - return crit.list(); - } finally { - close(s); - } - } + + final static String AE_CLASS = AuditEvent.class.getName(); + + static public AuditEvent findById(final Long id) throws HibernateException { + Session s = null; + try { + s = openSession(); + return (AuditEvent) s.get(AuditEvent.class, id); + } finally { + close(s); + } + } + + static public List findAll() throws HibernateException { + Session s = null; + try { + s = openSession(); + final Criteria criteria = s.createCriteria(AuditEvent.class); + return criteria.list(); + } finally { + close(s); + } + } + + // SELECT grp.subject_count, grp.subject FROM + // (SELECT count(subject) as subject_count, subject from audit_event GROUP BY + // subject) AS grp + // ORDER BY grp.subject_count DESC; + + static public List findMaxSubject() throws HibernateException { + Session s = null; + try { + s = openSession(); + + // Query q = s.createQuery("select grp.sc, grp.sub from ( " + + // + // " select count(subject) as sub, subject from " + // + AuditEvent.class.getName() + " GROUP BY subject) AS grp"); + + final Query q = s.createQuery("select count(ae.subject), ae.subject FROM " + AE_CLASS + " AS ae " + + "GROUP BY ae.subject ORDER BY count(ae.subject) desc"); + final ScrollableResults sr = q.scroll(); + final List l = new ArrayList<>(); + int i = 0; + while (sr.next()) { + System.out.println(i++); + final Object[] oa = sr.get(); + l.add(oa); + } + + return l; + } finally { + close(s); + } + } + + static public List findMaxObject() throws HibernateException { + Session s = null; + try { + s = openSession(); + + // Query q = s.createQuery("select count(ae.subject), ae.subject FROM "+ + // AE_CLASS + " AS ae "+ + // "GROUP BY ae.subject ORDER BY count(ae.subject) desc"); + + final Criteria crit = s.createCriteria(AuditEvent.class); + crit.setProjection(Projections.projectionList().add(Projections.count("object").as("gcount")) + .add(Projections.groupProperty("object"))); + crit.addOrder(Order.desc("gcount")); + crit.setMaxResults(10); + return crit.list(); + } finally { + close(s); + } + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventShaper.java b/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventShaper.java index 7f1dbd1..88dd4a1 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventShaper.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/persistent/AuditEventShaper.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -17,17 +17,15 @@ import ch.qos.logback.audit.AuditEvent; /** - * Shapes audit event so that they are compatible with the - * target RDBMS. - * + * Shapes audit event so that they are compatible with the target RDBMS. + * * @author ceki * */ public interface AuditEventShaper { - - /** - * Shape auditEvent so that it is compatible with the target RDBMS. - * */ - public void shape(AuditEvent auditEvent); + /** + * Shape auditEvent so that it is compatible with the target RDBMS. + */ + void shape(AuditEvent auditEvent); } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/persistent/NullAEShaper.java b/audit-server/src/main/java/ch/qos/logback/audit/persistent/NullAEShaper.java index 291b502..3251749 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/persistent/NullAEShaper.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/persistent/NullAEShaper.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,8 +18,9 @@ public class NullAEShaper implements AuditEventShaper { - public void shape(AuditEvent auditEvent) { - // NOP - } + @Override + public void shape(final AuditEvent auditEvent) { + // NOP + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/persistent/Persistor.java b/audit-server/src/main/java/ch/qos/logback/audit/persistent/Persistor.java index dbf77f5..b754c5d 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/persistent/Persistor.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/persistent/Persistor.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -27,203 +27,197 @@ /** * Base functionality "class" for all Persistor classes - this class only * bundles static functions, has no members nor methods. - * + * * Persistor includes functions to create or retrieve a Hibernate * SessionFactory, and functions to open, close or rollback sessions. - * + * * @author Ceki Gülcü */ public class Persistor { - // static Logger staticLogger = LoggerFactory.getLogger(Persistor.class); - static SessionFactory sessionFactory; - static Configuration cfg; - static Object cfgLock; - static Logger logger = LoggerFactory.getLogger(Persistor.class); - - /** - * Create or re-obtain our single Hibernate SessionFactory. - * - * @return An instantiated SessionFactory, always the same (the created - * instance is cached in this class). - * @throws HibernateException - */ - private static SessionFactory getSessionFactory() throws HibernateException { - if (sessionFactory == null) { - // Double-locked synchronization pattern - synchronized (SessionFactory.class) { - if (sessionFactory == null) { - sessionFactory = createSessionFactory(); - } - } - } - return sessionFactory; - } - - static public Configuration createConfiguration() { - final Configuration cfg = new Configuration(); - - // Configure Hibernate mappings,this will look for the "hbm.xml" resources. - // In alphabetical order: - cfg.addClass(AuditEvent.class); - - return cfg; - } - - public static void setConfiguration(Configuration cfg, Object lock) { - // set the lock if not set previously - if (Persistor.cfgLock == null && lock != null) { - Persistor.cfgLock = lock; - } - if (Persistor.cfgLock == null || Persistor.cfgLock.equals(lock)) { - Persistor.cfg = cfg; - } else if (Persistor.cfg == null) { - Persistor.cfg = cfg; - } else { - throw new IllegalStateException("Configuration was already set."); - } - } - - public static void resetConfiguration(Object lock) { - if (Persistor.cfgLock == null || Persistor.cfgLock.equals(lock)) { - Persistor.cfg = null; - if (Persistor.sessionFactory != null) { - try { - Persistor.sessionFactory.close(); - } catch (HibernateException he) { - logger.error("Warn failed to close session factory", he); - } - } - Persistor.sessionFactory = null; - - } - } - - static SessionFactory createSessionFactory() { - if (cfg == null) { - throw new IllegalStateException("Configuration must be set before usage."); - } - return cfg.buildSessionFactory(); - } - - /** - * Open an Hibernate Session. - * - * @return A valid Session instance, never null. - * @throws HibernateException - * In case the session could not be created. - */ - protected static Session openSession() throws HibernateException { - final SessionFactory sessionFactory = getSessionFactory(); - return sessionFactory.openSession(); - } - - protected static void update(Object o) throws HibernateException { - Session s = null; - Transaction tx = null; - try { - s = openSession(); - tx = s.beginTransaction(); - s.update(o); - tx.commit(); - } catch (HibernateException he) { - if (tx != null) { - tx.rollback(); - } - throw he; - } finally { - close(s, tx); - } - } - - public static void save(Object o) throws HibernateException { - Session s = null; - Transaction tx = null; - try { - s = openSession(); - tx = s.beginTransaction(); - s.save(o); - tx.commit(); - } catch (HibernateException he) { - logger.error("Failed to save object", he); - if (tx != null) { - tx.rollback(); - } - throw he; - } finally { - close(s, tx); - } - } - - static private Logger getStaticLogger() { - return LoggerFactory.getLogger(Persistor.class); - } - - public static void delete(Object o) throws HibernateException { - Session s = null; - Transaction tx = null; - try { - s = openSession(); - tx = s.beginTransaction(); - s.delete(o); - tx.commit(); - } catch (HibernateException he) { - if (tx != null) { - tx.rollback(); - } - throw he; - } finally { - close(s, tx); - } - } - - /** - * Close a Hibernate Session. - * - * @param theHibernateSession - * The open session to close. - * - * In case of a problem, this method will log an error but won't propagate any - * exception - therefore it may be used safely in a finally{} block. - * - */ - protected static void close(Session theHibernateSession) { - try { - if (theHibernateSession != null) { - theHibernateSession.close(); - } - } catch (Exception e) { - getStaticLogger().error("Failed to close session " + theHibernateSession, - e); - } - } - - /** - * Rollback a Hibernate transaction and close the session. - * - * In case of a problem, this method will log an error but won't propagate any - * exception - therefore it may be used safely in a finally{} block. - * - * @param theHibernateSession - * The open session to rollback and close. - * @param tx - */ - protected static void close(Session theHibernateSession, Transaction tx) { - try { - if ((tx != null) && (tx.isActive() && !tx.wasCommitted())) { - tx.rollback(); - } - } catch (HibernateException he) { - getStaticLogger().error("Could not rollback transaction" + tx); - } - - try { - if (theHibernateSession != null) { - theHibernateSession.close(); - } - } catch (Exception e) { - getStaticLogger().error("Failed to close session " + theHibernateSession, - e); - } - } + // static Logger staticLogger = LoggerFactory.getLogger(Persistor.class); + static SessionFactory sessionFactory; + static Configuration cfg; + static Object cfgLock; + static Logger logger = LoggerFactory.getLogger(Persistor.class); + + /** + * Create or re-obtain our single Hibernate SessionFactory. + * + * @return An instantiated SessionFactory, always the same (the created instance + * is cached in this class). + * @throws HibernateException + */ + private static SessionFactory getSessionFactory() throws HibernateException { + if (sessionFactory == null) { + // Double-locked synchronization pattern + synchronized (SessionFactory.class) { + if (sessionFactory == null) { + sessionFactory = createSessionFactory(); + } + } + } + return sessionFactory; + } + + static public Configuration createConfiguration() { + final Configuration cfg = new Configuration(); + + // Configure Hibernate mappings,this will look for the "hbm.xml" resources. + // In alphabetical order: + cfg.addClass(AuditEvent.class); + + return cfg; + } + + public static void setConfiguration(final Configuration cfg, final Object lock) { + // set the lock if not set previously + if (Persistor.cfgLock == null && lock != null) { + Persistor.cfgLock = lock; + } + if (Persistor.cfgLock != null && !Persistor.cfgLock.equals(lock) && Persistor.cfg != null) { + throw new IllegalStateException("Configuration was already set."); + } + Persistor.cfg = cfg; + } + + public static void resetConfiguration(final Object lock) { + if (Persistor.cfgLock == null || Persistor.cfgLock.equals(lock)) { + Persistor.cfg = null; + if (Persistor.sessionFactory != null) { + try { + Persistor.sessionFactory.close(); + } catch (final HibernateException he) { + logger.error("Warn failed to close session factory", he); + } + } + Persistor.sessionFactory = null; + + } + } + + static SessionFactory createSessionFactory() { + if (cfg == null) { + throw new IllegalStateException("Configuration must be set before usage."); + } + return cfg.buildSessionFactory(); + } + + /** + * Open an Hibernate Session. + * + * @return A valid Session instance, never null. + * @throws HibernateException In case the session could not be created. + */ + protected static Session openSession() throws HibernateException { + final SessionFactory sessionFactory = getSessionFactory(); + return sessionFactory.openSession(); + } + + protected static void update(final Object o) throws HibernateException { + Session s = null; + Transaction tx = null; + try { + s = openSession(); + tx = s.beginTransaction(); + s.update(o); + tx.commit(); + } catch (final HibernateException he) { + if (tx != null) { + tx.rollback(); + } + throw he; + } finally { + close(s, tx); + } + } + + public static void save(final Object o) throws HibernateException { + Session s = null; + Transaction tx = null; + try { + s = openSession(); + tx = s.beginTransaction(); + s.save(o); + tx.commit(); + } catch (final HibernateException he) { + logger.error("Failed to save object", he); + if (tx != null) { + tx.rollback(); + } + throw he; + } finally { + close(s, tx); + } + } + + static private Logger getStaticLogger() { + return LoggerFactory.getLogger(Persistor.class); + } + + public static void delete(final Object o) throws HibernateException { + Session s = null; + Transaction tx = null; + try { + s = openSession(); + tx = s.beginTransaction(); + s.delete(o); + tx.commit(); + } catch (final HibernateException he) { + if (tx != null) { + tx.rollback(); + } + throw he; + } finally { + close(s, tx); + } + } + + /** + * Close a Hibernate Session. + * + * @param theHibernateSession The open session to close. + * + * In case of a problem, this method will log an + * error but won't propagate any exception - + * therefore it may be used safely in a finally{} + * block. + * + */ + protected static void close(final Session theHibernateSession) { + try { + if (theHibernateSession != null) { + theHibernateSession.close(); + } + } catch (final Exception e) { + getStaticLogger().error("Failed to close session " + theHibernateSession, e); + } + } + + /** + * Rollback a Hibernate transaction and close the session. + * + * In case of a problem, this method will log an error but won't propagate any + * exception - therefore it may be used safely in a finally{} block. + * + * @param theHibernateSession The open session to rollback and close. + * @param tx + */ + protected static void close(final Session theHibernateSession, final Transaction tx) { + try { + if (tx != null && tx.isActive() && !tx.wasCommitted()) { + tx.rollback(); + } + } catch (final HibernateException he) { + getStaticLogger().error("Could not rollback transaction" + tx); + } + + try { + if (theHibernateSession != null) { + theHibernateSession.close(); + } + } catch (final Exception e) { + getStaticLogger().error("Failed to close session " + theHibernateSession, e); + } + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/persistent/SQLServerAEShaper.java b/audit-server/src/main/java/ch/qos/logback/audit/persistent/SQLServerAEShaper.java index d01f79c..a119246 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/persistent/SQLServerAEShaper.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/persistent/SQLServerAEShaper.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,45 +20,40 @@ public class SQLServerAEShaper implements AuditEventShaper { + /* + * SQLServer 2005 cannot index varchar columns longer than 900 characters. + */ + static final int MAX_VARCHAR_COL_WIDTH = 900; - /* - * SQLServer 2005 cannot index varchar columns longer than 900 characters. - */ - static final int MAX_VARCHAR_COL_WIDTH = 900; - - public void shape(AuditEvent auditEvent) { - - String subject = auditEvent.getSubject(); - if(tooLong(subject)) { - auditEvent.setSubject(narrow(subject)); - } - - String object = auditEvent.getObject(); - if(tooLong(object)) { - auditEvent.setObject(narrow(object)); - } - - Map predicateMap = auditEvent.getPredicateMap(); - if(predicateMap != null) { - for(String k: predicateMap.keySet()) { - String value = predicateMap.get(k); - if(tooLong(value)) { - predicateMap.put(k, narrow(value)); - } - } - } - } + @Override + public void shape(final AuditEvent auditEvent) { + + final String subject = auditEvent.getSubject(); + if (tooLong(subject)) { + auditEvent.setSubject(narrow(subject)); + } + + final String object = auditEvent.getObject(); + if (tooLong(object)) { + auditEvent.setObject(narrow(object)); + } + + final Map predicateMap = auditEvent.getPredicateMap(); + if (predicateMap != null) { + predicateMap.entrySet().stream().filter(e -> tooLong(e.getValue())) + .forEach(e -> predicateMap.put(e.getKey(), narrow(e.getValue()))); + } + } + + final boolean tooLong(final String in) { + if (in != null && in.length() > MAX_VARCHAR_COL_WIDTH) { + return true; + } + return false; + } + + final String narrow(final String in) { + return in.substring(0, MAX_VARCHAR_COL_WIDTH); + } - final boolean tooLong(String in) { - if(in != null && in.length() > MAX_VARCHAR_COL_WIDTH) { - return true; - } else { - return false; - } - } - - final String narrow(String in) { - return in.substring(0, MAX_VARCHAR_COL_WIDTH); - } - } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandler.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandler.java index ae46e55..5049a5a 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandler.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandler.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -17,12 +17,11 @@ import ch.qos.logback.audit.AuditEvent; import ch.qos.logback.audit.AuditException; - public interface AuditEventHandler { - public void doHandle(AuditEvent ae) throws AuditException; - - public void addAuditListener(AuditListener auditListener); - - public boolean removeAuditListener(AuditListener auditListener); + void doHandle(AuditEvent ae) throws AuditException; + + void addAuditListener(AuditListener auditListener); + + boolean removeAuditListener(AuditListener auditListener); } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandlerBase.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandlerBase.java index 35c02a2..6fd185e 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandlerBase.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventHandlerBase.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,24 +20,25 @@ import ch.qos.logback.audit.AuditEvent; import ch.qos.logback.audit.AuditException; - abstract class AuditEventHandlerBase implements AuditEventHandler { - List auditListenerList = new ArrayList(); - - public void addAuditListener(AuditListener auditListener) { - auditListenerList.add(auditListener); - } - - abstract public void doHandle(AuditEvent ae) throws AuditException; - - protected void fireIncoming(AuditEvent ae) { - for(AuditListener listener: auditListenerList) { - listener.incoming(ae); - } - } - public boolean removeAuditListener(AuditListener auditListener) { - return auditListenerList.remove(auditListener); - } + List auditListenerList = new ArrayList<>(); + + @Override + public void addAuditListener(final AuditListener auditListener) { + auditListenerList.add(auditListener); + } + + @Override + abstract public void doHandle(AuditEvent ae) throws AuditException; + + protected void fireIncoming(final AuditEvent ae) { + auditListenerList.stream().forEach(listener -> listener.incoming(ae)); + } + + @Override + public boolean removeAuditListener(final AuditListener auditListener) { + return auditListenerList.remove(auditListener); + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventPersistor.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventPersistor.java index a020244..89f3dba 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventPersistor.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditEventPersistor.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -15,21 +15,22 @@ package ch.qos.logback.audit.server; import ch.qos.logback.audit.AuditEvent; -import ch.qos.logback.audit.persistent.AuditEventDAO; import ch.qos.logback.audit.persistent.AuditEventShaper; +import ch.qos.logback.audit.persistent.Persistor; public class AuditEventPersistor extends AuditEventHandlerBase { - final AuditEventShaper eventShaper; - - public AuditEventPersistor(AuditEventShaper eventShaper) { - this.eventShaper = eventShaper; - } - - public void doHandle(AuditEvent ae) { - eventShaper.shape(ae); - AuditEventDAO.save(ae); - fireIncoming(ae); - } + final AuditEventShaper eventShaper; + + public AuditEventPersistor(final AuditEventShaper eventShaper) { + this.eventShaper = eventShaper; + } + + @Override + public void doHandle(final AuditEvent ae) { + eventShaper.shape(ae); + Persistor.save(ae); + fireIncoming(ae); + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditListener.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditListener.java index dc437b6..8a94f89 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditListener.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditListener.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,6 +18,6 @@ public interface AuditListener { - public void incoming(AuditEvent ae); - + void incoming(AuditEvent ae); + } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServer.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServer.java index 712194b..7c9b152 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServer.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServer.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -27,89 +27,89 @@ public class AuditServer extends Thread { - static Logger logger = LoggerFactory.getLogger(AuditServer.class); - - final int port; - final AuditEventHandler auditEventHandler; - boolean closed = false; - boolean serverSocketSucessfullyOpened = false; - ServerSocket serverSocket; - List socketNodeList = new ArrayList(); - - public AuditServer(int port, AuditEventHandler auditEventHandler) { - super(); - this.port = port; - this.auditEventHandler = auditEventHandler; - } - - public void run() { - try { - logger.info("Listening on port " + port); - serverSocket = new ServerSocket(port); - serverSocketSucessfullyOpened = true; - while (!closed) { - logger.info("Waiting to accept a new client."); - Socket socket = serverSocket.accept(); - InetAddress inetAddress = socket.getInetAddress(); - logger.info("Connected to client at " + inetAddress); - - logger.info("Starting new socket node."); - SocketNode newSocketNode = new SocketNode(this, socket, auditEventHandler); - // don't allow simultaneous access to the socketNodeList - // (e.g. removal whole iterating on the list causes - // java.util.ConcurrentModificationException - synchronized (socketNodeList) { - socketNodeList.add(newSocketNode); - } - - new Thread(newSocketNode).start(); - } - } catch (SocketException e) { - if ("socket closed".equals(e.getMessage())) { - logger.info("Audit server has been closed"); - } else { - logger.info("Caught an SocketException", e); - } - } catch (IOException e) { - logger.info("Caught an IOException", e); - } catch (Exception e) { - logger.error("Caught an unexpectged exception.", e); - } - } - - void socketNodeClosing(SocketNode sn) { - logger.debug("Removing {}", sn); - - // don't allow simultaneous access to the socketNodeList - // (e.g. removal whole iterating on the list causes - // java.util.ConcurrentModificationException - synchronized (socketNodeList) { - socketNodeList.remove(sn); - } - } - - public void close() { - closed = true; - if (serverSocket != null) { - try { - serverSocket.close(); - } catch (IOException e) { - logger.error("Failed to close serverSocket", e); - } - } - - // don't allow simultaneous access to the socketNodeList - // (e.g. removal whole iterating on the list causes - // java.util.ConcurrentModificationException - synchronized (socketNodeList) { - for(SocketNode sn: socketNodeList) { - sn.close(); - } - } - - } - - public boolean isServerSocketSucessfullyOpened() { - return serverSocketSucessfullyOpened; - } + static Logger logger = LoggerFactory.getLogger(AuditServer.class); + + final int port; + final AuditEventHandler auditEventHandler; + boolean closed = false; + boolean serverSocketSucessfullyOpened = false; + ServerSocket serverSocket; + List socketNodeList = new ArrayList<>(); + + public AuditServer(final int port, final AuditEventHandler auditEventHandler) { + this.port = port; + this.auditEventHandler = auditEventHandler; + } + + @Override + public void run() { + try { + logger.info("Listening on port " + port); + serverSocket = new ServerSocket(port); + serverSocketSucessfullyOpened = true; + while (!closed) { + logger.info("Waiting to accept a new client."); + final Socket socket = serverSocket.accept(); + final InetAddress inetAddress = socket.getInetAddress(); + logger.info("Connected to client at " + inetAddress); + + logger.info("Starting new socket node."); + final SocketNode newSocketNode = new SocketNode(this, socket, auditEventHandler); + // don't allow simultaneous access to the socketNodeList + // (e.g. removal whole iterating on the list causes + // java.util.ConcurrentModificationException + synchronized (socketNodeList) { + socketNodeList.add(newSocketNode); + } + + new Thread(newSocketNode).start(); + } + } catch (final SocketException e) { + if ("socket closed".equals(e.getMessage())) { + logger.info("Audit server has been closed"); + } else { + logger.info("Caught an SocketException", e); + } + } catch (final IOException e) { + logger.info("Caught an IOException", e); + } catch (final Exception e) { + logger.error("Caught an unexpectged exception.", e); + } + } + + void socketNodeClosing(final SocketNode sn) { + logger.debug("Removing {}", sn); + + // don't allow simultaneous access to the socketNodeList + // (e.g. removal whole iterating on the list causes + // java.util.ConcurrentModificationException + synchronized (socketNodeList) { + socketNodeList.remove(sn); + } + } + + public void close() { + closed = true; + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (final IOException e) { + logger.error("Failed to close serverSocket", e); + } + } + + // don't allow simultaneous access to the socketNodeList + // (e.g. removal whole iterating on the list causes + // java.util.ConcurrentModificationException + synchronized (socketNodeList) { + for (final SocketNode sn : socketNodeList) { + sn.close(); + } + } + + } + + public boolean isServerSocketSucessfullyOpened() { + return serverSocketSucessfullyOpened; + } } \ No newline at end of file diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServerConstants.java b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServerConstants.java index d373f1a..141ee0d 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServerConstants.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/AuditServerConstants.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -18,23 +18,21 @@ public class AuditServerConstants { - public static final SimpleDateFormat ISODATE_SDF = new SimpleDateFormat("yyyy-MM-dd'T'HHmmss"); - public static final String PORT_INIT_PARAM = "PORT"; - public static final String RDBMS_DIALECT_INIT_PARAM = "RDBMS_DIALECT"; - - public static final int DEFAULT_PORT = 9630; - public static final String AUDIT_SERVER_REFERENCE = "AUDIT_SERVER_REFERENCE"; + public static final SimpleDateFormat ISODATE_SDF = new SimpleDateFormat("yyyy-MM-dd'T'HHmmss"); + public static final String PORT_INIT_PARAM = "PORT"; + public static final String RDBMS_DIALECT_INIT_PARAM = "RDBMS_DIALECT"; - public static final String SQLSERVER_2005_DIALECT_VALUE ="SQLSERVER_2005"; - - - - // maximum length of persisted fields - public static final int SUBJECT_FIELD_MAX_LENGTH = 1024; - public static final int VERB_FIELD_MAX_LENGTH = 64; - public static final int OBJECT_FIELD_MAX_LENGTH = 4096; - public static final int APPLICATION_NAME_FIELD_MAX_LENGTH = VERB_FIELD_MAX_LENGTH; - public static final int IP_ADDRESS_FIELD_MAX_LENGTH = 48; - public static final int PREDICATE_KEY_FIELD_MAX_LENGTH = VERB_FIELD_MAX_LENGTH; - public static final int PREDICATE_VALUE_FIELD_MAX_LENGTH = OBJECT_FIELD_MAX_LENGTH; + public static final int DEFAULT_PORT = 9630; + public static final String AUDIT_SERVER_REFERENCE = "AUDIT_SERVER_REFERENCE"; + + public static final String SQLSERVER_2005_DIALECT_VALUE = "SQLSERVER_2005"; + + // maximum length of persisted fields + public static final int SUBJECT_FIELD_MAX_LENGTH = 1024; + public static final int VERB_FIELD_MAX_LENGTH = 64; + public static final int OBJECT_FIELD_MAX_LENGTH = 4096; + public static final int APPLICATION_NAME_FIELD_MAX_LENGTH = VERB_FIELD_MAX_LENGTH; + public static final int IP_ADDRESS_FIELD_MAX_LENGTH = 48; + public static final int PREDICATE_KEY_FIELD_MAX_LENGTH = VERB_FIELD_MAX_LENGTH; + public static final int PREDICATE_VALUE_FIELD_MAX_LENGTH = OBJECT_FIELD_MAX_LENGTH; } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/ServletContextListener.java b/audit-server/src/main/java/ch/qos/logback/audit/server/ServletContextListener.java index dc77938..29a5df9 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/ServletContextListener.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/ServletContextListener.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -29,55 +29,51 @@ import ch.qos.logback.audit.persistent.SQLServerAEShaper; import ch.qos.logback.audit.server.helper.ResourceUtil; -public class ServletContextListener implements - javax.servlet.ServletContextListener { +public class ServletContextListener implements javax.servlet.ServletContextListener { - Logger logger = LoggerFactory.getLogger(ServletContextListener.class); - String applicationName; - Object lock = new Object(); - AuditServer auditServer; - - public void contextDestroyed(ServletContextEvent sce) { - logger.info("Resetting configuration"); - Persistor.resetConfiguration(lock); - auditServer.close(); - } + Logger logger = LoggerFactory.getLogger(ServletContextListener.class); + String applicationName; + Object lock = new Object(); + AuditServer auditServer; - public void contextInitialized(ServletContextEvent sce) { - logger.debug("ContextListener.contextInitialized called"); - ServletContext servletContext = sce.getServletContext(); - String portStr = servletContext - .getInitParameter(AuditServerConstants.PORT_INIT_PARAM); - if (portStr == null || "".equals(portStr)) { - logger.error("The PORT argument was not set in web.xml. Aborting"); - return; - } - int port = Integer.parseInt(portStr); + @Override + public void contextDestroyed(final ServletContextEvent sce) { + logger.info("Resetting configuration"); + Persistor.resetConfiguration(lock); + auditServer.close(); + } - AuditEventShaper auditEventShaper; - String rdbmsDialect = servletContext - .getInitParameter(AuditServerConstants.RDBMS_DIALECT_INIT_PARAM); - if (AuditServerConstants.SQLSERVER_2005_DIALECT_VALUE - .equalsIgnoreCase(rdbmsDialect)) { - logger.info("Will shape events accord to SQL Server 2005 requirements"); - auditEventShaper = new SQLServerAEShaper(); - } else { - auditEventShaper = new NullAEShaper(); - } + @Override + public void contextInitialized(final ServletContextEvent sce) { + logger.debug("ContextListener.contextInitialized called"); + final ServletContext servletContext = sce.getServletContext(); + final String portStr = servletContext.getInitParameter(AuditServerConstants.PORT_INIT_PARAM); + if (portStr == null || "".equals(portStr)) { + logger.error("The PORT argument was not set in web.xml. Aborting"); + return; + } + final int port = Integer.parseInt(portStr); - applicationName = servletContext.getServletContextName(); - logger.debug("applicationName={}", applicationName); - Configuration cfg = Persistor.createConfiguration(); - ResourceUtil.setApplicationName(applicationName); - Properties props = ResourceUtil.getProps(applicationName - + "/hibernate.properties"); + AuditEventShaper auditEventShaper; + final String rdbmsDialect = servletContext.getInitParameter(AuditServerConstants.RDBMS_DIALECT_INIT_PARAM); + if (AuditServerConstants.SQLSERVER_2005_DIALECT_VALUE.equalsIgnoreCase(rdbmsDialect)) { + logger.info("Will shape events accord to SQL Server 2005 requirements"); + auditEventShaper = new SQLServerAEShaper(); + } else { + auditEventShaper = new NullAEShaper(); + } - cfg.setProperties(props); + applicationName = servletContext.getServletContextName(); + logger.debug("applicationName={}", applicationName); + final Configuration cfg = Persistor.createConfiguration(); + ResourceUtil.setApplicationName(applicationName); + final Properties props = ResourceUtil.getProps(applicationName + "/hibernate.properties"); - Persistor.setConfiguration(cfg, lock); - auditServer = new AuditServer(port, new AuditEventPersistor(auditEventShaper)); - auditServer.start(); - servletContext.setAttribute(AuditServerConstants.AUDIT_SERVER_REFERENCE, - auditServer); - } + cfg.setProperties(props); + + Persistor.setConfiguration(cfg, lock); + auditServer = new AuditServer(port, new AuditEventPersistor(auditEventShaper)); + auditServer.start(); + servletContext.setAttribute(AuditServerConstants.AUDIT_SERVER_REFERENCE, auditServer); + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/SocketNode.java b/audit-server/src/main/java/ch/qos/logback/audit/server/SocketNode.java index cc9279a..8a8dcf2 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/SocketNode.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/SocketNode.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -26,104 +26,103 @@ public class SocketNode implements Runnable { - final AuditServer auditServer; - final Socket socket; - final AuditEventHandler aeh; - - ObjectOutputStream oos; - ObjectInputStream ois; - int writeCount = 0; - boolean closed = false; - - static final int RESET_FREQUENCY = 1000; - - static Logger logger = (Logger) LoggerFactory.getLogger(SocketNode.class); - - public SocketNode(AuditServer auditServer, Socket socket, - AuditEventHandler aeh) { - this.auditServer = auditServer; - this.socket = socket; - this.aeh = aeh; - - try { - ois = new ObjectInputStream(socket.getInputStream()); - oos = new ObjectOutputStream(socket.getOutputStream()); - } catch (Exception e) { - logger.error("Could not open ObjectInputStream to " + socket, e); - } - } - - void close() { - if(closed) { - return; - } - closed = true; - if (ois != null) { - try { - ois.close(); - ois = null; - } catch (IOException e) { - logger.warn("While in close method caught: " + e.getMessage()); - } - } - } - - public void run() { - AuditEvent event = null; - - // try { - while (!closed) { - // read an event from the wire - try { - event = (AuditEvent) ois.readObject(); - - } catch (java.io.EOFException e) { - logger.info("Caught java.io.EOFException closing connection."); - break; - } catch (IOException e) { - logger.info("Caught: "+e.getMessage()); - break; - } catch (ClassNotFoundException e) { - logger.error("Unexpected ClassNotFoundException.", e); - writeResponse(e); - break; - } - - Object outgoingObject; - try { - aeh.doHandle(event); - outgoingObject = new Boolean(true); - } catch (Exception e) { - logger.error("Problem while handling audit event", e); - outgoingObject = e; - } - - logger.trace("Outgoing object is {}", outgoingObject); - writeResponse(outgoingObject); - - } - auditServer.socketNodeClosing(this); - } - - private void writeResponse(Object outgoingObject) { - try { - if (writeCount++ >= RESET_FREQUENCY) { - writeCount = 0; - System.out.print("r"); - oos.reset(); - } - oos.writeObject(outgoingObject); - } catch (IOException e) { - logger.error("Failed to send acknowledgement", e); - } - } - - @Override - public String toString() { - if (socket != null) { - return "SocketNode to " + socket.getRemoteSocketAddress(); - } else { - return "SocketNode to null socket"; - } - } + final AuditServer auditServer; + final Socket socket; + final AuditEventHandler aeh; + + ObjectOutputStream oos; + ObjectInputStream ois; + int writeCount = 0; + boolean closed = false; + + static final int RESET_FREQUENCY = 1000; + + static Logger logger = LoggerFactory.getLogger(SocketNode.class); + + public SocketNode(final AuditServer auditServer, final Socket socket, final AuditEventHandler aeh) { + this.auditServer = auditServer; + this.socket = socket; + this.aeh = aeh; + + try { + ois = new ObjectInputStream(socket.getInputStream()); + oos = new ObjectOutputStream(socket.getOutputStream()); + } catch (final Exception e) { + logger.error("Could not open ObjectInputStream to " + socket, e); + } + } + + void close() { + if (closed) { + return; + } + closed = true; + if (ois != null) { + try { + ois.close(); + ois = null; + } catch (final IOException e) { + logger.warn("While in close method caught: " + e.getMessage()); + } + } + } + + @Override + public void run() { + AuditEvent event = null; + + // try { + while (!closed) { + // read an event from the wire + try { + event = (AuditEvent) ois.readObject(); + + } catch (final java.io.EOFException e) { + logger.info("Caught java.io.EOFException closing connection."); + break; + } catch (final IOException e) { + logger.info("Caught: " + e.getMessage()); + break; + } catch (final ClassNotFoundException e) { + logger.error("Unexpected ClassNotFoundException.", e); + writeResponse(e); + break; + } + + Object outgoingObject; + try { + aeh.doHandle(event); + outgoingObject = Boolean.valueOf(true); + } catch (final Exception e) { + logger.error("Problem while handling audit event", e); + outgoingObject = e; + } + + logger.trace("Outgoing object is {}", outgoingObject); + writeResponse(outgoingObject); + + } + auditServer.socketNodeClosing(this); + } + + private void writeResponse(final Object outgoingObject) { + try { + if (writeCount++ >= RESET_FREQUENCY) { + writeCount = 0; + System.out.print("r"); + oos.reset(); + } + oos.writeObject(outgoingObject); + } catch (final IOException e) { + logger.error("Failed to send acknowledgement", e); + } + } + + @Override + public String toString() { + if (socket != null) { + return "SocketNode to " + socket.getRemoteSocketAddress(); + } + return "SocketNode to null socket"; + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/TableCreator.java b/audit-server/src/main/java/ch/qos/logback/audit/server/TableCreator.java index 9613ec3..b4e1c0c 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/TableCreator.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/TableCreator.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -27,44 +27,42 @@ import ch.qos.logback.audit.server.helper.ResourceUtil; /** - * + * * @author Ceki Gulcu */ public class TableCreator { - Logger logger = LoggerFactory.getLogger(TableCreator.class); - Configuration cfg; + Logger logger = LoggerFactory.getLogger(TableCreator.class); + Configuration cfg; - public TableCreator(Configuration cfg) { - this.cfg = cfg; - } + public TableCreator(final Configuration cfg) { + this.cfg = cfg; + } - public void createTables(String filename) { - SchemaExport schemaExport = new SchemaExport(cfg); - boolean printDLL = false; - if (filename != null) { - schemaExport.setOutputFile(filename); - printDLL = true; - } - - schemaExport.create(printDLL, true); - - } + public void createTables(final String filename) { + final SchemaExport schemaExport = new SchemaExport(cfg); + boolean printDLL = false; + if (filename != null) { + schemaExport.setOutputFile(filename); + printDLL = true; + } - public void createTables() { - createTables(null); - } + schemaExport.create(printDLL, true); - - public static void main(String[] args) throws IOException { - Configuration cfg = Persistor.createConfiguration(); + } - Properties props = ResourceUtil.getProps("tmp/hibernate.properties"); - - cfg.setProperties(props); - - TableCreator tc = new TableCreator(cfg); - tc.createTables("src/test/sql/audit_tables.sql-" - + AuditServerConstants.ISODATE_SDF.format(new Date())); - } + public void createTables() { + createTables(null); + } + + public static void main(final String[] args) throws IOException { + final Configuration cfg = Persistor.createConfiguration(); + + final Properties props = ResourceUtil.getProps("tmp/hibernate.properties"); + + cfg.setProperties(props); + + final TableCreator tc = new TableCreator(cfg); + tc.createTables("src/test/sql/audit_tables.sql-" + AuditServerConstants.ISODATE_SDF.format(new Date())); + } } diff --git a/audit-server/src/main/java/ch/qos/logback/audit/server/helper/ResourceUtil.java b/audit-server/src/main/java/ch/qos/logback/audit/server/helper/ResourceUtil.java index 2ddbc26..c849006 100644 --- a/audit-server/src/main/java/ch/qos/logback/audit/server/helper/ResourceUtil.java +++ b/audit-server/src/main/java/ch/qos/logback/audit/server/helper/ResourceUtil.java @@ -1,13 +1,13 @@ /** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 2006-2011, QOS.ch. All rights reserved. - * + * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation - * + * * or (per the licensee's choosing) - * + * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ @@ -20,42 +20,40 @@ public class ResourceUtil { - static String applicationName; - - public static Properties getProps(String path) { - ClassLoader ccl = Thread.currentThread().getContextClassLoader(); - - InputStream is = ccl.getResourceAsStream(path); - if (is == null) { - throw new IllegalStateException("Failed to resource [" + path + "]"); - } - Properties props = new Properties(); - try { - props.load(is); - return props; - } catch (IOException e) { - e.printStackTrace(); - return null; - } finally { - try { - is.close(); - } catch (IOException e) { - - } - } - } - - public static String getApplicationName() { - return applicationName; - } - - public static void setApplicationName(String applicationName) { - if (ResourceUtil.applicationName != null - && !ResourceUtil.applicationName.equals(applicationName)) { - throw new IllegalArgumentException( - "Application name has been already set to [" - + ResourceUtil.applicationName + "]."); - } - ResourceUtil.applicationName = applicationName; - } + static String applicationName; + + public static Properties getProps(final String path) { + final ClassLoader ccl = Thread.currentThread().getContextClassLoader(); + + final InputStream is = ccl.getResourceAsStream(path); + if (is == null) { + throw new IllegalStateException("Failed to resource [" + path + "]"); + } + final Properties props = new Properties(); + try { + props.load(is); + return props; + } catch (final IOException e) { + e.printStackTrace(); + return null; + } finally { + try { + is.close(); + } catch (final IOException e) { + + } + } + } + + public static String getApplicationName() { + return applicationName; + } + + public static void setApplicationName(final String applicationName) { + if (ResourceUtil.applicationName != null && !ResourceUtil.applicationName.equals(applicationName)) { + throw new IllegalArgumentException( + "Application name has been already set to [" + ResourceUtil.applicationName + "]."); + } + ResourceUtil.applicationName = applicationName; + } } diff --git a/audit-site/pom.xml b/audit-site/pom.xml index 5e2a4fc..9dfa197 100755 --- a/audit-site/pom.xml +++ b/audit-site/pom.xml @@ -1,72 +1,72 @@ + + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + ch.qos.logback + audit-parent + 0.7-SNAPSHOT + - - ch.qos.logback - audit-parent - 0.6 - + 4.0.0 + audit-site + jar + Logback Audit Site - 4.0.0 - audit-site - jar - Logback Audit Site + http://audit.qos.ch - http://audit.qos.ch + + + Eclipse Public License - v 1.0 + http://www.eclipse.org/legal/epl-v10.html + - - - Eclipse Public License - v 1.0 - http://www.eclipse.org/legal/epl-v10.html - + + GNU Lesser General Public License + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + + - - GNU Lesser General Public License - http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - - + + + + src/site/pages + + + ../../../target/site + true + + - - - - src/site/pages - - - ../../../target/site - true - - + + + org.apache.maven.plugins + maven-site-plugin + + ${project.parent.basedir}/target/site + - - - org.apache.maven.plugins - maven-site-plugin - - ${project.parent.basedir}/target/site - + + + + + + + + + + + - - - - - - - - - - - + - + + - - - - - + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 34dd8e2..4d7a475 100755 --- a/pom.xml +++ b/pom.xml @@ -1,368 +1,402 @@ + - - 4.0.0 - - ch.qos.logback - audit-parent - 0.6 - pom - Logback Audit Parent - Logback Audit project - - - http://audit.qos.ch - - - audit-common - audit-server - audit-client - audit-examples - audit-site - - - - - Eclipse Public License - v 1.0 - http://www.eclipse.org/legal/epl-v10.html - - - - GNU Lesser General Public License - http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - - - - - https://github.com/qos/logback - git@github.com:qos-ch/logback-audit.git - - - - - ceki - Ceki Gulcu - ceki@qos.ch - - - - - 1.7.2 - 1.0.9 - 2.6.1 - - - - - junit - junit - 3.8.1 - test - - - - - - - - javax.servlet - servlet-api - 2.5 - - - - ch.qos.logback - audit-common - ${project.version} - - - - ch.qos.logback - audit-client - ${project.version} - - - - ch.qos.logback - logback-core - ${logback.version} - - - - ch.qos.logback - logback-classic - ${logback.version} - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - - org.slf4j - slf4j-simple - ${slf4j.version} - - - - - janino - janino - 2.5.10 - - - javax.mail - mail - 1.4 - - - dom4j - dom4j - 1.6.1 - - - hsqldb - hsqldb - 1.8.0.7 - - - - - - - - - org.apache.maven.wagon - wagon-ssh - 2.0 - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.5 - 1.5 - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.6 - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - package - - jar - - - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - true - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.1 - - - - src/main/assembly/dist.xml - - - - logback-audit-${project.version} - - false - target/site/dist/ - - - - - org.apache.maven.plugins - maven-site-plugin - 3.0 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - true - - - http://java.sun.com/j2se/1.5.0/docs/api - - - - - Logback Audit Common - ch.qos.logback.audit - - - Logback Audit Client - - ch.qos.logback.audit.client:ch.qos.logback.audit.client.* - - - - Logback Audit Server - - ch.qos.logback.audit.server:ch.qos.logback.audit.server.* - - - - Examples - examples* - - - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - - examples/*.java - - - - - - - - - - - - - - - - - - - - - - - - - - - license - - - - com.google.code.maven-license-plugin - maven-license-plugin - -
src/main/licenseHeader.txt
- false - true - true - - src/**/*.java - - true - true - - 2006 - - - src/main/javadocHeaders.xml - -
-
-
-
-
- - - javadocjar - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - - attach-javadocs - - jar - - - - - - - - - - sign-artifacts - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.1 - - - sign-artifacts - verify - - sign - - - - - - - - -
- - - - pixie - scp://pixie.qos.ch/var/www/audit.qos.ch/htdocs/ - - - - sonatype-nexus-staging - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + + 4.0.0 + + ch.qos.logback + audit-parent + 0.7-SNAPSHOT + pom + Logback Audit Parent + Logback Audit project + + http://audit.qos.ch + + + audit-common + audit-server + audit-client + audit-examples + audit-site + + + + + Eclipse Public License - v 1.0 + http://www.eclipse.org/legal/epl-v10.html + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + + + + + https://github.com/qos/logback + git@github.com:qos-ch/logback-audit.git + + + + + ceki + Ceki Gulcu + ceki@qos.ch + + + + + 11 + 1.7.2 + 1.0.11 + 2.5.15 + 2.5 + 2.5.10 + 4.13.2 + 1.4 + 1.6.1 + 1.8.1.1 + 2.0 + 2.3.2 + 2.6 + 2.1.2 + 2.8 + 2.1 + 3.0 + 2.8 + 2.3 + 1.6.5 + 2.7.4 + + + + + + + ant + ant-antlr + ${ant-antlr.version} + + + antlr + antlrall + ${antlrall.version} + + + + junit + junit + ${junit.version} + test + + + + javax.servlet + servlet-api + ${servlet-api.version} + + + + ch.qos.logback + audit-common + ${project.version} + + + + ch.qos.logback + audit-client + ${project.version} + + + + ch.qos.logback + logback-core + ${logback.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + + + janino + janino + ${janino.version} + + + javax.mail + mail + ${mail.version} + + + dom4j + dom4j + ${dom4j.version} + + + hsqldb + hsqldb + ${hsqldb.version} + + + + + + + + + org.apache.maven.wagon + wagon-ssh + ${wagon-ssh.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + package + + jar + + + + + + org.apache.maven.plugins + maven-eclipse-plugin + ${maven-eclipse-plugin.version} + + true + + + + + org.apache.maven.plugins + maven-assembly-plugin + ${maven-assembly-plugin.version} + + + src/main/assembly/dist.xml + + + logback-audit-${project.version} + + false + target/site/dist/ + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven-site-plugin.version} + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + true + + https://docs.oracle.com/en/java/javase/11/docs/api/index.html + + + + Logback Audit Common + ch.qos.logback.audit + + + Logback Audit Client + ch.qos.logback.audit.client:ch.qos.logback.audit.client.* + + + Logback Audit Server + ch.qos.logback.audit.server:ch.qos.logback.audit.server.* + + + Examples + examples* + + + + + + + org.apache.maven.plugins + maven-jxr-plugin + ${maven-jxr-plugin.version} + + + examples/*.java + + + + + + + + + + + + + + + + + + + + + + + + + + + license + + + + com.google.code.maven-license-plugin + maven-license-plugin + +
src/main/licenseHeader.txt
+ false + true + true + + src/**/*.java + + true + true + + 2006 + + + src/main/javadocHeaders.xml + +
+
+
+
+
+ + + javadocjar + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + + attach-javadocs + + jar + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.1 + + + sign-artifacts + verify + + sign + + + + + + + + +
+ + + + pixie + scp://pixie.qos.ch/var/www/audit.qos.ch/htdocs/ + + + + sonatype-nexus-staging + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + +