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:disko.utils.DiscoProxySettings.java

/**
 * /*w  ww.  j ava2s  . co m*/
 * <p>
 * Convenience method to open a URL connection by using the
 * proxy settings. If proxyHost is null, the default is to  just
 * call <code>url.openConnection</code>.
 * </p>
 *
 * @param url
 * @return
 */
public static URLConnection newConnection(URL url) throws IOException {
    URLConnection connection;
    String externalForm = url.toExternalForm();
    url = new URL(externalForm.replace(" ", "%20"));
    if (DiscoProxySettings.proxyHost != null) {
        connection = url.openConnection(new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(DiscoProxySettings.proxyHost, DiscoProxySettings.proxyPort)));
        if (DiscoProxySettings.proxyUser != null) {
            String enc = new String(Base64.encodeBase64(
                    new String(DiscoProxySettings.proxyUser + ":" + DiscoProxySettings.proxyPassword)
                            .getBytes()));
            connection.setRequestProperty("Proxy-Authorization", "Basic " + enc);
        }
    } else
        connection = url.openConnection();
    return connection;
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

@BeforeClass
public static void startHttpServer() throws Exception {
    httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(getSslContext()));
    httpsServer.createContext("/", new ResponseHandler());
    httpsServer.start();//from  w  w  w. j  a v  a2 s  .  com
}

From source file:popo.defcon.MsgMeCDC.java

String readPage() {
    try {/*from  w  ww  .  j  a  v  a2  s.com*/
        URL site = new URL("http://cdc.iitkgp.ernet.in/notice/");
        Proxy p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.3.100.207", 8080));
        HttpURLConnection notice_board = (HttpURLConnection) site.openConnection(p);
        // System.out.println("Proxy in Use: "+notice_board.usingProxy());
        BufferedReader in = new BufferedReader(new InputStreamReader(notice_board.getInputStream()));
        //System.out.println(in.toString());
        String temp;
        StringBuilder http = new StringBuilder();
        // int line = 1;
        while ((temp = in.readLine()) != null) {
            http.append('\n').append(temp);
            //System.out.println("reading line no" + line++);
        }
        //System.out.println(http);
        return (http.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.mirth.connect.connectors.tcp.SocketUtil.java

/**
 * Creates a socket and connects it to the specified remote host on the specified remote port.
 * //from  w w w  . j av  a2 s.  c  om
 * @param host
 *            - The remote host to connect on.
 * @param port
 *            - The remote port to connect on.
 * @param localAddr
 *            - The local address to bind the socket to.
 * @param localPort
 *            - The local port to bind the socket to.
 * @param timeout
 *            - The socket timeout to use when connecting.
 * @return The bound and connected Socket.
 * @throws UnknownHostException
 *             if the IP address of the host could not be determined
 * @throws IOException
 *             if an I/O error occurs when creating the socket
 */
public static Socket createSocket(TcpConfiguration configuration, String localAddr, int localPort)
        throws UnknownHostException, IOException {
    Socket socket = configuration.createSocket();

    if (StringUtils.isNotEmpty(localAddr)) {
        InetAddress localAddress = InetAddress.getByName(TcpUtil.getFixedHost(localAddr));
        socket.bind(new InetSocketAddress(localAddress, localPort));
    }

    return socket;
}

From source file:com.adaptris.core.stubs.ExternalResourcesHelper.java

public static boolean isExternalServerAvailable(String server, int port) {
    boolean result = false;
    try (Socket s = new Socket()) {
        // Try and get a socket to dev on port 80
        // don't give it more than a second though...
        InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(server), port);
        s.connect(addr, 1000);/*from   w w  w  .  ja  va  2 s.  c  o  m*/
        result = true;
    } catch (Exception e) {
    }
    return result;
}

From source file:com.mebigfatguy.polycasso.URLFetcher.java

/**
 * retrieve arbitrary data found at a specific url
 * - either http or file urls/*from  w  w w .  j a  v a 2s.co m*/
 * for http requests, sets the user-agent to mozilla to avoid
 * sites being cranky about a java sniffer
 * 
 * @param url the url to retrieve
 * @param proxyHost the host to use for the proxy
 * @param proxyPort the port to use for the proxy
 * @return a byte array of the content
 * 
 * @throws IOException the site fails to respond
 */
public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
    HttpURLConnection con = null;
    InputStream is = null;

    try {
        URL u = new URL(url);
        if (url.startsWith("file://")) {
            is = new BufferedInputStream(u.openStream());
        } else {
            Proxy proxy;
            if (proxyHost != null) {
                proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            } else {
                proxy = Proxy.NO_PROXY;
            }
            con = (HttpURLConnection) u.openConnection(proxy);
            con.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
            con.addRequestProperty("Accept-Charset", "UTF-8");
            con.addRequestProperty("Accept-Language", "en-US,en");
            con.addRequestProperty("Accept", "text/html,image/*");
            con.setDoInput(true);
            con.setDoOutput(false);
            con.connect();

            is = new BufferedInputStream(con.getInputStream());
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(is, baos);
        return baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(is);
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:io.netlibs.bgp.config.nodes.impl.ClientConfigurationImpl.java

public ClientConfigurationImpl(final InetAddress addr) {
    this.remoteAddress = new InetSocketAddress(addr, 0);
}

From source file:hd3gtv.embddb.MainClass.java

private static List<InetSocketAddress> importConf(PoolManager poolmanager, Properties conf, int default_port)
        throws Exception {
    if (conf.containsKey("hosts") == false) {
        throw new NullPointerException("No hosts in configuration");
    }//from  w ww  . j a  v a 2 s  . com
    String hosts = conf.getProperty("hosts");

    return Arrays.asList(hosts.split(" ")).stream().map(addr -> {
        if (addr.isEmpty() == false) {
            log.debug("Found host in configuration: " + addr);
            return new InetSocketAddress(addr, default_port);
        } else {
            return null;
        }
    }).filter(addr -> {
        return addr != null;
    }).collect(Collectors.toList());
}

From source file:com.bytelightning.opensource.pokerface.ProxySpecificTest.java

/**
 * Configure both servers/*from w  w w.  ja  v  a2s  .  c  o m*/
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    RemoteTarget = new SunHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 8088), null);
    RemoteTarget.start(new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            OnRemoteTargetRequest(exchange);
        }
    });
    proxy = new PokerFace();
    XMLConfiguration conf = new XMLConfiguration();
    conf.load(ProxySpecificTest.class.getResource("/ProxySpecificTestConfig.xml"));
    proxy.config(conf);
    boolean started = proxy.start();
    Assert.assertTrue("Successful proxy start", started);

}

From source file:client.MultiplexingClient.java

public static void main(String[] args) throws Exception {
    // Prepare to parse the command line
    Options options = new Options();
    Option sslOpt = new Option("s", "ssl", false, "Use SSL");
    Option debugOpt = new Option("d", true,
            "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO.");
    Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]");
    Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]");
    Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]");
    Option help = new Option("h", "print this message");

    options.addOption(help);/*from   w  w  w  .j  av  a  2s.  c o  m*/
    options.addOption(debugOpt);
    options.addOption(numConnectionsOpt);
    options.addOption(numPcktOpt);
    options.addOption(pcktMaxSizeOpt);
    options.addOption(sslOpt);
    CommandLineParser parser = new PosixParser();
    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) {
        showUsage(options);
        return;
    }

    if (line.hasOption(sslOpt.getOpt())) {
        channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD);
    } else {
        channelFactory = new PlainChannelFactory();
    }

    if (line.hasOption(numConnectionsOpt.getOpt())) {
        connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt()));
    } else {
        connectionCount = 1;
    }

    if (line.hasOption(numPcktOpt.getOpt())) {
        packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt()));
    } else {
        packetsToSend = 20;
    }

    if (line.hasOption(pcktMaxSizeOpt.getOpt())) {
        maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt()));
    } else {
        maxPcktSize = 4096;
    }

    InetSocketAddress remotePoint;
    try {
        String host = line.getArgs()[0];
        int colonIndex = host.indexOf(':');
        remotePoint = new InetSocketAddress(host.substring(0, colonIndex),
                Integer.parseInt(host.substring(colonIndex + 1)));
    } catch (Exception e) {
        showUsage(options);
        return;
    }

    // Setups the logging context for Log4j
    //     NDC.push(Thread.currentThread().getName());

    st = new SelectorThread();
    for (int i = 0; i < connectionCount; i++) {
        new MultiplexingClient(remotePoint);
        // Must sleep for a while between opening connections in order
        // to give the remote host enough time to handle them. Otherwise,
        // the remote host backlog will get full and the connection
        // attemps will start to be refused.
        Thread.sleep(100);
    }
}