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.mkwhitacre.kafka.mapreduce.utils.EmbeddedZookeeper.java

/**
 * Constructs an embedded Zookeeper instance.
 * /*from   w  ww.j a  v  a 2s.c  o m*/
 * @param connectString Zookeeper connection string.
 * 
 * @throws IOException if an error occurs during Zookeeper initialization.
 */
public EmbeddedZookeeper(String connectString) throws IOException {
    this.snapshotDir = KafkaTestUtils.getTempDir();
    this.logDir = KafkaTestUtils.getTempDir();
    this.factory = new NIOServerCnxnFactory();
    String hostname = connectString.split(":")[0];
    int port = Integer.valueOf(connectString.split(":")[1]);
    int maxClientConnections = 1024;
    factory.configure(new InetSocketAddress(hostname, port), maxClientConnections);
    try {
        int tickTime = 500;
        factory.startup(new ZooKeeperServer(snapshotDir, logDir, tickTime));
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:edu.berkeley.sparrow.daemon.nodemonitor.TestTaskScheduler.java

/**
 * Tests the fifo task scheduler./*from www  . j  av a  2 s.  co  m*/
 */
@Test
public void testFifo() {
    TaskScheduler scheduler = new FifoTaskScheduler(4);
    scheduler.initialize(new PropertiesConfiguration(), 12345);

    final String testApp = "test app";
    final InetSocketAddress backendAddress = new InetSocketAddress("123.4.5.6", 2);

    // Make sure that tasks are launched right away, if resources are available.
    scheduler.submitTaskReservations(createTaskReservationRequest(1, scheduler, testApp), backendAddress);
    assertEquals(1, scheduler.runnableTasks());
    TaskSpec task = scheduler.getNextTask();
    assertEquals("1", task.requestId);
    assertEquals(0, scheduler.runnableTasks());

    scheduler.submitTaskReservations(createTaskReservationRequest(2, scheduler, testApp), backendAddress);
    assertEquals(2, scheduler.runnableTasks());

    // Make sure the request to schedule 3 tasks is appropriately split, with one task running
    // now and others started later.
    scheduler.submitTaskReservations(createTaskReservationRequest(3, scheduler, testApp), backendAddress);
    /* 4 tasks have been launched but one was already removed from the runnable queue using
     * getTask(), leaving 3 runnable tasks. */
    assertEquals(3, scheduler.runnableTasks());
    task = scheduler.getNextTask();
    assertEquals("2", task.requestId);
    task = scheduler.getNextTask();
    assertEquals("2", task.requestId);
    /* Make a list of task ids to use in every call to tasksFinished, and just update the request
     * id for each call. */
    TFullTaskId fullTaskId = new TFullTaskId();
    fullTaskId.taskId = "";
    List<TFullTaskId> completedTasks = Lists.newArrayList();
    completedTasks.add(fullTaskId);

    // Have a few tasks complete before the last runnable task is removed from the queue.
    fullTaskId.requestId = "2";
    scheduler.tasksFinished(completedTasks);
    scheduler.tasksFinished(completedTasks);
    fullTaskId.requestId = "1";
    scheduler.tasksFinished(completedTasks);

    task = scheduler.getNextTask();
    assertEquals("3", task.requestId);
    task = scheduler.getNextTask();
    assertEquals("3", task.requestId);
    task = scheduler.getNextTask();
    assertEquals("3", task.requestId);
    assertEquals(0, scheduler.runnableTasks());
}

From source file:at.diamonddogs.net.ssl.CustomSSLSocketFactory.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   ww w.j a v a2 s  . c om
@Override
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.phei.netty.protocol.netty.client.NettyClient.java

public void connect(int port, String host) throws Exception {

    // ?NIO//from  ww w .j a v a  2 s.c  o m

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                        ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                        ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                        ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                        ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
                    }
                });
        // ??
        ChannelFuture future = b.connect(new InetSocketAddress(host, port),
                new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        // channelchannel
        // Returns the ChannelFuture which will be notified when this channel is closed. This method always returns the same future instance.
        future.channel().closeFuture().sync();
    } finally {
        // ????????
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ???
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private URLConnection getUrlConnection(HttpServletRequest request, String method, String requestBody,
        String forwardUrl) throws MalformedURLException, IOException, ProtocolException {
    final URL url = new URL(forwardUrl);
    final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

    URLConnection urlConnection = url.openConnection(proxy);

    Map<String, String> requestHeaders = getRequestHeaders(request);
    requestHeaders.put("Host", urlConnection.getURL().getHost());

    ((HttpURLConnection) urlConnection).setRequestMethod(method);

    if (forwardUrl.startsWith("https")) {
        SSLSocketFactory sslSocketFactory = null;
        try {/*from w  w w .ja va  2s .c  o m*/
            sslSocketFactory = getSSLSocketFactory();
        } catch (KeyManagementException e) {
            throw new IOException("Exception caught while setting up SSL props : ", e);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Exception caught while setting up SSL props : ", e);
        }
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslSocketFactory);
    }

    urlConnection.setDoInput(true);

    setHeaders(urlConnection, requestHeaders);

    setDoOutput(method, requestBody, urlConnection);

    return urlConnection;
}

From source file:idgs.client.TcpClient.java

private void initialize() throws IOException {
    servAddr = new InetSocketAddress(host, port);
    // create selector
    try {//from  w ww  .j av a2 s .c om
        selector = Selector.open();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:es.ugr.swad.swadroid.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. jav 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 {
    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:dk.dma.epd.common.prototype.sensor.nmea.NmeaTcpSensor.java

private void connect() throws IOException {
    try {/*  w  ww  .j a  v a 2s.c  o m*/
        clientSocket = new Socket();
        InetSocketAddress address = new InetSocketAddress(hostname, port);
        clientSocket.connect(address);
        clientSocket.setKeepAlive(true);
        clientSocket.setSoTimeout(TCP_READ_TIMEOUT);
        outputStream = clientSocket.getOutputStream();
        LOG.info("NMEA source connected " + hostname + ":" + port);
    } catch (UnknownHostException e) {
        LOG.error("Unknown host: " + hostname + ": " + e.getMessage());
        throw e;
    } catch (IOException e) {
        LOG.error("Could not connect to NMEA source: " + hostname + ": " + e.getMessage());
        throw e;
    }
}

From source file:Fetcher.Fetcher.java

@Deprecated
@Override//from   ww w.j  av a 2  s .c  o  m
/**
 * run() is deprecated. Use startFetching() instead.
 */
public void run() {
    WebDocument link = null;
    HttpURLConnection connection;
    Proxy p;

    //PreConnfiguration
    //Configure proxy
    //TODO Anonymizer is deprecated. Use in following for warning generation.
    switch (Variables.anonymizerProxyType) {
    case DIRECT:
        p = new Proxy(Proxy.Type.DIRECT,
                new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort));
        break;
    case HTTP:
        p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort));
        break;
    case SOCKS:
        p = new Proxy(Proxy.Type.SOCKS,
                new InetSocketAddress(Variables.anonymizerIP, Variables.anonymizerPort));
        break;
    case NONE:
    default:
        p = null;
        break;
    }

    link = Methods.getNextProfileLink();
    while (link != null && isWorking) {
        //Start fetching ...

        //Check if it should work or not
        Date currentTime = Methods.getCurrentTime();
        if (!currentTime.after(Variables.startTime) || !currentTime.before(Variables.endTime)) {
            try {
                synchronized (t) {
                    getThread().wait(60000); //sleep 60 seconds
                }
            } catch (InterruptedException ex) {
                if (Variables.debug) {
                    Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                            "Time is not between start and end time and thread is in exception!");
                }
            } finally {
                continue;
            }
        }

        String URL = link.getNextUrl();
        String UA = Methods.getRandomUserAgent(); //Use this UA for refererd or single links.

        //loop for referer
        for (int i = 0; i <= link.getRefererCount(); URL = link.getNextUrl(), i++) {

            if (Variables.debug && Variables.vv) {
                Variables.logger.Log(Fetcher.class, Variables.LogType.Trace,
                        "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") start getting " + URL);
            }

            try {

                //Anonymizer
                if (Variables.anonymizerProxyType == Variables.AnonymizerProxy.NONE) {
                    connection = (HttpURLConnection) new URL(URL).openConnection();
                } else {
                    connection = (HttpURLConnection) new URL(URL).openConnection(p);
                }

                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("User-Agent", UA);
                connection.setRequestProperty("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                connection.setRequestProperty("Accept-Encoding", "gzip, deflated");

                String referer = link.getNextReferrer();
                if (referer != null) {
                    connection.setRequestProperty("Referer", referer);
                    referer = null;
                    System.gc();
                }

                //Send Cookie using user input
                if (!(Variables.Cookie == null || Variables.Cookie.equalsIgnoreCase(""))) {
                    connection.setRequestProperty("Cookie", Variables.Cookie);
                } else if (cookies.getCookieStore().getCookies().size() > 0) { //From referer, there are some cookies
                    connection.setRequestProperty("Cookie", Join(",", cookies.getCookieStore().getCookies()));
                }

                connection.setRequestMethod("GET");

                connection.connect();

                //Get Cookie from response
                getCookies(connection);

                if (connection.getResponseCode() == 200) {
                    //Write to file
                    String outputName = Variables.outputDirectory
                            + link.getOutputName().substring(0, link.getOutputName().lastIndexOf(".")) + i
                            + link.getOutputName().substring(link.getOutputName().lastIndexOf("."));

                    //Check extension
                    if (!(outputName.endsWith("html") || outputName.endsWith("htm"))) {
                        outputName += "html";
                    }

                    //get content
                    String html = "";

                    if (connection.getContentEncoding().equalsIgnoreCase("gzip")) {
                        html = IOUtils.toString(new GZIPInputStream(connection.getInputStream()));
                    } else if (connection.getContentEncoding().equalsIgnoreCase("deflate")) {
                        html = IOUtils.toString(new InflaterInputStream(connection.getInputStream()));
                    }

                    FileWriter fw = new FileWriter(outputName);
                    fw.write(html);
                    fw.flush();
                    fw.close();
                } else { //The returned code is not 200.
                    if (Variables.debug) {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "Fetcher could not download (" + Methods.Colorize(URL, Methods.Color.Red)
                                        + ") in " + name);
                        if (Variables.vv) {
                            Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Server responded ("
                                    + Methods.Colorize(connection.getResponseCode() + " - "
                                            + connection.getResponseMessage(), Methods.Color.Red)
                                    + ") for " + URL);
                        }
                    }
                }

                //Close the connection
                connection.disconnect();

                //Report progress
                Variables.logger.logResult(connection, link);
                Methods.oneFinished();

                if (Variables.debug && Variables.vv) {
                    Variables.logger.Log(Fetcher.class, Variables.LogType.Info,
                            "[+] Done fetching (" + Methods.Colorize(URL, Methods.Color.Red) + "]");
                }

                try {
                    synchronized (t) {
                        t.wait(Methods.getNextRandom() * 1000);
                    }
                } catch (InterruptedException ex) {
                    if (Variables.debug) {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error, "Cannot interrupt thread ["
                                + Methods.Colorize(name, Methods.Color.Red) + "]. Interrupted before!");
                    }
                } catch (IllegalArgumentException ex) {
                    if (Variables.debug) {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "-1 is returned as random number for thread ["
                                        + Methods.Colorize(name, Methods.Color.Red) + "].");
                    }
                }
            } catch (IOException ex) {
                if (Variables.debug) {
                    if (Variables.vv) {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red)
                                        + "] in fetcher (" + Methods.Colorize(name, Methods.Color.Yellow)
                                        + ") for writing in ("
                                        + Methods.Colorize(link.getOutputName(), Methods.Color.White)
                                        + "). Detail:\r\n" + ex.getMessage());
                    } else {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "Error in fetching [" + Methods.Colorize(URL, Methods.Color.Red) + "]");
                    }
                }
            } catch (NullPointerException ex) { //Thrown sometimes and make the thread as Dead!
                if (Variables.debug) {
                    if (Variables.vv) {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "Null pointer occured. Error in fetching ["
                                        + Methods.Colorize(URL, Methods.Color.Red) + "] in fetcher ("
                                        + Methods.Colorize(name, Methods.Color.Yellow) + ") for writing in ("
                                        + Methods.Colorize(link.getOutputName(), Methods.Color.White) + ").");
                    } else {
                        Variables.logger.Log(Fetcher.class, Variables.LogType.Error,
                                "Null pointer occured. Error in fetching ["
                                        + Methods.Colorize(URL, Methods.Color.Red) + "]");
                    }
                }
            }
        }

        //Check size limit and compress ...
        long size = Methods.getFolderSize(Variables.outputDirectory);
        if (size >= Variables.outputSizeLimit) {
            //Deactivate itself by waiting ...
            Variables.state = Variables.microbotState.Compressing;
            Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Compressing);
        }

        //Check if user terminated program or not
        if (isWorking) {
            link = Methods.getNextProfileLink();
        }
    }

    //Thread finished. (Normally or by force)
    Variables.state = Variables.microbotState.Stopping;
    Variables.threadController.changeActiveThreads(false, t, Variables.microbotState.Stopping);

    //URLs done. This thread finishes its work.
    if (Variables.debug) {
        Variables.logger.Log(Fetcher.class, Variables.LogType.Info,
                "Fetcher (" + Methods.Colorize(name, Methods.Color.Green) + ") finished its work.");
    }

}

From source file:com.offbynull.portmapper.natpmp.NatPmpController.java

/**
 * Constructs a {@link NatPmpController} object.
 * @param gatewayAddress address of router/gateway
 * @param listener a listener to listen for all NAT-PMP packets from this router
 * @throws NullPointerException if any argument is {@code null}
 * @throws IOException if problems initializing UDP channels
 *//*from  w  w w. j av a  2  s . com*/
public NatPmpController(InetAddress gatewayAddress, final NatPmpControllerListener listener)
        throws IOException {
    Validate.notNull(gatewayAddress);

    this.gateway = new InetSocketAddress(gatewayAddress, 5351);

    List<DatagramChannel> channels = new ArrayList<>(3);

    try {
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));

        ipv4MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET);
        ipv4MulticastChannel.configureBlocking(false);
        ipv4MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv4MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv4InterfaceAddresses(ipv4MulticastChannel);

        ipv6MulticastChannel = DatagramChannel.open(StandardProtocolFamily.INET6);
        ipv6MulticastChannel.configureBlocking(false);
        ipv6MulticastChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        ipv6MulticastChannel.socket().bind(new InetSocketAddress(5350));
        NetworkUtils.multicastListenOnAllIpv6InterfaceAddresses(ipv6MulticastChannel);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        IOUtils.closeQuietly(ipv4MulticastChannel);
        IOUtils.closeQuietly(ipv6MulticastChannel);
        throw ioe;
    }

    channels.add(unicastChannel);
    channels.add(ipv4MulticastChannel);
    channels.add(ipv6MulticastChannel);

    this.communicator = new UdpCommunicator(channels);
    this.communicator.startAsync().awaitRunning();

    if (listener != null) {
        this.communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                CommunicationType type;
                if (channel == unicastChannel) {
                    type = CommunicationType.UNICAST;
                } else if (channel == ipv4MulticastChannel || channel == ipv6MulticastChannel) {
                    type = CommunicationType.MULTICAST;
                } else {
                    return; // unknown, do nothing
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new ExternalAddressNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new UdpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }

                try {
                    packet.mark();
                    listener.incomingResponse(type, new TcpMappingNatPmpResponse(packet));
                } catch (BufferUnderflowException | IllegalArgumentException e) { // NOPMD
                    // ignore
                } finally {
                    packet.reset();
                }
            }
        });
    }
}