Example usage for java.net InetSocketAddress getHostName

List of usage examples for java.net InetSocketAddress getHostName

Introduction

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

Prototype

public final String getHostName() 

Source Link

Document

Gets the hostname .

Usage

From source file:org.nuxeo.connect.tools.report.client.ReportConnector.java

<A> void connect(Consumer consumer) throws IOException, InterruptedException, ExecutionException {
    ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {

        @Override//from   w w  w.  jav  a 2  s  . com
        public Thread newThread(Runnable target) {
            Thread thread = new Thread(target, "connect-report");
            thread.setDaemon(true);
            return thread;
        }
    });
    try {
        for (ReportServer server : new Discovery()) {
            try (ServerSocket callback = new ServerSocket(0)) {
                final Future<?> consumed = executor.submit(new Runnable() {

                    @Override
                    public void run() {

                        String name = Thread.currentThread().getName();
                        Thread.currentThread().setName("connect-report-consumer-" + server);
                        try (InputStream source = callback.accept().getInputStream()) {
                            consumer.consume(Json.createParser(source));
                        } catch (IOException | JsonParsingException cause) {
                            throw new AssertionError("Cannot consume connect report", cause);
                        } finally {
                            Thread.currentThread().setName(name);
                        }
                        LogFactory.getLog(ReportConnector.class).info("Consumed " + server);
                    }
                });
                final Future<?> served = executor.submit(new Runnable() {

                    @Override
                    public void run() {
                        String name = Thread.currentThread().getName();
                        Thread.currentThread().setName("connect-report-server-" + server);
                        InetSocketAddress address = (InetSocketAddress) callback.getLocalSocketAddress();
                        try {
                            server.run(address.getHostName(), address.getPort());
                        } catch (IOException cause) {
                            throw new AssertionError("Cannot run connect report", cause);
                        } finally {
                            Thread.currentThread().setName(name);
                        }
                    }

                });
                ExecutionException consumerError = null;
                try {
                    consumed.get();
                } catch (ExecutionException cause) {
                    consumerError = cause;
                }
                try {
                    served.get();
                } catch (ExecutionException cause) {
                    if (consumerError != null) {
                        consumerError.addSuppressed(cause);
                        throw consumerError;
                    }
                    throw cause;
                }
            }
        }
    } finally {
        executor.shutdownNow();
    }
}

From source file:org.cloudata.core.fs.PipeBasedCommitLogFileSystem.java

public void processCommitLogServerFailed(Set<String> failedHostNames, List<String> tabletNames) {
    HashMap<ServerSet, CommitLogFileSystemInfo> tempFsCache = new HashMap<ServerSet, CommitLogFileSystemInfo>();
    tempFsCache.putAll(fsCache);// ww w  . j a v  a  2  s.c o m

    for (Map.Entry<ServerSet, CommitLogFileSystemInfo> entry : tempFsCache.entrySet()) {
        ServerSet set = entry.getKey();
        InetSocketAddress[] addressList = set.getAddressList();

        for (InetSocketAddress eachAddress : addressList) {
            String hostName = eachAddress.getHostName() + ":" + eachAddress.getPort();
            if (failedHostNames.contains(hostName)) {
                CommitLogFileSystemInfo info = entry.getValue();
                info.clear();
            }
        }
    }
    for (String tabletName : tabletNames) {
        staleTabletNameSet.add(tabletName);
    }
}

From source file:org.apache.hama.monitor.fd.UDPSupervisor.java

@Override
public Object call() throws Exception {
    ByteBuffer packet = ByteBuffer.allocate(8);
    try {//  w ww. j  a  v  a2s .  com
        while (running.get()) {
            final InetSocketAddress source = (InetSocketAddress) channel.receive(packet);
            final String hostName = source.getHostName();
            packet.flip();
            final long seq = packet.getLong();
            packet.clear();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Seqence: " + seq + " src host: " + hostName);
            }
            final Node tmpNode = new Node(hostName, WINDOW_SIZE.get());
            receiver.submit(new Hermes(tmpNode, seq, System.currentTimeMillis()));
        }
    } catch (IOException ioe) {
        LOG.error("Problem in receiving packet from channel.", ioe);
        Thread.currentThread().interrupt();
    } finally {
        if (null != this.channel)
            try {
                this.channel.socket().close();
                this.channel.close();
            } catch (IOException ioe) {
                LOG.error("Error closing supervisor channel.", ioe);
            }
    }
    return null;
}

From source file:org.planetcrypto.bitcoin.PlanetCryptoBitcoinMinerAPICommands.java

private static String process(String cmd, InetSocketAddress ip, int port) throws Exception {
    Socket socket = new Socket();
    StringBuffer sb = new StringBuffer();
    char buf[] = new char[MAXRECEIVESIZE];
    int len = 0;/*from  w  w w. j  a v a2s  .  c  om*/
    //System.out.println("Attempting to send: " + cmd + " to: "+ ip.getHostAddress()+":"+port);
    try {
        //socket = new Socket(ip, port);
        socket.connect(ip, 2000);
        //System.out.println("Start Sleep");
        //Thread.sleep(1000);
        //System.out.println("Stop Sleep");
        socket.setSoTimeout(2000);
        //socket.(ip, port);
        //System.out.println(socket.getSoTimeout());
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.print(cmd.toLowerCase().toCharArray());
        InputStreamReader isr = new InputStreamReader(socket.getInputStream());
        while (0x80085 > 0) {
            len = isr.read(buf, 0, MAXRECEIVESIZE);
            if (len < 1) {
                break;
            }
            sb.append(buf, 0, len);
            if (buf[len - 1] == '\0') {
                break;
            }
        }
        //closeAll();
        socket.close();
        socket = null;
    } catch (IOException ioe) {
        System.err.println(ioe.toString() + ", " + ip.getHostName());
        //closeAll();
        socket.close();
        socket = null;
        return "Failed to get information";
    }
    String result = sb.toString();
    //System.out.println(result);
    return result.replace("\0", "");
    //jsonFactory(result);
    //System.out.println(result);
}

From source file:com.twitter.finagle.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}.//  ww  w  .  ja  va  2  s. c o m
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Duration sessionTimeout, Credentials credentials, Optional<String> chrootPath,
        Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = (int) Preconditions.checkNotNull(sessionTimeout).inMillis();
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            new Function<InetSocketAddress, String>() {
                @Override
                public String apply(InetSocketAddress addr) {
                    return addr.getHostName() + ":" + addr.getPort();
                }
            });
    this.zooKeeperServers = Joiner.on(',').join(servers);
    this.connectString = this.zooKeeperServers.concat(chrootPath.or(""));
}

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClient(CONF);
    try {//from   ww w.j av a 2 s. c  o m
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        channel.callMethod(md, new PayloadCarryingRpcController(), param, md.getOutputType().toProto(),
                new RpcCallback<Message>() {
                    @Override
                    public void run(Message parameter) {
                        done.set(true);
                    }
                });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:tajo.TajoTestingUtility.java

public MiniCatalogServer startCatalogCluster() throws Exception {
    TajoConf c = getConfiguration();/*w  ww .java 2 s.  c  om*/
    c.setVar(ConfVars.CATALOG_ADDRESS, "localhost:0");

    if (clusterTestBuildDir == null) {
        clusterTestBuildDir = setupClusterTestBuildDir();
    }
    String testDir = clusterTestBuildDir.getAbsolutePath();

    conf.set(TConstants.JDBC_URI, "jdbc:derby:" + testDir + "/db");
    LOG.info("derby repository is set to " + conf.get(TConstants.JDBC_URI));

    this.catalogCluster = new MiniCatalogServer(conf);
    CatalogServer catServer = this.catalogCluster.getCatalogServer();
    InetSocketAddress sockAddr = catServer.getBindAddress();
    c.setVar(ConfVars.CATALOG_ADDRESS, sockAddr.getHostName() + ":" + sockAddr.getPort());

    return this.catalogCluster;
}

From source file:org.apache.hadoop.dfs.SecondaryNameNode.java

/**
 * Initialize SecondaryNameNode./*ww w  .  ja va  2 s.  co  m*/
 */
private void initialize(Configuration conf) throws IOException {
    // initiate Java VM metrics
    JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));

    // Create connection to the namenode.
    shouldRun = true;
    nameNodeAddr = NameNode.getAddress(conf);

    this.conf = conf;
    this.namenode = (ClientProtocol) RPC.waitForProxy(ClientProtocol.class, ClientProtocol.versionID,
            nameNodeAddr, conf);

    // initialize checkpoint directories
    fsName = getInfoServer();
    checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary");
    checkpointImage = new CheckpointStorage();
    checkpointImage.recoverCreate(checkpointDirs);

    // Initialize other scheduling parameters from the configuration
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);

    // initialize the webserver for uploading files.
    String infoAddr = NetUtils.getServerAddress(conf, "dfs.secondary.info.bindAddress",
            "dfs.secondary.info.port", "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    infoBindAddress = infoSocAddr.getHostName();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new StatusHttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0);
    infoServer.setAttribute("name.system.image", checkpointImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort);
    LOG.warn("Checkpoint Period   :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)");
    LOG.warn("Log Size Trigger    :" + checkpointSize + " bytes " + "(" + checkpointSize / 1024 + " KB)");
}

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testRTEDuringAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClientRTEDuringConnectionSetup(CONF);
    try {/*from   ww w  .j a  v a 2  s  . c  o  m*/
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
        controller.notifyOnFail(new RpcCallback<IOException>() {
            @Override
            public void run(IOException e) {
                done.set(true);
                LOG.info("Caught expected exception: " + e.toString());
                assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
            }
        });

        channel.callMethod(md, controller, param, md.getOutputType().toProto(), new RpcCallback<Message>() {
            @Override
            public void run(Message parameter) {
                done.set(true);
                fail("Expected an exception to have been thrown!");
            }
        });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:edu.tsinghua.lumaqq.qq.net.Socks5Proxy.java

@Override
public void setRemoteAddress(InetSocketAddress serverAddress) {
    super.setRemoteAddress(serverAddress);
    // ???/*from w w  w .  j ava  2 s.c om*/
    if (serverAddress.isUnresolved()) {
        /* ??? */
        isIp = false;
        byte[] b = serverAddress.getHostName().getBytes();
        remoteAddress = new byte[b.length + 1];
        remoteAddress[0] = (byte) (b.length & 0xFF);
        System.arraycopy(b, 0, remoteAddress, 1, b.length);
    } else {
        /* ???IPSocks5??????ipip */
        isIp = true;
        remoteAddress = serverAddress.getAddress().getAddress();
    }
    remotePort = serverAddress.getPort();
}