001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.net.mock;
015
016import java.net.DatagramPacket;
017import java.net.DatagramSocket;
018import java.util.ArrayList;
019import java.util.List;
020
021/**
022 * 
023 * @author Ceki Gülcü
024 */
025public class MockSyslogServer extends Thread {
026
027    final int loopLen;
028    final int port;
029
030    List<byte[]> msgList = new ArrayList<byte[]>();
031    boolean finished = false;
032
033    public MockSyslogServer(int loopLen, int port) {
034        super();
035        this.loopLen = loopLen;
036        this.port = port;
037    }
038
039    @Override
040    public void run() {
041        // System.out.println("MockSyslogServer listening on port "+port);
042        DatagramSocket socket = null;
043        try {
044            socket = new DatagramSocket(port);
045
046            for (int i = 0; i < loopLen; i++) {
047                byte[] buf = new byte[65536];
048                DatagramPacket packet = new DatagramPacket(buf, buf.length);
049                // System.out.println("Waiting for message");
050                socket.receive(packet);
051                byte[] out = new byte[packet.getLength()];
052                System.arraycopy(buf, 0, out, 0, out.length);
053                msgList.add(out);
054            }
055        } catch (Exception se) {
056            se.printStackTrace();
057        } finally {
058            if (socket != null) {
059                try {
060                    socket.close();
061                } catch (Exception e) {
062                }
063            }
064        }
065        finished = true;
066    }
067
068    public boolean isFinished() {
069        return finished;
070    }
071
072    public List<byte[]> getMessageList() {
073        return msgList;
074    }
075}