Example usage for java.net InetSocketAddress getHostString

List of usage examples for java.net InetSocketAddress getHostString

Introduction

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

Prototype

public final String getHostString() 

Source Link

Document

Returns the hostname, or the String form of the address if it doesn't have a hostname (it was created using a literal).

Usage

From source file:com.vmware.photon.controller.deployer.service.DeployerService.java

/**
 * This method responds to a new server joining the server set.
 *
 * @param address new server address//from   w ww.  j a v a  2  s.  co  m
 */
@Override
public void onServerAdded(InetSocketAddress address) {
    String host = address.getHostString();
    String currentHost = dcpHost.getUri().getHost();
    if (host.equals(currentHost)) {
        logger.info("Skip adding self {}", host);
        return;
    }

    logger.info("Joining {} to {}", host, currentHost);
    ServiceHostUtils.joinNodeGroup(dcpHost, host);
}

From source file:net.dv8tion.jda.audio.AudioWebSocket.java

@Override
public void onTextMessage(WebSocket websocket, String message) {
    JSONObject contentAll = new JSONObject(message);
    int opCode = contentAll.getInt("op");

    switch (opCode) {
    case INITIAL_CONNECTION_RESPONSE: {
        JSONObject content = contentAll.getJSONObject("d");
        ssrc = content.getInt("ssrc");
        int port = content.getInt("port");
        int heartbeatInterval = content.getInt("heartbeat_interval");

        //Find our external IP and Port using Discord
        InetSocketAddress externalIpAndPort = null;

        int tries = 0;
        do {// w ww. j a  v a  2 s .c  om
            externalIpAndPort = handleUdpDiscovery(new InetSocketAddress(endpoint, port), ssrc);
            tries++;
            if (externalIpAndPort == null && tries > 5) {
                close(false, UDP_UNABLE_TO_CONNECT);
                return;
            }
        } while (externalIpAndPort == null);

        setupUdpKeepAliveThread();

        send(new JSONObject().put("op", 1)
                .put("d",
                        new JSONObject().put("protocol", "udp").put("data",
                                new JSONObject().put("address", externalIpAndPort.getHostString())
                                        .put("port", externalIpAndPort.getPort())
                                        .put("mode", "xsalsa20_poly1305") //Discord requires encryption
                        )).toString());
        setupKeepAliveThread(heartbeatInterval);

        break;
    }
    case HEARTBEAT_PING_RETURN: {
        if (LOG.getEffectiveLevel().getPriority() <= SimpleLog.Level.TRACE.getPriority()) {
            long timePingSent = contentAll.getLong("d");
            long ping = System.currentTimeMillis() - timePingSent;
            LOG.trace("ping: " + ping + "ms");
        }
        break;
    }
    case CONNECTING_COMPLETED: {
        //secret_key is an array of 32 ints that are less than 256, so they are bytes.
        JSONArray keyArray = contentAll.getJSONObject("d").getJSONArray("secret_key");

        secretKey = new byte[DISCORD_SECRET_KEY_LENGTH];
        for (int i = 0; i < keyArray.length(); i++)
            secretKey[i] = (byte) keyArray.getInt(i);

        LOG.trace("Audio connection has finished connecting!");
        ready = true;
        break;
    }
    case USER_SPEAKING_UPDATE: {
        JSONObject content = contentAll.getJSONObject("d");
        boolean speaking = content.getBoolean("speaking");
        int ssrc = content.getInt("ssrc");
        String userId = content.getString("user_id");

        User user = api.getUserById(userId);
        if (user == null) {
            LOG.warn("Got an Audio USER_SPEAKING_UPDATE for a non-existent User. JSON: " + contentAll);
            return;
        }

        audioConnection.updateUserSSRC(ssrc, userId, speaking);
        if (speaking)
            LOG.log(SimpleLog.Level.ALL, user.getUsername() + " started transmitting audio."); //Replace with event.
        else
            LOG.log(SimpleLog.Level.ALL, user.getUsername() + " stopped transmitting audio."); //Replace with event.
        break;
    }
    default:
        LOG.debug("Unknown Audio OP code.\n" + contentAll.toString(4));
    }
}

From source file:org.apache.flink.client.CliFrontend.java

/**
 * Creates a {@link ClusterClient} object from the given command line options and other parameters.
 * @param options Command line options// www  .  j  a  v  a 2  s . com
 * @param program The program for which to create the client.
 * @throws Exception
 */
protected ClusterClient createClient(CommandLineOptions options, PackagedProgram program) throws Exception {

    // Get the custom command-line (e.g. Standalone/Yarn/Mesos)
    CustomCommandLine<?> activeCommandLine = getActiveCustomCommandLine(options.getCommandLine());

    ClusterClient client;
    try {
        client = activeCommandLine.retrieveCluster(options.getCommandLine(), config);
        logAndSysout("Cluster configuration: " + client.getClusterIdentifier());
    } catch (UnsupportedOperationException e) {
        try {
            String applicationName = "Flink Application: " + program.getMainClassName();
            client = activeCommandLine.createCluster(applicationName, options.getCommandLine(), config,
                    program.getAllLibraries());
            logAndSysout("Cluster started: " + client.getClusterIdentifier());
        } catch (UnsupportedOperationException e2) {
            throw new IllegalConfigurationException(
                    "The JobManager address is neither provided at the command-line, "
                            + "nor configured in flink-conf.yaml.");
        }
    }

    // Avoid resolving the JobManager Gateway here to prevent blocking until we invoke the user's program.
    final InetSocketAddress jobManagerAddress = client.getJobManagerAddress();
    logAndSysout("Using address " + jobManagerAddress.getHostString() + ":" + jobManagerAddress.getPort()
            + " to connect to JobManager.");
    logAndSysout("JobManager web interface address " + client.getWebInterfaceURL());
    return client;
}

From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java

@Override
public void onTextMessage(WebSocket websocket, String message) {
    JSONObject contentAll = new JSONObject(message);
    int opCode = contentAll.getInt("op");

    switch (opCode) {
    case INITIAL_CONNECTION_RESPONSE: {
        JSONObject content = contentAll.getJSONObject("d");
        ssrc = content.getInt("ssrc");
        int port = content.getInt("port");
        int heartbeatInterval = content.getInt("heartbeat_interval");

        //Find our external IP and Port using Discord
        InetSocketAddress externalIpAndPort;

        changeStatus(ConnectionStatus.CONNECTING_ATTEMPTING_UDP_DISCOVERY);
        int tries = 0;
        do {/*from ww w.  j a v  a2  s .  co  m*/
            externalIpAndPort = handleUdpDiscovery(new InetSocketAddress(endpoint, port), ssrc);
            tries++;
            if (externalIpAndPort == null && tries > 5) {
                close(ConnectionStatus.ERROR_UDP_UNABLE_TO_CONNECT);
                return;
            }
        } while (externalIpAndPort == null);

        send(new JSONObject().put("op", 1)
                .put("d",
                        new JSONObject().put("protocol", "udp").put("data",
                                new JSONObject().put("address", externalIpAndPort.getHostString())
                                        .put("port", externalIpAndPort.getPort())
                                        .put("mode", "xsalsa20_poly1305") //Discord requires encryption
                        )).toString());

        setupKeepAlive(heartbeatInterval);
        changeStatus(ConnectionStatus.CONNECTING_AWAITING_READY);
        break;
    }
    case HEARTBEAT_START: {
        break;
    }
    case HEARTBEAT_PING_RETURN: {
        long timePingSent = contentAll.getLong("d");
        long ping = System.currentTimeMillis() - timePingSent;
        listener.onPing(ping);
        break;
    }
    case CONNECTING_COMPLETED: {
        //secret_key is an array of 32 ints that are less than 256, so they are bytes.
        JSONArray keyArray = contentAll.getJSONObject("d").getJSONArray("secret_key");

        secretKey = new byte[DISCORD_SECRET_KEY_LENGTH];
        for (int i = 0; i < keyArray.length(); i++)
            secretKey[i] = (byte) keyArray.getInt(i);

        LOG.trace("Audio connection has finished connecting!");
        ready = true;
        changeStatus(ConnectionStatus.CONNECTED);
        break;
    }
    case USER_SPEAKING_UPDATE: {
        JSONObject content = contentAll.getJSONObject("d");
        boolean speaking = content.getBoolean("speaking");
        int ssrc = content.getInt("ssrc");
        final long userId = content.getLong("user_id");

        User user;
        if (!api.getUserMap().containsKey(userId)) {
            if (!api.getFakeUserMap().containsKey(userId)) {
                LOG.warn("Got an Audio USER_SPEAKING_UPDATE for a non-existent User. JSON: " + contentAll);
                return;
            }
            user = api.getFakeUserMap().get(userId);
        } else {
            user = api.getUserById(userId);
        }

        audioConnection.updateUserSSRC(ssrc, userId, speaking);
        listener.onUserSpeaking(user, speaking);
        break;
    }
    default:
        LOG.debug("Unknown Audio OP code.\n" + contentAll.toString(4));
    }
}

From source file:org.apache.nifi.cdc.mysql.processors.CaptureChangeMySQL.java

/**
 * using Thread.currentThread().getContextClassLoader(); will ensure that you are using the ClassLoader for you NAR.
 *
 * @throws InitializationException if there is a problem obtaining the ClassLoader
 *//*from  w w  w  . ja  va2  s.c  om*/
protected Connection getJdbcConnection(String locationString, String drvName, InetSocketAddress host,
        String username, String password, Map<String, String> customProperties)
        throws InitializationException, SQLException {
    Properties connectionProps = new Properties();
    if (customProperties != null) {
        connectionProps.putAll(customProperties);
    }
    connectionProps.put("user", username);
    connectionProps.put("password", password);

    return DriverManager.getConnection("jdbc:mysql://" + host.getHostString() + ":" + host.getPort(),
            connectionProps);
}

From source file:old.server.loginserver.LoginServer.java

private boolean registerPlayer(final InetSocketAddress sender_address, final JSONObject jo)
        throws JSONException {
    // TODO: Configurable limitations for names and etc.
    // TODO: Check role indexes to the bound of array(enum)
    final String name = jo.getString(CommonPacketConsts.ITEM_USERNAME);
    CommonPacketConsts.ENUM_PLAYER_ROLE role = CommonPacketConsts.ENUM_PLAYER_ROLE.values()[jo
            .getInt(CommonPacketConsts.PLAYER_ROLE)];

    final GameServerInfo gsi = getFirstAvailableGameServer();

    if (gsi == null) {
        enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_FAIL, CLIENT_LOGINSERVER),
                sender_address));//from ww w. ja  v  a 2 s  .c o m
        return false;
    }

    PlayerInfo player_info = new PlayerInfo(sender_address, gsi.getServerAddress(), name, role, (short) 0);

    if (!logged_players.add(player_info)) {
        enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_FAIL, CLIENT_LOGINSERVER),
                sender_address));
        return false;
    }

    enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(PACKET_TYPE_RESULT_SUCCESS, CLIENT_LOGINSERVER),
            sender_address));

    enqueueMessage(MessageToBeEnqueued.make(PacketFactory.make(CLIENT_LOGINSERVER, name,
            sender_address.getHostString(), sender_address.getPort(), role), gsi.getServerAddress()));
    player_info.setConnected(true);

    return true;
}

From source file:org.apache.nifi.cdc.mysql.processors.CaptureChangeMySQL.java

protected void connect(List<InetSocketAddress> hosts, String username, String password, Long serverId,
        boolean createEnrichmentConnection, String driverLocation, String driverName, long connectTimeout)
        throws IOException {

    int connectionAttempts = 0;
    final int numHosts = hosts.size();
    InetSocketAddress connectedHost = null;
    Exception lastConnectException = new Exception("Unknown connection error");

    if (createEnrichmentConnection) {
        try {//from  www. j a v  a  2  s  .c o  m
            // Ensure driverLocation and driverName are correct before establishing binlog connection
            // to avoid failing after binlog messages are received.
            // Actual JDBC connection is created after binlog client gets started, because we need
            // the connect-able host same as the binlog client.
            registerDriver(driverLocation, driverName);
        } catch (InitializationException e) {
            throw new RuntimeException("Failed to register JDBC driver. Ensure MySQL Driver Location(s)"
                    + " and MySQL Driver Class Name are configured correctly. " + e, e);
        }
    }

    while (connectedHost == null && connectionAttempts < numHosts) {
        if (binlogClient == null) {

            connectedHost = hosts.get(currentHost);
            binlogClient = createBinlogClient(connectedHost.getHostString(), connectedHost.getPort(), username,
                    password);
        }

        // Add an event listener and lifecycle listener for binlog and client events, respectively
        if (eventListener == null) {
            eventListener = createBinlogEventListener(binlogClient, queue);
        }
        eventListener.start();
        binlogClient.registerEventListener(eventListener);

        if (lifecycleListener == null) {
            lifecycleListener = createBinlogLifecycleListener();
        }
        binlogClient.registerLifecycleListener(lifecycleListener);

        binlogClient.setBinlogFilename(currentBinlogFile);
        if (currentBinlogPosition != DO_NOT_SET) {
            binlogClient.setBinlogPosition(currentBinlogPosition);
        }

        if (serverId != null) {
            binlogClient.setServerId(serverId);
        }

        try {
            if (connectTimeout == 0) {
                connectTimeout = Long.MAX_VALUE;
            }
            binlogClient.connect(connectTimeout);
            transitUri = "mysql://" + connectedHost.getHostString() + ":" + connectedHost.getPort();

        } catch (IOException | TimeoutException te) {
            // Try the next host
            connectedHost = null;
            transitUri = "<unknown>";
            currentHost = (currentHost + 1) % numHosts;
            connectionAttempts++;
            lastConnectException = te;
        }
    }
    if (!binlogClient.isConnected()) {
        binlogClient = null;
        throw new IOException("Could not connect binlog client to any of the specified hosts due to: "
                + lastConnectException.getMessage(), lastConnectException);
    }

    if (createEnrichmentConnection) {
        try {
            jdbcConnection = getJdbcConnection(driverLocation, driverName, connectedHost, username, password,
                    null);
        } catch (InitializationException | SQLException e) {
            throw new IOException(
                    "Error creating binlog enrichment JDBC connection to any of the specified hosts", e);
        }
    }

    doStop.set(false);
}

From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java

@Override
// ok//w  w w .ja  v  a 2 s . c o  m
public String getLocalName() {
    InetSocketAddress local = socketChannel.localAddress();
    return local.getHostString();
}