org.productivity.java.syslog4j.server.SyslogServerEventIF Java Examples

The following examples show how to use org.productivity.java.syslog4j.server.SyslogServerEventIF. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractSyslogServer.java    From syslog4j with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, byte[] lineBytes, int lineBytesLength, InetAddress inetAddr) {
	SyslogServerEventIF event = null;
	
	if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig,lineBytes)) {
		event = new StructuredSyslogServerEvent(lineBytes,lineBytesLength,inetAddr);
		
		if (serverConfig.getDateTimeFormatter() != null) {
			((StructuredSyslogServerEvent) event).setDateTimeFormatter(serverConfig.getDateTimeFormatter());
		}
		
	} else {
		event = new SyslogServerEvent(lineBytes,lineBytesLength,inetAddr);
	}		
	
	return event;
}
 
Example #2
Source File: AuditLogBootingSyslogTest.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Before
public void beforeTest() throws Exception {
    container.startInAdminMode();
    final ModelControllerClient client = container.getClient().getControllerClient();

    Operations.CompositeOperationBuilder compositeOp = Operations.CompositeOperationBuilder.create();
    configureServerName(compositeOp);
    configureElytron(compositeOp);
    executeForSuccess(client, compositeOp.build());

    SYSLOG_SETUP.setup(container.getClient());


    compositeOp = Operations.CompositeOperationBuilder.create();
    configureAliases(compositeOp);
    compositeOp.addStep(Util.getWriteAttributeOperation(auditLogConfigAddress,
            AuditLogLoggerResourceDefinition.LOG_BOOT.getName(), ModelNode.TRUE));
    compositeOp.addStep(Util.getWriteAttributeOperation(auditLogConfigAddress, AuditLogLoggerResourceDefinition.ENABLED.getName(),
            ModelNode.TRUE));
    executeForSuccess(client, compositeOp.build());
    final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue();
    queue.clear();
    container.stop();
}
 
Example #3
Source File: AuditLogFieldsOfLogTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @test.objective Test whether fields in Audit Log have right content
 * @test.expectedResult All asserts are correct and test finishes without any exception.
 */
@Test
public void testAuditLoggingFields() throws Exception {
    queue.clear();
    SyslogServerEventIF syslogEvent = null;

    Assert.assertTrue(makeOneLog());
    syslogEvent = queue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("Event wasn't logged into the syslog", syslogEvent);

    Rfc5424SyslogEvent event = (Rfc5424SyslogEvent) syslogEvent;
    String message = event.getMessage();
    Assert.assertNotNull("Message in the syslog event is empty", message);
    message = DATE_STAMP_PATTERN.matcher(message).replaceFirst("{");
    ModelNode syslogNode = ModelNode.fromJSONString(message);
    checkLog("Syslog", syslogNode);
    //Since JMX audit logging is not enabled for this test, we should not need to trim the records for WFCORE-2997
    List<ModelNode> logs = readFile(1, false);
    ModelNode log = logs.get(0);
    checkLog("File", log);
}
 
Example #4
Source File: SyslogIsNotAvailableDuringServerBootTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testSyslogIsNotAvailableDuringServerBoot() throws Exception {
    container.start();
    Assert.assertTrue(container.isStarted());

    final BlockingQueue<SyslogServerEventIF> udpQueue = BlockedAllProtocolsSyslogServerEventHandler.getQueue("udp");
    final BlockingQueue<SyslogServerEventIF> tcpQueue = BlockedAllProtocolsSyslogServerEventHandler.getQueue("tcp");
    udpQueue.clear();
    tcpQueue.clear();

    // do log when syslog is not running
    makeLog_syslogIsOffline();
    SyslogServerEventIF udpSyslogEvent = udpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the UDP syslog even if syslog server should be stopped", udpSyslogEvent);
    SyslogServerEventIF tcpSyslogEvent = tcpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the TCP syslog even if syslog server should be stopped", tcpSyslogEvent);

    startSyslogServers(host);

    // do log when syslog is running
    makeLog();
    udpSyslogEvent = udpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the UDP syslog", udpSyslogEvent);
    tcpSyslogEvent = tcpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the TCP syslog", tcpSyslogEvent);
}
 
Example #5
Source File: TLSAuditLogToTCPSyslogTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testAuditLoggingToSyslog() throws Exception {
    final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue();
    queue.clear();

    SyslogServerEventIF syslogEvent = null;
    try {
        setAuditlogEnabled(true);
        // enabling audit-log is auditable event
        syslogEvent = queue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
        // but we don't expect a message in TCP syslog server
        Assert.assertNull("No message was expected in the syslog, because TCP syslog server is used", syslogEvent);
    } finally {
        setAuditlogEnabled(false);
    }

    for (Long property : properties) {
        CoreUtils.applyUpdate(
                Util.createRemoveOperation(PathAddress.pathAddress().append(SYSTEM_PROPERTY, Long.toString(property))),
                managementClient.getControllerClient());
    }
    properties.clear();
}
 
Example #6
Source File: UDPSyslogServer.java    From simple-syslog-server with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void run() {
	this.shutdown = false;
	try {
		this.ds = createDatagramSocket();
	} catch (Exception e) {
		System.err.println("Creating DatagramSocket failed");
		e.printStackTrace();
		throw new SyslogRuntimeException(e);
	}

	byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];

	while (!this.shutdown) {
		try {
			final DatagramPacket dp = new DatagramPacket(receiveData, receiveData.length);
			this.ds.receive(dp);
			final SyslogServerEventIF event = new Rfc5424SyslogEvent(receiveData, dp.getOffset(), dp.getLength());
			System.out.println(">>> Syslog message came: " + event);
		} catch (SocketException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
 
Example #7
Source File: SyslogHandlerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests that messages on all levels are logged, when level="TRACE" in syslog handler.
 */
@Test
public void testAllLevelLogs() throws Exception {
    final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue();
    executeOperation(Operations.createWriteAttributeOperation(SYSLOG_HANDLER_ADDR, "level", "TRACE"));
    queue.clear();
    makeLogs();
    for (Level level : LoggingServiceActivator.LOG_LEVELS) {
        testLog(queue, level);
    }
    Assert.assertTrue("No other message was expected in syslog.", queue.isEmpty());
}
 
Example #8
Source File: AuditLogBootingSyslogTest.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void waitForExpectedOperations(int expectedOperations, BlockingQueue<SyslogServerEventIF> queue) throws InterruptedException {
    int operations = 0;
    int openClose = 0;
    long endTime = System.currentTimeMillis() + TimeoutUtil.adjust(5000);
    do {
        if (queue.isEmpty()) {
            Thread.sleep(100);
        }

        while (!queue.isEmpty()) {
            SyslogServerEventIF event = queue.take();
            char[] messageChars = event.getMessage().toCharArray();
            for (char character : messageChars) {
                if (character == '{' || character == '}') {
                    if (character == '{') {
                        openClose++;
                    } else {
                        openClose--;
                    }
                    Assert.assertTrue(openClose >= 0);

                    if (openClose == 0) operations++;
                }
            }
        }

        if (operations >= expectedOperations) {
            break;
        }
    } while (System.currentTimeMillis() < endTime);

    Assert.assertEquals(expectedOperations, operations);
}
 
Example #9
Source File: AuditLogBootingSyslogTest.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test the Syslog audit events emitted during a server boot.
 *
 * During the server boot there are two key audit events to be recorded.
 * <ol>
 * <li>Adding of extensions.
 * <li>Composite operation of initial configuration.
 * </ol>
 */
@Test
public void testSyslog() throws Exception {
    final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue();
    queue.clear();
    container.start();
    waitForExpectedOperations(2, queue);
    queue.clear();
    makeOneLog();
    waitForExpectedOperations(1, queue);
    queue.clear();
}
 
Example #10
Source File: SyslogHandlerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests if the next message in the syslog is the expected one with the given log-level.
 *
 * @param expectedLevel the expected level of the next log message
 *
 * @throws Exception
 */
private void testJsonLog(final BlockingQueue<SyslogServerEventIF> queue, final Level expectedLevel) throws Exception {
    final SyslogServerEventIF log = queue.poll(15L * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    assertNotNull(log);
    final String msg = log.getMessage();
    assertNotNull(msg);
    try (JsonReader reader = Json.createReader(new StringReader(msg))) {
        final JsonObject json = reader.readObject();
        assertEquals("Message with unexpected Syslog event text received.", expectedLevel.name(), json.getString("level"));
        final String expectedMsg = LoggingServiceActivator.formatMessage(MSG, expectedLevel);
        assertEquals("Message with unexpected Syslog event text received.", expectedMsg, json.getString("message"));
    }
}
 
Example #11
Source File: SyslogHandlerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests if the next message in the syslog is the expected one with the given log-level.
 *
 * @param expectedLevel the expected level of the next log message
 *
 * @throws Exception
 */
private void testLog(final BlockingQueue<SyslogServerEventIF> queue, final Level expectedLevel) throws Exception {
    SyslogServerEventIF log = queue.poll(15L * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    assertNotNull(log);
    String msg = log.getMessage();
    assertEquals("Message with unexpected Syslog event level received: " + msg, getSyslogLevel(expectedLevel), log.getLevel());
    final String expectedMsg = LoggingServiceActivator.formatMessage(MSG, expectedLevel);
    assertEquals("Message with unexpected Syslog event text received.", expectedMsg, msg);
}
 
Example #12
Source File: SyslogHandlerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests that only messages on specific level or higher level are logged to syslog.
 */
@Test
public void testLogOnSpecificLevel() throws Exception {
    final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue();
    executeOperation(Operations.createWriteAttributeOperation(SYSLOG_HANDLER_ADDR, "level", "ERROR"));
    queue.clear();
    makeLogs();
    testLog(queue, Level.FATAL);
    testLog(queue, Level.ERROR);
    Assert.assertTrue("No other message was expected in syslog.", queue.isEmpty());
}
 
Example #13
Source File: TCPSyslogSocketHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parses {@link Rfc5424SyslogEvent} instance from given raw message bytes and sends it to event handlers.
 *
 * @param rawMsg
 */
private void handleSyslogMessage(final byte[] rawMsg) {
    final SyslogServerEventIF event = new Rfc5424SyslogEvent(rawMsg, 0, rawMsg.length);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Firing Syslog event: " + event);
    }
    final List eventHandlers = this.server.getConfig().getEventHandlers();
    for (int i = 0; i < eventHandlers.size(); i++) {
        final SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) eventHandlers.get(i);
        eventHandler.event(this.server, event);
    }
}
 
Example #14
Source File: UDPSyslogServer.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void run() {
    this.shutdown = false;
    try {
        this.ds = createDatagramSocket();
    } catch (Exception e) {
        LOGGER.error("Creating DatagramSocket failed", e);
        throw new SyslogRuntimeException(e);
    }

    byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];

    while (!this.shutdown) {
        try {
            final DatagramPacket dp = new DatagramPacket(receiveData, receiveData.length);
            this.ds.receive(dp);
            final SyslogServerEventIF event = new Rfc5424SyslogEvent(receiveData, dp.getOffset(), dp.getLength());
            List list = this.syslogServerConfig.getEventHandlers();
            for (int i = 0; i < list.size(); i++) {
                SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) list.get(i);
                eventHandler.event(this, event);
            }
        } catch (SocketException se) {
            LOGGER.warn("SocketException occurred", se);
        } catch (IOException ioe) {
            LOGGER.warn("IOException occurred", ioe);
        }
    }
}
 
Example #15
Source File: AbstractSyslogServer.java    From syslog4j with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static SyslogServerEventIF createEvent(SyslogServerConfigIF serverConfig, String line, InetAddress inetAddr) {
	SyslogServerEventIF event = null;
	
	if (serverConfig.isUseStructuredData() && AbstractSyslogServer.isStructuredMessage(serverConfig,line)) {
		event = new StructuredSyslogServerEvent(line,inetAddr);
		
	} else {
		event = new SyslogServerEvent(line,inetAddr);
	}		
	
	return event;
}
 
Example #16
Source File: BlockedSyslogServerEventHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static BlockingQueue<SyslogServerEventIF> getQueue() {
    return queue;
}
 
Example #17
Source File: BlockedAllProtocolsSyslogServerEventHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static BlockingQueue<SyslogServerEventIF> getQueue(String protocol) {
    return queueMap.get(protocol);
}
 
Example #18
Source File: AuditLogToSyslogTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
void assertAppName(String expected, SyslogServerEventIF syslogEvent) {
    Rfc5424SyslogEvent event = (Rfc5424SyslogEvent) syslogEvent;
    Assert.assertEquals(expected, event.getAppName());
}
 
Example #19
Source File: PrintStreamServerEventTest.java    From syslog4j with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testPrintStreamEvent() {
	SyslogServerIF server = SyslogServer.getInstance("udp");
	
	String message = "test message";
	
	InetAddress inetAddress = null;
	
	try { inetAddress = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { }
	
	SyslogServerEventIF event = new SyslogServerEvent(message.getBytes(),message.length(),inetAddress);

	assertEquals(SyslogConstants.CHAR_SET_DEFAULT,event.getCharSet());
	event.setCharSet("xxyyzz");
	assertEquals("xxyyzz",event.getCharSet());
	
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	PrintStream ps = new PrintStream(baos);
	
	SyslogServerSessionEventHandlerIF eventHandler = new PrintStreamSyslogServerEventHandler(ps);
	eventHandler.sessionOpened(server,null);
	eventHandler.event(null,server,null,event);
	eventHandler.exception(null,server,null,null);
	eventHandler.sessionClosed(null,server,null,false);
	assertEquals(event.getMessage(),new String("test message"));

	Date date = new Date();
	event.setDate(date);
	assertTrue(date == event.getDate());
	
	event.setFacility(SyslogConstants.FACILITY_LOCAL0);
	assertEquals(SyslogConstants.FACILITY_LOCAL0,event.getFacility());
	
	event.setHost("foo");
	assertEquals("foo",event.getHost());
	
	event.setLevel(SyslogConstants.LEVEL_DEBUG);
	assertEquals(SyslogConstants.LEVEL_DEBUG,event.getLevel());
	
	event.setMessage(message);
	assertEquals(message,event.getMessage());
	
	eventHandler = SystemOutSyslogServerEventHandler.create();
	eventHandler.event(null,server,null,event);

	eventHandler = new SystemErrSyslogServerEventHandler();
	eventHandler.event(null,server,null,event);
	
	try {
		File f = File.createTempFile("syslog4j-test",".txt");
		
		eventHandler = new FileSyslogServerEventHandler(f.getPath());
		eventHandler.event(null,server,null,event);

		eventHandler = new FileSyslogServerEventHandler(f.getPath(),true);
		eventHandler.event(null,server,null,event);

	} catch (Exception e) {
		fail(e.toString());
	}
}
 
Example #20
Source File: ReconnectSyslogServerTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testReconnectSyslogServer() throws Exception {
    final BlockingQueue<SyslogServerEventIF> udpQueue = BlockedAllProtocolsSyslogServerEventHandler.getQueue("udp");
    final BlockingQueue<SyslogServerEventIF> tcpQueue = BlockedAllProtocolsSyslogServerEventHandler.getQueue("tcp");
    udpQueue.clear();
    tcpQueue.clear();

    // logging before syslog restart
    makeLog();
    SyslogServerEventIF udpSyslogEvent = udpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the UDP syslog", udpSyslogEvent);
    SyslogServerEventIF tcpSyslogEvent = tcpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the TCP syslog", tcpSyslogEvent);

    stopSyslogServers();

    makeLog_syslogIsOffline();
    udpSyslogEvent = udpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the UDP syslog even if syslog server should be stopped", udpSyslogEvent);
    tcpSyslogEvent = tcpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the TCP syslog even if syslog server should be stopped", tcpSyslogEvent);

    startSyslogServers(host);

    // logging after first syslog restart
    makeLog();
    udpSyslogEvent = udpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the UDP syslog after first syslog server restart", udpSyslogEvent);
    tcpSyslogEvent = tcpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the TCP syslog after first syslog server restart", tcpSyslogEvent);

    stopSyslogServers();

    makeLog_syslogIsOffline();
    udpSyslogEvent = udpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the UDP syslog even if syslog server should be stopped", udpSyslogEvent);
    tcpSyslogEvent = tcpQueue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNull("Message was logged into the TCP syslog even if syslog server should be stopped", tcpSyslogEvent);

    startSyslogServers(host);

    // logging after second syslog restart
    makeLog();
    udpSyslogEvent = udpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the UDP syslog after second syslog server restart", udpSyslogEvent);
    tcpSyslogEvent = tcpQueue.poll(5 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    Assert.assertNotNull("No message was logged into the TCP syslog after second syslog server restart", tcpSyslogEvent);

}
 
Example #21
Source File: AbstractSyslogServer.java    From syslog4j with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, Socket socket, SyslogServerEventIF event) {
	handleEvent(sessions,syslogServer,socket,socket.getRemoteSocketAddress(),event);
}
 
Example #22
Source File: AbstractSyslogServer.java    From syslog4j with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void handleEvent(Sessions sessions, SyslogServerIF syslogServer, DatagramPacket packet, SyslogServerEventIF event) {
	handleEvent(sessions,syslogServer,null,packet.getSocketAddress(),event);
}
 
Example #23
Source File: TCPSyslogSocketHandler.java    From simple-syslog-server with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Parses {@link Rfc5424SyslogEvent} instance from given raw message bytes
 * and sends it to event handlers.
 *
 * @param rawMsg
 */
private void handleSyslogMessage(final byte[] rawMsg) {
	final SyslogServerEventIF event = new Rfc5424SyslogEvent(rawMsg, 0, rawMsg.length);
	System.out.println(">>> Syslog message came: " + event);
}