org.apache.mina.transport.socket.nio.NioSession Java Examples

The following examples show how to use org.apache.mina.transport.socket.nio.NioSession. 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: ModbusExport.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create a new modbus exporter
 *
 * @param executor
 *            the executor used for
 * @param processor
 *            the IO processor
 * @param hiveSource
 *            the source of the hive to export
 * @param itemFactory
 *            an optional item factory for publishing statistics
 * @param logName
 *            an optional name for logging
 */
public ModbusExport ( final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ObjectPoolDataItemFactory itemFactory, final String logName )
{
    this.executor = executor;
    this.hiveSource = hiveSource;
    this.processor = processor;
    this.logName = logName != null ? logName : toString ();

    if ( itemFactory != null )
    {
        this.exporter = new ObjectExporter ( itemFactory, true, true );
        this.exporter.attachTarget ( this.info );
    }
    else
    {
        this.exporter = null;
    }
}
 
Example #2
Source File: WrapperNioSocketConnector.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public WrapperNioSocketConnector(ITaskExecutor taskExecutor) {
       this.taskExecutor = taskExecutor;
	if (taskExecutor != null) {
           Executor executor = taskExecutor.getThreadPool();
		this.ioProcessor = new SimpleIoProcessorPool<NioSession>(NioProcessor.class, executor);
		this.nioSocketConnector = new NioSocketConnector(executor, ioProcessor);
	} else {
		this.ioProcessor = null;
		this.nioSocketConnector = new NioSocketConnector();
	}
}
 
Example #3
Source File: ClientBaseConnection.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected ClientBaseConnection ( final IoHandlerFactory handlerFactory, final IoLoggerFilterChainBuilder chainBuilder, final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception
{
    super ( connectionInformation );

    this.stateNotifier = new StateNotifier ( this.executor, this );

    this.handler = handlerFactory.create ( this );

    if ( processor != null )
    {
        this.connector = new NioSocketConnector ( processor );
    }
    else
    {
        this.connector = new NioSocketConnector ();
    }

    this.chainBuilder = chainBuilder;
    this.chainBuilder.setLoggerName ( ClientBaseConnection.class.getName () + ".protocol" );

    this.connector.setFilterChainBuilder ( this.chainBuilder );
    this.connector.setHandler ( this.handler );

    this.statistics.setLabel ( STATS_CACHE_ADDRESS, "Flag if the IP address gets cached" );
    this.statistics.setCurrentValue ( STATS_CACHE_ADDRESS, this.cacheAddress ? 1.0 : 0.0 );

    this.statistics.setLabel ( STATS_CURRENT_STATE, "Numeric connection state" );
    this.statistics.setLabel ( STATS_CONNECT_CALLS, "Calls to connect" );
    this.statistics.setLabel ( STATS_DISCONNECT_CALLS, "Calls to disconnect" );

    this.statistics.setLabel ( STATS_MESSAGES_SENT, "Messages sent" );
    this.statistics.setLabel ( STATS_MESSAGES_RECEIVED, "Messages received" );

    this.statistics.setLabel ( STATS_CREATION_TIMESTAMP, "Timestamp of creation (in seconds)" );
    this.statistics.setCurrentValue ( STATS_CREATION_TIMESTAMP, Math.floor ( System.currentTimeMillis () / 1000 ) );

    this.statistics.setLabel ( STATS_LAST_CONNECT_TIMESTAMP, "Timestamp of last CONNECT (in seconds)" );
    this.statistics.setLabel ( STATS_LAST_BOUND_TIMESTAMP, "Timestamp of last BOUND (in seconds)" );
}
 
Example #4
Source File: ConnectionBaseImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public ConnectionBaseImpl ( final ProtocolConfigurationFactory protocolConfigurationFactory, final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception
{
    super ( new ProtocolIoHandlerFactory ( protocolConfigurationFactory ), new FilterChainBuilder ( true ), connectionInformation, processor );
    this.responseManager = new ResponseManager ( this.statistics, this.messageSender, this.executor );
    this.callbackHandlerManager = new CallbackHandlerManager ( this.statistics );
    this.callbackManager = new OpenCallbacksManager ( this, this.statistics, this.executor );
    this.callbackFactory = new DefaultCallbackFactory ();
}
 
Example #5
Source File: AbstractIoService.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected AbstractIoService(IoProcessor<NioSession> proc) {
	try {
		selector = Selector.open();
	} catch (IOException e) {
		throw new RuntimeException("failed to open selector", e);
	}

	processor = proc;
	String threadName = getClass().getSimpleName() + '-' + idGenerator.incrementAndGet();
	executor = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
			r -> new Thread(r, threadName));
}
 
Example #6
Source File: SimpleIoProcessorPool.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Find the processor associated to a session.
 * If it hasn't be stored into the session's attributes, pick a new processor and stores it.
 */
private NioProcessor getProcessor(NioSession session) {
	NioProcessor processor = session.getNioProcessor();
	if (processor == null) {
		if (disposing)
			throw new IllegalStateException(getClass().getSimpleName() + " is disposed");

		processor = pool[(int)((session.getId() & Long.MAX_VALUE) % pool.length)];
		if (processor == null)
			throw new IllegalStateException("null processor in pool");
		session.setNioProcessor(processor);
	}

	return processor;
}
 
Example #7
Source File: StaticModbusExport.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private StaticModbusExport ( final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ObjectPoolDataItemFactory itemFactory, final boolean disposeProcessor )
{
    super ( executor, processor, hiveSource, itemFactory );
    this.executor = executor;
    this.processor = processor;
    this.disposeProcessor = disposeProcessor;
}
 
Example #8
Source File: WrapperNioSocketAcceptor.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public WrapperNioSocketAcceptor(ITaskExecutor taskExecutor) {
       this.taskExecutor = taskExecutor;
       if (taskExecutor != null) {
           Executor executor = taskExecutor.getThreadPool();
		this.ioProcessor = new SimpleIoProcessorPool<NioSession>(NioProcessor.class, executor);
		this.nioSocketAcceptor = new NioSocketAcceptor(executor, ioProcessor);
	} else {
		this.ioProcessor = null;
		this.nioSocketAcceptor = new NioSocketAcceptor();
	}
}
 
Example #9
Source File: SimpleIoProcessorPool.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public final void remove(NioSession session) {
	getProcessor(session).remove(session);
}
 
Example #10
Source File: SimpleIoProcessorPool.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public final void add(NioSession session) {
	getProcessor(session).add(session);
}
 
Example #11
Source File: SimpleIoProcessorPool.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public final void write(NioSession session, WriteRequest writeRequest) {
	getProcessor(session).write(session, writeRequest);
}
 
Example #12
Source File: AbstractIoService.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
public final IoProcessor<NioSession> getProcessor() {
	return processor;
}
 
Example #13
Source File: SimpleIoProcessorPool.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public final void flush(NioSession session) {
	getProcessor(session).flush(session);
}
 
Example #14
Source File: TestMultiportSyslogTCPSource.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
/**
 * Test that different charsets are parsed by different ports correctly.
 */
@Test
public void testPortCharsetHandling() throws UnknownHostException, Exception {

  ///////////////////////////////////////////////////////
  // port setup

  InetAddress localAddr = InetAddress.getLocalHost();
  DefaultIoSessionDataStructureFactory dsFactory =
      new DefaultIoSessionDataStructureFactory();


  // one faker on port 10001
  int port1 = 10001;
  NioSession session1 = mock(NioSession.class);
  session1.setAttributeMap(dsFactory.getAttributeMap(session1));
  SocketAddress sockAddr1 = new InetSocketAddress(localAddr, port1);
  when(session1.getLocalAddress()).thenReturn(sockAddr1);

  // another faker on port 10002
  int port2 = 10002;
  NioSession session2 = mock(NioSession.class);
  session2.setAttributeMap(dsFactory.getAttributeMap(session2));
  SocketAddress sockAddr2 = new InetSocketAddress(localAddr, port2);
  when(session2.getLocalAddress()).thenReturn(sockAddr2);

  // set up expected charsets per port
  ConcurrentMap<Integer, ThreadSafeDecoder> portCharsets =
      new ConcurrentHashMap<Integer, ThreadSafeDecoder>();
  portCharsets.put(port1, new ThreadSafeDecoder(Charsets.ISO_8859_1));
  portCharsets.put(port2, new ThreadSafeDecoder(Charsets.UTF_8));

  ///////////////////////////////////////////////////////
  // channel / source setup

  // set up channel to receive events
  MemoryChannel chan = new MemoryChannel();
  chan.configure(new Context());
  chan.start();
  ReplicatingChannelSelector sel = new ReplicatingChannelSelector();
  sel.setChannels(Lists.<Channel>newArrayList(chan));
  ChannelProcessor chanProc = new ChannelProcessor(sel);

  // defaults to UTF-8
  MultiportSyslogHandler handler = new MultiportSyslogHandler(
      1000, 10, chanProc, new SourceCounter("test"), "port",
      new ThreadSafeDecoder(Charsets.UTF_8), portCharsets);

  // initialize buffers
  handler.sessionCreated(session1);
  handler.sessionCreated(session2);

  ///////////////////////////////////////////////////////
  // event setup

  // Create events of varying charsets.
  String header = "<10>2012-08-17T02:14:00-07:00 192.168.1.110 ";

  // These chars encode under ISO-8859-1 as illegal bytes under UTF-8.
  String dangerousChars = "þÿÀÁ";

  ///////////////////////////////////////////////////////
  // encode and send them through the message handler
  String msg;
  IoBuffer buf;
  Event evt;

  // valid ISO-8859-1 on the right (ISO-8859-1) port
  msg = header + dangerousChars + "\n";
  buf = IoBuffer.wrap(msg.getBytes(Charsets.ISO_8859_1));
  handler.messageReceived(session1, buf);
  evt = takeEvent(chan);
  Assert.assertNotNull("Event vanished!", evt);
  Assert.assertNull(evt.getHeaders().get(SyslogUtils.EVENT_STATUS));

  // valid ISO-8859-1 on the wrong (UTF-8) port
  msg = header + dangerousChars + "\n";
  buf = IoBuffer.wrap(msg.getBytes(Charsets.ISO_8859_1));
  handler.messageReceived(session2, buf);
  evt = takeEvent(chan);
  Assert.assertNotNull("Event vanished!", evt);
  Assert.assertEquals("Expected invalid event due to character encoding",
      SyslogUtils.SyslogStatus.INVALID.getSyslogStatus(),
      evt.getHeaders().get(SyslogUtils.EVENT_STATUS));

  // valid UTF-8 on the right (UTF-8) port
  msg = header + dangerousChars + "\n";
  buf = IoBuffer.wrap(msg.getBytes(Charsets.UTF_8));
  handler.messageReceived(session2, buf);
  evt = takeEvent(chan);
  Assert.assertNotNull("Event vanished!", evt);
  Assert.assertNull(evt.getHeaders().get(SyslogUtils.EVENT_STATUS));
}
 
Example #15
Source File: DriverFactoryImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverFactoryImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #16
Source File: DriverInformationImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverInformationImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #17
Source File: DriverFactoryImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverFactoryImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #18
Source File: DefaultIoFilterChain.java    From jane with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public NioSession getSession() {
	return session;
}
 
Example #19
Source File: DriverInformation.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverInformation ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #20
Source File: DriverFactoryImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverFactoryImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #21
Source File: DriverInformationImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverInformationImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #22
Source File: DriverFactoryImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverFactoryImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #23
Source File: DriverInformationImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public DriverInformationImpl ( final IoProcessor<NioSession> processor )
{
    this.processor = processor;
}
 
Example #24
Source File: ModbusExportImpl.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public ModbusExportImpl ( final String id, final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ManageableObjectPool<DataItem> itemObjectPool )
{
    super ( id, executor, processor, hiveSource, itemObjectPool );
}
 
Example #25
Source File: ModbusExport.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public ModbusExport ( final String id, final ScheduledExecutorService executor, final IoProcessor<NioSession> processor, final HiveSource hiveSource, final ManageableObjectPool<DataItem> itemObjectPool )
{
    this ( executor, processor, hiveSource, new ObjectPoolDataItemFactory ( executor, itemObjectPool, String.format ( "org.eclipse.scada.da.server.exporter.modbus.export.%s.information.", id ) ), "ModbusExporter/" + id ); //$NON-NLS-1$
}
 
Example #26
Source File: StaticModbusExport.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Build a new modbus export instance based on the current builder state
 * <br/>
 * <em>Note:</em> The call is responsible for disposing the created
 * instance using {@link ModbusExport#dispose()}.
 *
 * @return a newly created modbus instance
 */
public ModbusExport build ()
{
    final ScheduledExecutorService executor;
    if ( this.threadFactory == null )
    {
        executor = ScheduledExportedExecutorService.newSingleThreadExportedScheduledExecutor ( "StaticModubusExporter/" + COUNTER.incrementAndGet () );
    }
    else
    {
        executor = new ScheduledExportedExecutorService ( "StaticModubusExporter/" + COUNTER.incrementAndGet (), 1, this.threadFactory );
    }

    boolean disposeProcessor;
    final IoProcessor<NioSession> processor;
    if ( this.processor == null )
    {
        processor = new SimpleIoProcessorPool<> ( NioProcessor.class );
        disposeProcessor = true;
    }
    else
    {
        processor = this.processor;
        disposeProcessor = false;
    }

    final StaticModbusExport result = new StaticModbusExport ( executor, processor, this.hiveSource, null, disposeProcessor );

    try
    {
        result.setProperties ( this.hiveProperies );

        result.setReadTimeout ( this.readTimeout );
        result.setSlaveId ( this.slaveId );
        result.setPort ( this.port );

        // we must call this after "setProperties", since this method creates the block
        result.setBlockConfiguration ( this.definitions );

        return result;
    }
    catch ( final Throwable e )
    {
        result.dispose ();
        throw new RuntimeException ( "Failed to start exporter", e );
    }
}
 
Example #27
Source File: WrapperNioSocketConnector.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public IoProcessor<NioSession> getIoProcessor() {
	return ioProcessor;
}
 
Example #28
Source File: ConnectionImpl.java    From neoscada with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Create a new connection <br/>
 * 
 * @param connectionInformation
 *            the information where to connect to
 * @param processor
 *            the socket processor, may be <code>null</code> to use the
 *            default
 * @throws Exception
 *             if anything goes wrong
 */
public ConnectionImpl ( final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception
{
    super ( new ProtocolConfigurationFactoryImpl ( connectionInformation ), connectionInformation, processor );
    this.browserManager = new BrowserManager ( this.executor, this );
    this.monitorManager = new MonitorManager ( this.executor, this );
    this.eventManager = new EventManager ( this.executor, this );
    this.queryManager = new QueryManager ( this.executor, this );
}
 
Example #29
Source File: ConnectionImpl.java    From neoscada with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Create a new connection <br/>
 * 
 * @param connectionInformation
 *            the information where to connect to
 * @param processor
 *            the socket processor, may be <code>null</code> to use the
 *            default
 * @throws Exception
 *             if anything goes wrong
 */
public ConnectionImpl ( final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception
{
    super ( new ProtocolConfigurationFactoryImpl ( connectionInformation ), connectionInformation, processor );
    this.itemManager = new ItemManager ( this.executor, this );

    this.statistics.setLabel ( STATS_OPEN_QUERIES, "Open queries" );
}
 
Example #30
Source File: ConnectionImpl.java    From neoscada with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Create a new connection <br/>
 * 
 * @param connectionInformation
 *            the information where to connect to
 * @param processor
 *            the socket processor, may be <code>null</code> to use the
 *            default
 * @throws Exception
 *             if anything goes wrong
 */
public ConnectionImpl ( final ConnectionInformation connectionInformation, final IoProcessor<NioSession> processor ) throws Exception
{
    super ( new ProtocolConfigurationFactoryImpl ( connectionInformation ), connectionInformation, processor );
}