Example usage for java.net InetSocketAddress InetSocketAddress

List of usage examples for java.net InetSocketAddress InetSocketAddress

Introduction

In this page you can find the example usage for java.net InetSocketAddress InetSocketAddress.

Prototype

private InetSocketAddress(int port, String hostname) 

Source Link

Usage

From source file:com.mobius.software.mqtt.performance.controller.net.ClientBootstrap.java

protected InetSocketAddress nextLocalAddress() {
    int port = 0;
    do {/*  w  w w.ja  v  a2s.  c om*/
        if (usedPorts.size() == 65535)
            throw new IllegalStateException("reached limit for number of connected clients");

        currLocalPort.compareAndSet(65535, 10000);
        port = currLocalPort.incrementAndGet();
        if (port == 21883)
            continue;
    } while (!available(Config.getInstance().getHostname(), port) || usedPorts.put(port, true) != null);

    return new InetSocketAddress(Config.getInstance().getHostname(), port);
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/*from   ww w .j  a  va 2  s . c  o m*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        socket.setSoTimeout(timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to " + server + ":" + port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.difference.historybook.proxy.ProxyTest.java

@Test
public void testChunkedResponseHandling() throws IOException {
    String fileName = "src/test/resources/__files/response.txt";
    Path path = Paths.get(fileName).toAbsolutePath();
    byte[] body = Files.readAllBytes(path);

    stubFor(get(urlEqualTo("/some/page")).willReturn(
            aResponse().withStatus(200).withHeader("Content-Type", "text/html").withBodyFile("response.txt")));

    Proxy proxy = getProxy().setPort(PROXY_PORT);
    try {//from   w  w  w  .j  ava2 s  .  c o  m
        proxy.start();

        java.net.Proxy proxyServer = new java.net.Proxy(java.net.Proxy.Type.HTTP,
                new InetSocketAddress("127.0.0.1", PROXY_PORT));
        HttpURLConnection connection = (HttpURLConnection) new URL(
                "http://localhost:" + DUMMY_SERVER_PORT + "/some/page").openConnection(proxyServer);

        // The purpose of this test is to test chunked response handling, but there doesn't seem
        // to be an easy way to force this in WireMock (or any of the other tools I looked at)
        // Having it response with the content of a file seems to result in it switching to 
        // chunked responses, but there isn't a reason this needs to be the case.
        // The following test is really testing to make sure this test is still working
        // and forcing chunked mode responses.
        assertEquals("chunked", connection.getHeaderField("Transfer-Encoding"));

        byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream());
        assertArrayEquals(body, fetchedContent);

        proxy.stop();
    } catch (Exception e) {
        fail(e.getLocalizedMessage());
    }

}

From source file:si.mazi.rescu.HttpTemplate.java

/**
 * Constructor//from w  ww  .  j a v a 2 s  .c  o m
 */
public HttpTemplate() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    // Always use UTF8
    defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8);
    // Assume form encoding by default (typically becomes application/json or application/xml)
    defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
    // Accept text/plain by default (typically becomes application/json or application/xml)
    defaultHttpHeaders.put("Accept", "text/plain");
    // User agent provides statistics for servers, but some use it for content negotiation so fake good agents
    defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent

    if (Config.getProxyPort() == null || Config.getProxyHost() == null) {
        proxy = Proxy.NO_PROXY;
    } else {
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Config.getProxyHost(), Config.getProxyPort()));
        log.info("Using proxy {}", proxy);
    }
}

From source file:be.fedict.eid.dss.client.DSSProxySelector.java

/**
 * Sets the proxy for a certain location URL. If the proxyHost is
 * <code>null</code, we go DIRECT.
 * //from  ww  w .  j av  a  2  s. co m
 * @param location
 *            the location to proxy.
 * @param proxyHost
 *            proxy hostname
 * @param proxyPort
 *            proxy port
 */
public void setProxy(String location, String proxyHost, int proxyPort) {
    String hostname;
    try {
        hostname = new URL(location).getHost();
    } catch (MalformedURLException e) {
        throw new RuntimeException("URL error: " + e.getMessage(), e);
    }
    if (null == proxyHost) {
        LOG.debug("removing proxy for: " + hostname);
        this.proxies.remove(hostname);
    } else {
        LOG.debug("setting proxy for: " + hostname);
        this.proxies.put(hostname, new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
    }
}

From source file:br.com.ararati.operacoes.SocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("HttpConnectionParams: Parmetros no podem ser nulos.");
    }//  w  w  w.j av  a2s.  c  o m

    int timeout = params.getConnectionTimeout();
    javax.net.SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    }

    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.bind(localaddr);
    try {
        socket.connect(remoteaddr, timeout);
    } catch (Exception e) {
        error(e.toString());
        throw new ConnectTimeoutException("Possvel timeout de conexo", e);
    }

    return socket;
}

From source file:io.mandrel.OtherTest.java

@Test
@SneakyThrows//from ww  w  .java  2 s  . c o  m
public void whut4() {
    String add = "208.67.220.220:53";
    Splitter splitter = Splitter.on(":");
    List<String> split = Lists.newArrayList(splitter.split(add));
    InetAddresses.forString(split.get(0));
    new InetSocketAddress(InetAddress.getByAddress(split.get(0).getBytes(Charsets.UTF_8)),
            split.size() == 2 ? Integer.valueOf(split.get(1)) : 53);

}

From source file:de.javakaffee.web.msm.integration.MemcachedFailoverIntegrationTest.java

@BeforeMethod
public void setUp() throws Throwable {

    _portTomcat1 = 18888;//from w  w w . j  a  v a 2  s  .  c om

    _address1 = new InetSocketAddress("localhost", 21211);
    _daemon1 = createDaemon(_address1);
    _daemon1.start();

    _address2 = new InetSocketAddress("localhost", 21212);
    _daemon2 = createDaemon(_address2);
    _daemon2.start();

    _address3 = new InetSocketAddress("localhost", 21213);
    _daemon3 = createDaemon(_address3);
    _daemon3.start();

    _nodeId1 = "n1";
    _nodeId2 = "n2";
    _nodeId3 = "n3";

    try {
        final String memcachedNodes = toString(_nodeId1, _address1) + " " + toString(_nodeId2, _address2) + " "
                + toString(_nodeId3, _address3);
        _tomcat1 = getTestUtils().tomcatBuilder().port(_portTomcat1).sessionTimeout(10)
                .memcachedNodes(memcachedNodes).sticky(true).build();
        _tomcat1.start();
    } catch (final Throwable e) {
        LOG.error("could not start tomcat.", e);
        throw e;
    }

    _httpClient = new DefaultHttpClient();
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();// www  .j  av  a 2s  .co  m
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

From source file:eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl.java

public TaskManagerProfilerImpl(InetAddress jobManagerAddress, InstanceConnectionInfo instanceConnectionInfo)
        throws ProfilingException {

    // Create RPC stub for communication with job manager's profiling component.
    final InetSocketAddress profilingAddress = new InetSocketAddress(jobManagerAddress, GlobalConfiguration
            .getInteger(ProfilingUtils.JOBMANAGER_RPC_PORT_KEY, ProfilingUtils.JOBMANAGER_DEFAULT_RPC_PORT));
    ProfilerImplProtocol jobManagerProfilerTmp = null;
    try {//from   w w  w.  ja va2s  . c  om
        jobManagerProfilerTmp = (ProfilerImplProtocol) RPC.getProxy(ProfilerImplProtocol.class,
                profilingAddress, NetUtils.getSocketFactory());
    } catch (IOException e) {
        throw new ProfilingException(StringUtils.stringifyException(e));
    }
    this.jobManagerProfiler = jobManagerProfilerTmp;

    // Initialize MX interface and check if thread contention monitoring is supported
    this.tmx = ManagementFactory.getThreadMXBean();
    if (this.tmx.isThreadContentionMonitoringSupported()) {
        this.tmx.setThreadContentionMonitoringEnabled(true);
    } else {
        throw new ProfilingException("The thread contention monitoring is not supported.");
    }

    // Create instance profiler
    this.instanceProfiler = new InstanceProfiler(instanceConnectionInfo);

    // Set and trigger timer
    this.timerInterval = (long) (GlobalConfiguration.getInteger(ProfilingUtils.TASKMANAGER_REPORTINTERVAL_KEY,
            ProfilingUtils.DEFAULT_TASKMANAGER_REPORTINTERVAL) * 1000);
    // The initial delay is based on a random value, so the task managers will not send data to the job manager all
    // at once.
    final long initialDelay = (long) (Math.random() * this.timerInterval);
    this.timer = new Timer(true);
    this.timer.schedule(this, initialDelay, this.timerInterval);
}