Example usage for javax.net SocketFactory getDefault

List of usage examples for javax.net SocketFactory getDefault

Introduction

In this page you can find the example usage for javax.net SocketFactory getDefault.

Prototype

public static SocketFactory getDefault() 

Source Link

Document

Returns a copy of the environment's default socket factory.

Usage

From source file:org.apache.camel.component.smpp.SmppConnectionFactory.java

public Connection createConnection(String host, int port) throws IOException {
    try {//from   w w  w  . j a  v  a  2  s  .c o  m
        Socket socket;
        SocketFactory socketFactory;
        socketFactory = config.getUsingSSL() ? SSLSocketFactory.getDefault() : SocketFactory.getDefault();
        if (config.getHttpProxyHost() != null) {
            socket = socketFactory.createSocket(config.getHttpProxyHost(), config.getHttpProxyPort());
            connectProxy(host, port, socket);
        } else {
            socket = socketFactory.createSocket(host, port);
        }
        return new SocketConnection(socket);

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:org.apache.hadoop.ipc.ProtobufRpcEngine.java

@VisibleForTesting
@InterfaceAudience.Private//from   w  w  w . j  a  v  a  2s.  co m
@InterfaceStability.Unstable
static Client getClient(Configuration conf) {
    return CLIENTS.getClient(conf, SocketFactory.getDefault(), RpcWritable.Buffer.class);
}

From source file:org.apache.hadoop.yarn.ipc.ProtoOverHadoopRpcEngine.java

@InterfaceAudience.Private
@InterfaceStability.Unstable// www  . ja v a 2s .  c o m
static Client getClient(Configuration conf) {
    return CLIENTS.getClient(conf, SocketFactory.getDefault(), ProtoSpecificResponseWritable.class);
}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java

private void registerSchemes(ISocketEventSource source, ISocketListener socketListener) {
    SchemeRegistry schemeRegistry = this.httpClient.getConnectionManager().getSchemeRegistry();

    Scheme http = new Scheme(HttpClientRetrieveFileTransfer.HTTP, HTTP_PORT,
            new ECFHttpClientProtocolSocketFactory(SocketFactory.getDefault(), source, socketListener));

    Trace.trace(Activator.PLUGIN_ID, "registering http scheme"); //$NON-NLS-1$
    schemeRegistry.register(http);/*from ww  w .  j  a v  a2  s . c om*/

    ISSLSocketFactoryModifier sslSocketFactoryModifier = Activator.getDefault().getSSLSocketFactoryModifier();

    if (sslSocketFactoryModifier == null) {
        sslSocketFactoryModifier = new HttpClientDefaultSSLSocketFactoryModifier();
    }

    SSLSocketFactory sslSocketFactory = null;
    try {
        sslSocketFactory = sslSocketFactoryModifier.getSSLSocketFactory();
    } catch (IOException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, ISSLSocketFactoryModifier.class,
                "getSSLSocketFactory()", e); //$NON-NLS-1$
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                HttpClientRetrieveFileTransfer.class, "registerSchemes()", e); //$NON-NLS-1$
        throw new ECFRuntimeException("Unable to instantiate schemes for HttpClient.", e); //$NON-NLS-1$
    }

    Scheme https = new Scheme(HttpClientRetrieveFileTransfer.HTTPS, HTTPS_PORT,
            new ECFHttpClientSecureProtocolSocketFactory(sslSocketFactory, source, socketListener));
    Trace.trace(Activator.PLUGIN_ID, "registering https scheme; modifier=" + sslSocketFactoryModifier); //$NON-NLS-1$
    schemeRegistry.register(https);

    // SPNEGO is not supported, so remove it from the list
    List authpref = new ArrayList(3);
    authpref.add(AuthPolicy.NTLM);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.BASIC);

    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
}

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

@Test
public void testAssemblerUsesSecondaryExecutor() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    factory.setApplicationEventPublisher(nullPublisher);

    CompositeExecutor compositeExec = compositeExecutor();

    factory.setSoTimeout(1000);/*w ww  .j  a  va 2 s. co m*/
    factory.setTaskExecutor(compositeExec);
    final AtomicReference<String> threadName = new AtomicReference<String>();
    final CountDownLatch latch = new CountDownLatch(1);
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                threadName.set(Thread.currentThread().getName());
                latch.countDown();
            }
            return false;
        }

    });
    factory.start();
    TestingUtilities.waitListening(factory, null);
    int port = factory.getPort();

    Socket socket = null;
    int n = 0;
    while (n++ < 100) {
        try {
            socket = SocketFactory.getDefault().createSocket("localhost", port);
            break;
        } catch (ConnectException e) {
        }
        Thread.sleep(100);
    }
    assertTrue("Could not open socket to localhost:" + port, n < 100);
    socket.getOutputStream().write("foo\r\n".getBytes());
    socket.close();

    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertThat(threadName.get(), containsString("assembler"));

    factory.stop();
}

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

@Test
public void testAllMessagesDelivered() throws Exception {
    final int numberOfSockets = 100;
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    factory.setApplicationEventPublisher(nullPublisher);

    CompositeExecutor compositeExec = compositeExecutor();

    factory.setTaskExecutor(compositeExec);
    final CountDownLatch latch = new CountDownLatch(numberOfSockets * 4);
    factory.registerListener(new TcpListener() {

        @Override/*from   ww  w . j av a  2 s  .c  o  m*/
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                latch.countDown();
            }
            return false;
        }

    });
    factory.start();
    TestingUtilities.waitListening(factory, null);
    int port = factory.getPort();

    Socket[] sockets = new Socket[numberOfSockets];
    for (int i = 0; i < numberOfSockets; i++) {
        Socket socket = null;
        int n = 0;
        while (n++ < 100) {
            try {
                socket = SocketFactory.getDefault().createSocket("localhost", port);
                break;
            } catch (ConnectException e) {
            }
            Thread.sleep(100);
        }
        assertTrue("Could not open socket to localhost:" + port, n < 100);
        sockets[i] = socket;
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write("foo1 and...".getBytes());
        sockets[i].getOutputStream().flush();
    }
    Thread.sleep(100);
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...foo2\r\nbar1 and...").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...bar2\r\n").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write("foo3 and...".getBytes());
        sockets[i].getOutputStream().flush();
    }
    Thread.sleep(100);
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...foo4\r\nbar3 and...").getBytes());
        sockets[i].getOutputStream().flush();
    }
    for (int i = 0; i < numberOfSockets; i++) {
        sockets[i].getOutputStream().write(("...bar4\r\n").getBytes());
        sockets[i].close();
    }

    assertTrue("latch is still " + latch.getCount(), latch.await(60, TimeUnit.SECONDS));

    factory.stop();
}

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

@Test
public void int3453RaceTest() throws Exception {
    TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(0);
    final CountDownLatch connectionLatch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override/*from ww w.j av  a2  s .c  o m*/
        public void publishEvent(ApplicationEvent event) {
            if (event instanceof TcpConnectionOpenEvent) {
                connectionLatch.countDown();
            }
        }

        @Override
        public void publishEvent(Object event) {

        }

    });
    final CountDownLatch assemblerLatch = new CountDownLatch(1);
    final AtomicReference<Thread> assembler = new AtomicReference<Thread>();
    factory.registerListener(new TcpListener() {

        @Override
        public boolean onMessage(Message<?> message) {
            if (!(message instanceof ErrorMessage)) {
                assembler.set(Thread.currentThread());
                assemblerLatch.countDown();
            }
            return false;
        }

    });
    ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
    te.setCorePoolSize(3); // selector, reader, assembler
    te.setMaxPoolSize(3);
    te.setQueueCapacity(0);
    te.initialize();
    factory.setTaskExecutor(te);
    factory.start();
    TestingUtilities.waitListening(factory, 10000L);
    int port = factory.getPort();
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    assertTrue(connectionLatch.await(10, TimeUnit.SECONDS));

    TcpNioConnection connection = (TcpNioConnection) TestUtils
            .getPropertyValue(factory, "connections", Map.class).values().iterator().next();
    Log logger = spy(TestUtils.getPropertyValue(connection, "logger", Log.class));
    DirectFieldAccessor dfa = new DirectFieldAccessor(connection);
    dfa.setPropertyValue("logger", logger);

    ChannelInputStream cis = spy(
            TestUtils.getPropertyValue(connection, "channelInputStream", ChannelInputStream.class));
    dfa.setPropertyValue("channelInputStream", cis);

    final CountDownLatch readerLatch = new CountDownLatch(4); // 3 dataAvailable, 1 continuing
    final CountDownLatch readerFinishedLatch = new CountDownLatch(1);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            // delay the reader thread resetting writingToPipe
            readerLatch.await(10, TimeUnit.SECONDS);
            Thread.sleep(100);
            readerFinishedLatch.countDown();
            return null;
        }
    }).when(cis).write(any(ByteBuffer.class));

    doReturn(true).when(logger).isTraceEnabled();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("checking data avail"));

    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            readerLatch.countDown();
            return null;
        }
    }).when(logger).trace(contains("Nio assembler continuing"));

    socket.getOutputStream().write("foo\r\n".getBytes());

    assertTrue(assemblerLatch.await(10, TimeUnit.SECONDS));
    assertTrue(readerFinishedLatch.await(10, TimeUnit.SECONDS));

    StackTraceElement[] stackTrace = assembler.get().getStackTrace();
    assertThat(Arrays.asList(stackTrace).toString(), not(containsString("ChannelInputStream.getNextBuffer")));
    socket.close();
    factory.stop();
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testTcp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
    int port = SocketUtils.findAvailableServerSocket(1514);
    factory.setPort(port);/*from   w w w  . jav a 2 s  .  c  om*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
    final CountDownLatch latch = new CountDownLatch(2);
    doAnswer(invocation -> {
        latch.countDown();
        return null;
    }).when(publisher).publishEvent(any(ApplicationEvent.class));
    factory.setApplicationEventPublisher(publisher);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
    doReturn(true).when(logger).isDebugEnabled();
    final CountDownLatch sawLog = new CountDownLatch(1);
    doAnswer(invocation -> {
        if (((String) invocation.getArgument(0)).contains("Error on syslog socket")) {
            sawLog.countDown();
        }
        invocation.callRealMethod();
        return null;
    }).when(logger).debug(anyString());
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE\n".getBytes("UTF-8");
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    socket.getOutputStream().write(buf);
    socket.close();
    assertTrue(sawLog.await(10, TimeUnit.SECONDS));
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    adapter.stop();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testTcpRFC5424() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
    int port = SocketUtils.findAvailableServerSocket(1514);
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
    final CountDownLatch latch = new CountDownLatch(2);
    doAnswer(invocation -> {/*from   ww w .j  a v  a 2 s.c o  m*/
        latch.countDown();
        return null;
    }).when(publisher).publishEvent(any(ApplicationEvent.class));
    factory.setBeanFactory(mock(BeanFactory.class));
    AbstractServerConnectionFactory connectionFactory = new TcpNioServerConnectionFactory(port);
    connectionFactory.setDeserializer(new RFC6587SyslogDeserializer());
    connectionFactory.setApplicationEventPublisher(publisher);
    factory.setConnectionFactory(connectionFactory);
    factory.setConverter(new RFC5424MessageConverter());
    factory.afterPropertiesSet();
    factory.start();
    TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.class));
    doReturn(true).when(logger).isDebugEnabled();
    final CountDownLatch sawLog = new CountDownLatch(1);
    doAnswer(invocation -> {
        if (((String) invocation.getArgument(0)).contains("Error on syslog socket")) {
            sawLog.countDown();
        }
        invocation.callRealMethod();
        return null;
    }).when(logger).debug(anyString());
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    Thread.sleep(1000);
    byte[] buf = ("253 <14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - "
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]"
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance")
                    .getBytes("UTF-8");
    Socket socket = SocketFactory.getDefault().createSocket("localhost", port);
    socket.getOutputStream().write(buf);
    socket.close();
    assertTrue(sawLog.await(10, TimeUnit.SECONDS));
    @SuppressWarnings("unchecked")
    Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("loggregator", message.getPayload().get("syslog_HOST"));
    adapter.stop();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
}

From source file:pl.otros.logview.gui.actions.ConnectToSocketHubAppenderAction.java

private boolean chooseLogImporter() {
    DataConfiguration configuration = getOtrosApplication().getConfiguration();
    List<Object> list1 = configuration.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES);
    configuration.getInt(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES_MAX_COUNT, 20);

    Vector<String> recent = new Vector<String>();
    for (Object o : list1) {
        recent.add(o.toString());/*  ww w .  ja  va  2 s . c  om*/
    }

    JXComboBox box = new JXComboBox(recent);
    box.setEditable(true);
    AutoCompleteDecorator.decorate(box);

    MigLayout migLayout = new MigLayout();
    JPanel panel = new JPanel(migLayout);
    panel.add(new JLabel("Host name:port"));
    panel.add(box, "wrap, width 200:220:440");

    while (true) {
        String[] options = { "Connect", "Cancel" };
        int showConfirmDialog = JOptionPane.showOptionDialog(getOtrosApplication().getApplicationJFrame(),
                panel, "Enter host name and port", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        if (showConfirmDialog != JOptionPane.OK_OPTION) {

            return false;
        }

        try {
            String hostAndPortString = box.getSelectedItem().toString().trim();
            socket = tryToConnectToSocket(configuration, hostAndPortString, SocketFactory.getDefault());
        } catch (UnknownHostException e) {
            JOptionPane.showMessageDialog(panel, host + " is unknown host name", "Error",
                    JOptionPane.ERROR_MESSAGE);
            continue;
        } catch (IOException e) {
            JOptionPane.showMessageDialog(panel, "Cannot connect to host " + host + ":" + port, "Error",
                    JOptionPane.ERROR_MESSAGE);
            continue;
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(panel, "Can't parse port number.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            continue;
        }
        return true;
    }

}