Example usage for org.apache.mina.filter.logging LoggingFilter LoggingFilter

List of usage examples for org.apache.mina.filter.logging LoggingFilter LoggingFilter

Introduction

In this page you can find the example usage for org.apache.mina.filter.logging LoggingFilter LoggingFilter.

Prototype

public LoggingFilter(String name) 

Source Link

Document

Create a new LoggingFilter using a name

Usage

From source file:BuggyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("log4j.properties");

    LOG.info("starting echo server");

    OneThreadSelectorStrategy strategy = new OneThreadSelectorStrategy(
            new SelectorFactory(NioSelectorProcessor.class));
    NioTcpServer acceptor = new NioTcpServer(strategy);

    // create the fitler chain for this service
    acceptor.setFilters(new LoggingFilter("LoggingFilter1"), new IoFilter() {

        @Override//from  www .  jav a  2  s  .  c  om
        public void sessionOpened(IoSession session) {
            LOG.info("session {} open", session);
        }

        @Override
        public void sessionIdle(IoSession session, IdleStatus status) {
            LOG.info("session {} idle", session);
        }

        @Override
        public void sessionCreated(IoSession session) {
            LOG.info("session {} created", session);
        }

        @Override
        public void sessionClosed(IoSession session) {
            LOG.info("session {} open", session);
        }

        @Override
        public void messageWriting(IoSession session, Object message, WriteFilterChainController controller) {
            // we just push the message in the chain
            controller.callWriteNextFilter(session, message);
        }

        @Override
        public void messageReceived(IoSession session, Object message, ReadFilterChainController controller) {

            if (message instanceof ByteBuffer) {
                LOG.info("echoing");
                session.write(message);
            }
        }
    });

    acceptor.addListener(new IoServiceListener() {

        @Override
        public void sessionDestroyed(IoSession session) {
            LOG.info("session destroyed {}", session);

        }

        @Override
        public void sessionCreated(IoSession session) {
            LOG.info("session created {}", session);

            String welcomeStr = "welcome\n";
            ByteBuffer bf = ByteBuffer.allocate(welcomeStr.length());
            bf.put(welcomeStr.getBytes());
            bf.flip();
            session.write(bf);
        }

        @Override
        public void serviceInactivated(IoService service) {
            LOG.info("service deactivated {}", service);
        }

        @Override
        public void serviceActivated(IoService service) {
            LOG.info("service activated {}", service);
        }
    });

    startOfAll = System.currentTimeMillis();
    List<BindingThread> threads = new ArrayList<BindingThread>();
    for (int i = 9999; i < totalPorts + 9999; i++) {
        BindingThread bindingThread = new BindingThread(acceptor, i);
        threads.add(bindingThread);
        bindingThread.start();
    }

    Thread.sleep(500);
    acceptor.unbindAll();// the iterator in it must be in the synchronized block, but it is not in the sync block, so the concurrentModificationException happens.

    //               Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
    //               Exception in thread "main" java.util.ConcurrentModificationException
    //                  at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
    //                  at java.util.HashMap$KeyIterator.next(HashMap.java:928)
    //                  at org.apache.mina.transport.tcp.nio.NioTcpServer.unbindAll(NioTcpServer.java:127)
    //                  at org.apache.mina.examples.echoserver.BuggyServer.main(BuggyServer.java:143)

    // join does not work for the binding thread as they wait for the incoming requests.

    //        try {
    //            SocketAddress address = new InetSocketAddress(9999);
    //            acceptor.bind(address);
    //            LOG.debug("Running the server for 25 sec");
    //            Thread.sleep(25000);
    //            LOG.debug("Unbinding the TCP port");
    //            acceptor.unbind(address);
    //        } catch (IOException e) {
    //            LOG.error("I/O exception", e);
    //        } catch (InterruptedException e) {
    //            LOG.error("Interrupted exception", e);
    //        }
}

From source file:com.easyway.spring.apache.tapedeck.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    SocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setReuseAddress(true);/*w  w w . j  a v a 2 s  .  c  o m*/
    ProtocolCodecFilter pcf = new ProtocolCodecFilter(new TextLineEncoder(), new CommandDecoder());
    acceptor.getFilterChain().addLast("log1", new LoggingFilter("log1"));
    acceptor.getFilterChain().addLast("codec", pcf);
    //        acceptor.getFilterChain().addLast("authentication", createAuthenticationIoFilter());
    acceptor.getFilterChain().addLast("log2", new LoggingFilter("log2"));
    acceptor.setHandler(createIoHandler());
    acceptor.bind(new InetSocketAddress(PORT));
}

From source file:com.evangel.example.tapedeck.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    SocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setReuseAddress(true);// w  w  w  .  j a  v a2 s. c  o  m
    ProtocolCodecFilter pcf = new ProtocolCodecFilter(new TextLineEncoder(), new CommandDecoder());
    acceptor.getFilterChain().addLast("log1", new LoggingFilter("log1"));
    acceptor.getFilterChain().addLast("codec", pcf);
    // acceptor.getFilterChain().addLast("authentication",
    // createAuthenticationIoFilter());
    acceptor.getFilterChain().addLast("log2", new LoggingFilter("log2"));
    acceptor.setHandler(createIoHandler());
    acceptor.bind(new InetSocketAddress(PORT));
}

From source file:com.masslink.idea.mina.host.ZigBeeHost.java

License:Apache License

@Override
public void run() {
    logger.info("ZigBee Mina ?...");
    acceptor = new NioSocketAcceptor();
    /* ? zigBee host  */
    acceptor.getSessionConfig().setReadBufferSize(hostSettings.getZigBeeBufferSize());
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, hostSettings.getZigBeeIdle());
    acceptor.getSessionConfig().setWriteTimeout(hostSettings.getZigBeeTimeout());
    /*  *//*  ww w. j a  v  a  2  s .  c  o  m*/
    acceptor.getFilterChain().clear();
    acceptor.getFilterChain().addLast("LOGGER", new LoggingFilter(ZigBeeHost.class));
    /* ?? */
    ZigBeeCodecFactory factory = new ZigBeeCodecFactory(new ZigBeeEncoder(CHARSET), new ZigBeeDecoder(CHARSET));
    acceptor.getFilterChain().addLast("CODEC", new ProtocolCodecFilter(factory));
    /* ? */
    acceptor.setHandler(handler);
    try {
        logger.info("ZigBee Mina Filter ?{}", acceptor.getFilterChain().getAll().size());
        acceptor.bind(new InetSocketAddress(hostSettings.getZigBeePort()));
    } catch (IOException ex) {
        logger.warn("ZigBee Mina ?IO", ex);
    }
}

From source file:com.nokia.gdc.domain.SocketInfo.java

public void prepareAcceptor() throws Exception {

    ClassLoader classLoader = this.getClass().getClassLoader();
    Class loadedMyClass = classLoader.loadClass("com.nokia.gdc.socket." + classHandlerName);
    Constructor constructor = loadedMyClass.getConstructor();

    LineDelimiter line = new LineDelimiter("#E#");
    TextLineCodecFactory txtFac = new TextLineCodecFactory(Charset.forName("UTF-8"), line, line);
    txtFac.setDecoderMaxLineLength(10240);

    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("logger", new LoggingFilter(socketName));
    acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(txtFac));

    acceptor.setHandler((IoHandlerAdapter) constructor.newInstance());
    acceptor.setHandler(new NetactAlarmForwardingHandler());
    acceptor.getSessionConfig().setReadBufferSize(2048);
    acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);

    incomingCounter = 0;/* w ww.  j  a  v a 2  s.com*/
    processingCounter = 0;
    lifeTime = new Long(0);
}

From source file:com.semion.demo.mina.NioEchoServer.java

License:Apache License

public static void main(final String[] args) {
    LOG.info("starting echo server");

    final NioTcpServer acceptor = new NioTcpServer();

    // create the filter chain for this service
    acceptor.setFilters(new LoggingFilter("LoggingFilter1"));

    acceptor.setIoHandler(new AbstractIoHandler() {
        @Override/*from  w  w w  .  j  av a2 s . c  om*/
        public void sessionOpened(final IoSession session) {
            LOG.info("session opened {}", session);

            final String welcomeStr = "welcome\n";
            final ByteBuffer bf = ByteBuffer.allocate(welcomeStr.length());
            bf.put(welcomeStr.getBytes());
            bf.flip();
            session.write(bf);
        }

        @Override
        public void messageReceived(IoSession session, Object message) {
            if (message instanceof ByteBuffer) {
                LOG.info("echoing");
                session.write(message);
            }
        }
    });
    try {
        final SocketAddress address = new InetSocketAddress(9999);
        acceptor.bind(address);
        LOG.debug("Running the server for 25 sec");
        Thread.sleep(25000);
        LOG.debug("Unbinding the TCP port");
        acceptor.unbind();
    } catch (final InterruptedException e) {
        LOG.error("Interrupted exception", e);
    }
}

From source file:com.vake.MessageClient.java

License:Apache License

/**
 * Constructor/*from   w  w  w . j a  va2  s  .  co m*/
 *
 * @param scheduleExecutor check request time out schedule executor
 */
public MessageClient(ScheduledExecutorService scheduleExecutor, String ip, int port) {
    connector = new NioDatagramConnector();
    this.scheduleExecutor = scheduleExecutor;
    responseInspector = new MessageResponseInspector();
    final DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
    filterChain.addLast("logging", new LoggingFilter(MessageClient.class));
    // ??
    final MessageProtocolCodecFactory codec = new MessageProtocolCodecFactory();
    filterChain.addLast("codec", new ProtocolCodecFilter(codec));

    // thread pool
    filterChain.addLast("threadPool", new ExecutorFilter(IoEventType.MESSAGE_RECEIVED));

    // profile
    profiler = new ProfilerTimerFilter(TimeUnit.MILLISECONDS, IoEventType.MESSAGE_RECEIVED);
    filterChain.addLast("profiler", profiler);

    // request and response filter
    final RequestResponseFilter reqRspFilter = new RequestResponseFilter(responseInspector, scheduleExecutor);
    filterChain.addLast("requestResponse", reqRspFilter);

    final DatagramSessionConfig sessionConfig = connector.getSessionConfig();
    sessionConfig.setReceiveBufferSize(READ_BUFFER_SIZE);
    sessionConfig.setReuseAddress(true);

    // add chained io handler
    connector.setHandler(this);

    final ConnectFuture connect = connector.connect(new InetSocketAddress("10.8.9.60", port),
            new InetSocketAddress(port));
    connect.awaitUninterruptibly();
    session = connect.getSession();
}

From source file:m3da.server.tcp.M3daTcpServer.java

License:Open Source License

public void start() {

    acceptor.getSessionConfig().setBothIdleTime(idleTimeInSec);
    acceptor.getSessionConfig().setReuseAddress(true);
    acceptor.getSessionConfig().setTcpNoDelay(true);
    acceptor.setReuseAddress(true);//from  w  w w.ja va  2  s. c  om

    // filter for dumping incoming/outgoing TCP data
    final LoggingFilter firstLogger = new LoggingFilter(this.getClass().getName());
    firstLogger.setMessageReceivedLogLevel(LogLevel.INFO);
    firstLogger.setSessionOpenedLogLevel(LogLevel.INFO);
    firstLogger.setSessionCreatedLogLevel(LogLevel.INFO);
    firstLogger.setSessionClosedLogLevel(LogLevel.INFO);
    firstLogger.setMessageSentLogLevel(LogLevel.INFO);

    // exception are already logged in the IoHandler, no need to duplicate the stacktrace
    firstLogger.setExceptionCaughtLogLevel(LogLevel.NONE);
    acceptor.getFilterChain().addFirst("LOGGER", firstLogger);

    // filter for encoding/decoding the AWTDA3 envelopes
    acceptor.getFilterChain().addLast("ENVCODEC", new EnvelopeFilter(codec));

    // load the security information for the communicating client
    acceptor.getFilterChain().addLast("COMINFO", new ComInfoFilter(securityStore));

    // thread pool for long lasting API calls after the decoding
    acceptor.getFilterChain().addLast("EXECUTOR", new ExecutorFilter(executorCoreSize, executorMaxSize));

    // plug the server logic
    acceptor.setHandler(handler);

    try {
        // bind the port
        LOG.info("bound port : {} for M3DA TCP connections", port);
        acceptor.bind(new InetSocketAddress(port));

    } catch (final IOException e) {
        throw new IllegalStateException("cannot bind the AWTDA3 server port (" + port + ")", e);
    }

}

From source file:org.eclipse.scada.da.client.sfp.FilterChainBuilder.java

License:Open Source License

@Override
public void buildFilterChain(final IoFilterChain chain) {
    if (this.loggerName != null && Boolean.getBoolean("org.eclipse.scada.protocol.sfp.common.logger.raw")) {
        chain.addFirst("logger.raw", new LoggingFilter(this.loggerName));
    }/*  w  w w. jav  a 2s . c  om*/

    if (!Boolean.getBoolean("org.eclipse.scada.protocol.sfp.common.disableStats")) {
        chain.addFirst(StatisticsFilter.DEFAULT_NAME, new StatisticsFilter());
    }

    if (this.loggerName != null && Boolean.getBoolean("org.eclipse.scada.protocol.sfp.common.logger")) {
        chain.addFirst("logger", new LoggingFilter(this.loggerName));
    }

    chain.addLast("closeidle", new IoFilterAdapter() {
        @Override
        public void sessionIdle(final NextFilter nextFilter, final IoSession session, final IdleStatus status)
                throws Exception {
            session.close(true);
        }
    });
    chain.addLast("codec", new ProtocolCodecFilter(new ProtocolEncoderImpl(), new ProtocolDecoderImpl()));
}

From source file:org.eclipse.scada.da.server.osgi.modbus.ModbusMaster.java

License:Open Source License

@Override
protected void configureConnector(final NioSocketConnector connector) {
    logger.debug("Configuring connector: {}", connector);

    switch (this.protocolType) {
    case TYPE_TCP:
        connector.getFilterChain().addLast("modbusPdu",
                new ProtocolCodecFilter(new ModbusTcpEncoder(), new ModbusTcpDecoder()));
        connector.getFilterChain().addLast("modbus", new ModbusMasterProtocolFilter());
        break;/*from w w  w .  j ava2 s  . c  o  m*/
    case TYPE_RTU:
        // convert milliseconds to microseconds to allow more accurate timing
        final ModbusRtuDecoder rtuDecoder = new ModbusRtuDecoder(getExecutor(),
                Double.valueOf(this.interFrameDelay * 1000).longValue(), TimeUnit.MICROSECONDS);
        connector.getFilterChain().addLast("modbusPdu",
                new ModbusRtuProtocolCodecFilter(new ModbusRtuEncoder(), rtuDecoder));
        connector.getFilterChain().addLast("modbus", new ModbusMasterProtocolFilter());
        break;
    default:
        throw new IllegalArgumentException(
                String.format("'%s' is not an allowed modbus device type", this.protocolType));
    }

    if (Boolean.getBoolean("org.eclipse.scada.da.server.osgi.modbus.trace")) {
        connector.getFilterChain().addFirst("logger",
                new LoggingFilter(ModbusMaster.class.getName() + ".protocol"));
    }
}