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:at.general.solutions.android.ical.remote.ssl.EasySSLSocketFactory.java

/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
 *      java.lang.String, int, java.net.InetAddress, int,
 *      org.apache.http.params.HttpParams)
 *//*from   www. j a v  a2s  . com*/
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            localPort = 0; // indicates "any"
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }

    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;

}

From source file:com.sap.wec.adtreco.be.ODataClientService.java

private HttpURLConnection initializeConnection(final String absoluteUri, final String contentType,
        final String httpMethod) {
    LOG.info("Initialize connection for URL: " + absoluteUri);
    HttpURLConnection connection = null;
    try {//from w ww.j  av a2 s . c o  m
        final URL url = new URL(absoluteUri);
        if (getProxyHost() != null) {
            final Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(getProxyHost(), getProxyPort()));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestProperty(HTTP_HEADER_ACCEPT, contentType);
        connection.setRequestMethod(httpMethod);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT_RT);
    } catch (final IOException IOe) {
        (new Exception("Error initializing connection to CEI: " + absoluteUri, IOe)).printStackTrace();
    }

    if (HTTP_METHOD_POST.equals(httpMethod) || HTTP_METHOD_PUT.equals(httpMethod)) {
        connection.setDoOutput(true);
        connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, contentType);
    }

    if (this.user != null) {
        String authorization = "Basic ";
        authorization += new String(Base64.encodeBase64((this.user + ":" + this.password).getBytes()));
        connection.setRequestProperty("Authorization", authorization);
    }
    LOG.info("End of initialize connection");
    return connection;
}

From source file:com.jkoolcloud.jesl.net.socket.SocketClient.java

/**
 * Create JESL HTTP[S} client stream with given attributes
 * //from   w  ww .j  av  a  2  s.c o  m
 * @param host JESL host server
 * @param port JESL host port number
 * @param secure use SSL if secure, standard sockets if false
 * @param proxyHost proxy host name if any, null if none
 * @param proxyPort proxy port number if any, 0 of none
 * @param logger event sink used for logging, null if none
 * 
 */
public SocketClient(String host, int port, boolean secure, String proxyHost, int proxyPort, EventSink logger) {
    this(host, port, secure, logger);
    if (!StringUtils.isEmpty(proxyHost)) {
        proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
        proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
    }
}

From source file:com.chiralBehaviors.slp.hive.configuration.BroadcastConfiguration.java

InetSocketAddress getBroadcastAddress(NetworkInterface networkInterface) {
    InetSocketAddress broadcastAddress = null;
    for (InterfaceAddress addr : networkInterface.getInterfaceAddresses()) {
        if (ipv4) {
            if (addr.getBroadcast() != null && addr.getBroadcast().getAddress().length == 4) {
                broadcastAddress = new InetSocketAddress(addr.getBroadcast(), port);
                break;
            }/*from   w  w w .j  ava  2s  . c  o m*/
        } else {
            if (addr.getBroadcast() != null && addr.getBroadcast().getAddress().length > 4) {
                broadcastAddress = new InetSocketAddress(addr.getBroadcast(), port);
                break;
            }
        }
    }
    return broadcastAddress;
}

From source file:com.mastfrog.acteur.server.EventImpl.java

public EventImpl(HttpRequest req, PathFactory paths) {
    this.req = req;
    this.path = paths.toPath(req.getUri());
    address = new InetSocketAddress("timboudreau.com", 8985); //XXX for tests
    this.channel = null;
    Codec codec = new ServerModule.CodecImpl(Providers.of(new ObjectMapper()));
    this.converter = new ContentConverter(codec, Providers.of(Charset.defaultCharset()), null, null);
}

From source file:org.bimserver.client.protocolbuffers.ProtocolBuffersChannel.java

public void connect(TokenHolder tokenHolder) throws ChannelConnectionException {
    protocolBuffersChannel = new SocketProtocolBuffersChannel(tokenHolder);
    protocolBuffersChannel.registerConnectDisconnectListener(this);

    ProtocolBuffersReflector reflector = new ProtocolBuffersReflector(protocolBuffersMetaData, servicesMap,
            protocolBuffersChannel);/*  w w  w. j ava2  s .  co  m*/
    for (Class<? extends PublicInterface> interface1 : servicesMap.getInterfaceClasses()) {
        PublicInterface createReflector = reflectorFactory.createReflector(interface1, reflector);
        add(interface1.getName(), createReflector);
    }

    finish(reflector, reflectorFactory);
    try {
        protocolBuffersChannel.connect(new InetSocketAddress(address, port));
    } catch (IOException e) {
        throw new ChannelConnectionException(e);
    }
}

From source file:com.xiovr.unibot.bot.BotGameConfigTest.java

@SuppressWarnings("deprecation")
@Test()/*from   w  w w .java 2 s  .com*/
public void testBotEnvironment_load_and_save() {
    String dir = getClass().getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
    File fn = new File(dir + "/" + BotEnvironment.ENVIRONMENT_CFG_FN);
    fn.delete();
    //      botGameConfig.loadPropsToBotEnvironment(botEnvironment);
    botGameConfig.loadSettings(botEnvironment, "/" + dir + "/" + BotEnvironment.ENVIRONMENT_CFG_FN);

    Assert.assertEquals(botEnvironment.getNextBotConnectionInterval(), 10);
    Assert.assertEquals(botEnvironment.getUpdateInterval(), 100);
    Assert.assertEquals(botEnvironment.getClientAddresses().get(0).getHostString(), "127.0.0.1");
    Assert.assertEquals(botEnvironment.getClientAddresses().get(0).getPort(), 2594);

    Assert.assertEquals(botEnvironment.getServerAddresses().get(0).getHostString(), "91.206.202.30");
    Assert.assertEquals(botEnvironment.getServerAddresses().get(0).getPort(), 2594);
    Assert.assertEquals(botEnvironment.getProxy(), false);
    Assert.assertEquals(botEnvironment.getRawData(), false);

    botEnvironment.setNextBotConnectionInterval(10);
    botEnvironment.setUpdateInterval(200);
    botEnvironment.getServerAddresses().clear();
    botEnvironment.getClientAddresses().clear();
    botEnvironment.addClientAddress(new InetSocketAddress("255.255.255.255", 1000));
    botEnvironment.addServerAddress(new InetSocketAddress("125.124.123.11", 2000));
    botEnvironment.addClientAddress(new InetSocketAddress("255.255.255.254", 1001));
    botEnvironment.addServerAddress(new InetSocketAddress("126.124.123.11", 2001));
    botEnvironment.setProxy(true);
    botEnvironment.setRawData(true);

    //      botGameConfig.savePropsFromBotEnvironment(botEnvironment);
    botGameConfig.saveSettings(botEnvironment, "/" + dir + "/" + BotEnvironment.ENVIRONMENT_CFG_FN,
            "Bot v" + BotGameConfig.VERSION);
    BotEnvironment botEnvTest = new BotEnvironmentImpl();

    //      botGameConfig.loadPropsToBotEnvironment(botEnvTest);
    botGameConfig.loadSettings(botEnvTest, "/" + dir + "/" + BotEnvironmentImpl.ENVIRONMENT_CFG_FN);

    Assert.assertEquals(botEnvTest.getNextBotConnectionInterval(), 10);
    Assert.assertEquals(botEnvTest.getUpdateInterval(), 200);
    Assert.assertEquals(botEnvTest.getClientAddresses().get(0).getHostString(), "255.255.255.255");
    Assert.assertEquals(botEnvTest.getClientAddresses().get(0).getPort(), 1000);

    Assert.assertEquals(botEnvTest.getServerAddresses().get(0).getHostString(), "125.124.123.11");
    Assert.assertEquals(botEnvTest.getServerAddresses().get(0).getPort(), 2000);
    Assert.assertEquals(botEnvTest.getClientAddresses().get(1).getHostString(), "255.255.255.254");
    Assert.assertEquals(botEnvTest.getClientAddresses().get(1).getPort(), 1001);

    Assert.assertEquals(botEnvTest.getServerAddresses().get(1).getHostString(), "126.124.123.11");
    Assert.assertEquals(botEnvTest.getServerAddresses().get(1).getPort(), 2001);
    Assert.assertEquals(botEnvTest.getProxy(), true);
    Assert.assertEquals(botEnvTest.getRawData(), true);

}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *//*  w w w. j a v a2  s.c o m*/
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:org.akita.io._FakeSSLSocketFactory.java

@Override
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }// ww w .  jav  a2  s. c  om
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0) {
            localPort = 0;
        }

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress;
    remoteAddress = new InetSocketAddress(host, port);

    sslsock.connect(remoteAddress, connTimeout);

    sslsock.setSoTimeout(soTimeout);

    return sslsock;
}

From source file:com.isec.helperapp.EasySSLSocketFactory.java

/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
 *      java.lang.String, int, java.net.InetAddress, int,
 *      org.apache.http.params.HttpParams)
 *//*  w  ww  .  j a  v a 2  s  . c  o m*/
public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    Log.i(TAG, "connectSocket: " + host + ":" + port);
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {
        // we need to bind explicitly
        if (localPort < 0) {
            localPort = 0; // indicates "any"
        }
        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }

    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);
    return sslsock;

}