Example usage for org.springframework.integration.ip.tcp.connection AbstractServerConnectionFactory getPort

List of usage examples for org.springframework.integration.ip.tcp.connection AbstractServerConnectionFactory getPort

Introduction

In this page you can find the example usage for org.springframework.integration.ip.tcp.connection AbstractServerConnectionFactory getPort.

Prototype

public int getPort() 

Source Link

Usage

From source file:org.musa.tcpserver.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/* w w  w.ja v  a  2  s.  com*/
 */
public static void main(final String... args) {

    System.out.println("preparing to launch the server app 'Eye of Terror'");

    final GenericXmlApplicationContext context = setupContext();
    // context.registerShutdownHook();

    final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    TestingUtilities.waitListening(crLfServer, 10000L);

    System.out.println("'Eye of Terror' is up and running at port " + crLfServer.getPort());

}

From source file:com.haythem.integration.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from   www  .ja  va2s .c  om*/
 */
public static void main(final String... args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration                    "
            + "\n          TCP-Client-Server Sample!                      "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    final GenericXmlApplicationContext context = Main.setupContext();
    final SimpleGateway gateway = context.getBean(SimpleGateway.class);
    final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    System.out.print("Waiting for server to accept connections...");
    TestingUtilities.waitListening(crLfServer, 10000L);
    System.out.println("running.\n\n");

    System.out.println("Please enter some text and press <enter>: ");
    System.out.println("\tNote:");
    System.out.println("\t- Entering FAIL will create an exception");
    System.out.println("\t- Entering q will quit the application");
    System.out.print("\n");
    System.out.println("\t--> Please also check out the other samples, " + "that are provided as JUnit tests.");
    System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort()
            + "' using Telnet.\n\n");

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        } else {
            final String result = gateway.send(input);
            System.out.println(result);
        }
    }

    System.out.println("Exiting application...bye.");
    System.exit(0);

}

From source file:com.richard.memorystore.tcp.TcpServer.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*  ww  w .  j ava 2 s. co  m*/
 */
public static void main() {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration                    "
            + "\n          TCP-Client-Server Sample!                      "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springintegration.org/                    "
            + "\n                                                         "
            + "\n=========================================================");

    final GenericXmlApplicationContext context = TcpServer.setupContext();
    final SimpleGateway gateway = context.getBean(SimpleGateway.class);
    final AbstractServerConnectionFactory crLfServer = context.getBean(AbstractServerConnectionFactory.class);

    System.out.print("Waiting for server to accept connections...");
    TestingUtilities.waitListening(crLfServer, 10000L);
    System.out.println("running.\n\n");

    System.out.println("Please enter some text and press <enter>: ");
    System.out.println("\tNote:");
    System.out.println("\t- Entering FAIL will create an exception");
    System.out.println("\t- Entering q will quit the application");
    System.out.print("\n");
    System.out.println("\t--> Please also check out the other samples, " + "that are provided as JUnit tests.");
    System.out.println("\t--> You can also connect to the server on port '" + crLfServer.getPort()
            + "' using Telnet.\n\n");

    InputProcessor lineProcessor = new InputProcessor();

    while (true) {

        final String input = scanner.nextLine();

        System.out.println("GOT THIS!!!" + input);

        KeyValueController keyValueController = new KeyValueController();

        KeyValue keyValue = lineProcessor.processLine(input);

        keyValueController.addToMemoryStore(keyValue.getKey(), keyValue.getValue());

        if ("q".equals(input.trim())) {
            break;
        } else {
            final String result = gateway.send(input);
            System.out.println(result);
        }
    }

    System.out.println("Exiting application...bye.");
    System.exit(0);

}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java

public void testObtainConnectionIds(AbstractServerConnectionFactory serverFactory) throws Exception {
    final List<IpIntegrationEvent> events = Collections.synchronizedList(new ArrayList<IpIntegrationEvent>());
    int expectedEvents = serverFactory instanceof TcpNetServerConnectionFactory ? 7 // Listening, + OPEN, CLOSE, EXCEPTION for each side
            : 5; // Listening, + OPEN, CLOSE (but we *might* get exceptions, depending on timing).
    final CountDownLatch serverListeningLatch = new CountDownLatch(1);
    final CountDownLatch eventLatch = new CountDownLatch(expectedEvents);
    ApplicationEventPublisher publisher = new ApplicationEventPublisher() {

        @Override/*  w  w  w  .  ja v  a  2  s .  c  om*/
        public void publishEvent(ApplicationEvent event) {
            LogFactory.getLog(this.getClass()).trace("Received: " + event);
            events.add((IpIntegrationEvent) event);
            if (event instanceof TcpConnectionServerListeningEvent) {
                serverListeningLatch.countDown();
            }
            eventLatch.countDown();
        }

        @Override
        public void publishEvent(Object event) {

        }

    };
    serverFactory.setBeanName("serverFactory");
    serverFactory.setApplicationEventPublisher(publisher);
    serverFactory = spy(serverFactory);
    final CountDownLatch serverConnectionInitLatch = new CountDownLatch(1);
    doAnswer(invocation -> {
        Object result = invocation.callRealMethod();
        serverConnectionInitLatch.countDown();
        return result;
    }).when(serverFactory).wrapConnection(any(TcpConnectionSupport.class));
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(10);
    scheduler.afterPropertiesSet();
    BeanFactory bf = mock(BeanFactory.class);
    when(bf.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    when(bf.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class))
            .thenReturn(scheduler);
    serverFactory.setBeanFactory(bf);
    TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
    adapter.setOutputChannel(new NullChannel());
    adapter.setConnectionFactory(serverFactory);
    adapter.start();
    assertTrue("Listening event not received", serverListeningLatch.await(10, TimeUnit.SECONDS));
    assertThat(events.get(0), instanceOf(TcpConnectionServerListeningEvent.class));
    assertThat(((TcpConnectionServerListeningEvent) events.get(0)).getPort(), equalTo(serverFactory.getPort()));
    int port = serverFactory.getPort();
    TcpNetClientConnectionFactory clientFactory = new TcpNetClientConnectionFactory("localhost", port);
    clientFactory.registerListener(message -> false);
    clientFactory.setBeanName("clientFactory");
    clientFactory.setApplicationEventPublisher(publisher);
    clientFactory.start();
    TcpConnectionSupport client = clientFactory.getConnection();
    List<String> clients = clientFactory.getOpenConnectionIds();
    assertEquals(1, clients.size());
    assertTrue(clients.contains(client.getConnectionId()));
    assertTrue("Server connection failed to register", serverConnectionInitLatch.await(1, TimeUnit.SECONDS));
    List<String> servers = serverFactory.getOpenConnectionIds();
    assertEquals(1, servers.size());
    assertTrue(serverFactory.closeConnection(servers.get(0)));
    servers = serverFactory.getOpenConnectionIds();
    assertEquals(0, servers.size());
    int n = 0;
    clients = clientFactory.getOpenConnectionIds();
    while (n++ < 100 && clients.size() > 0) {
        Thread.sleep(100);
        clients = clientFactory.getOpenConnectionIds();
    }
    assertEquals(0, clients.size());
    assertTrue(eventLatch.await(10, TimeUnit.SECONDS));
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
            events.size(), greaterThanOrEqualTo(expectedEvents));

    FooEvent event = new FooEvent(client, "foo");
    client.publishEvent(event);
    assertThat("Expected at least " + expectedEvents + " events; got: " + events.size() + " : " + events,
            events.size(), greaterThanOrEqualTo(expectedEvents + 1));

    try {
        event = new FooEvent(mock(TcpConnectionSupport.class), "foo");
        client.publishEvent(event);
        fail("Expected exception");
    } catch (IllegalArgumentException e) {
        assertTrue("Can only publish events with this as the source".equals(e.getMessage()));
    }

    SocketAddress address = serverFactory.getServerSocketAddress();
    if (address instanceof InetSocketAddress) {
        InetSocketAddress inetAddress = (InetSocketAddress) address;
        assertEquals(port, inetAddress.getPort());
    }
    serverFactory.stop();
    scheduler.shutdown();
}

From source file:org.springframework.integration.ip.tcp.connection.ConnectionFactoryTests.java

private void testEarlyClose(final AbstractServerConnectionFactory factory, String property, String message)
        throws Exception {
    factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    factory.setBeanName("foo");
    factory.registerListener(mock(TcpListener.class));
    factory.afterPropertiesSet();/*www. ja  v  a  2  s  .  c  om*/
    Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class));
    new DirectFieldAccessor(factory).setPropertyValue("logger", logger);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final CountDownLatch latch3 = new CountDownLatch(1);
    when(logger.isInfoEnabled()).thenReturn(true);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(invocation -> {
        latch1.countDown();
        // wait until the stop nulls the channel
        latch2.await(10, TimeUnit.SECONDS);
        return null;
    }).when(logger).info(contains("Listening"));
    doAnswer(invocation -> {
        latch3.countDown();
        return null;
    }).when(logger).debug(contains(message));
    factory.start();
    assertTrue("missing info log", latch1.await(10, TimeUnit.SECONDS));
    // stop on a different thread because it waits for the executor
    Executors.newSingleThreadExecutor().execute(() -> factory.stop());
    int n = 0;
    DirectFieldAccessor accessor = new DirectFieldAccessor(factory);
    while (n++ < 200 && accessor.getPropertyValue(property) != null) {
        Thread.sleep(100);
    }
    assertTrue("Stop was not invoked in time", n < 200);
    latch2.countDown();
    assertTrue("missing debug log", latch3.await(10, TimeUnit.SECONDS));
    String expected = "foo, port=" + factory.getPort() + message;
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger, atLeast(1)).debug(captor.capture());
    assertThat(captor.getAllValues(), hasItem(expected));
    factory.stop();
}