Example usage for java.net InetSocketAddress getPort

List of usage examples for java.net InetSocketAddress getPort

Introduction

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

Prototype

public final int getPort() 

Source Link

Document

Gets the port number.

Usage

From source file:com.chinamobile.bcbsp.http.HttpServer.java

/**
 * Configure an ssl listener on the server.
 * @param addr//  w w  w .  j  av  a 2 s  .c o m
 *        address to listen on
 * @param sslConf
 *        conf to retrieve ssl options
 * @param needClientAuth
 *        whether client authentication is required
 */
public void addSslListener(InetSocketAddress addr, Configuration sslConf, boolean needClientAuth)
        throws IOException {
    if (webServer.isStarted()) {
        throw new IOException("Failed to add ssl listener");
    }
    if (needClientAuth) {
        /** Set up SSL truststore for authenticating clients */
        System.setProperty("javax.net.ssl.trustStore", sslConf.get("ssl.server.truststore.location", ""));
        System.setProperty("javax.net.ssl.trustStorePassword",
                sslConf.get("ssl.server.truststore.password", ""));
        System.setProperty("javax.net.ssl.trustStoreType", sslConf.get("ssl.server.truststore.type", "jks"));
    }
    SslSocketConnector sslListener = new SslSocketConnector();
    sslListener.setHost(addr.getHostName());
    sslListener.setPort(addr.getPort());
    sslListener.setKeystore(sslConf.get("ssl.server.keystore.location"));
    sslListener.setPassword(sslConf.get("ssl.server.keystore.password", ""));
    sslListener.setKeyPassword(sslConf.get("ssl.server.keystore.keypassword", ""));
    sslListener.setKeystoreType(sslConf.get("ssl.server.keystore.type", "jks"));
    sslListener.setNeedClientAuth(needClientAuth);
    webServer.addConnector(sslListener);
}

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   w  w w  . j a v  a  2s  .c  o 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:com.all.dht.DhtManager.java

private void requestOversizedValue(KUID primaryKey) {
    for (DHTValueEntity valueEntity : get(primaryKey)) {
        InetSocketAddress contactAddress = (InetSocketAddress) valueEntity.getSender().getContactAddress();
        log.info("Will request oversized value to " + contactAddress.getAddress());
        AllMessage<String> message = new AllMessage<String>(OVERSIZED_DHT_VALUE_REQUEST_TYPE,
                primaryKey.toHexString());
        boolean requested = networkingService.send(dht.getLocalNodeID().toHexString(), message,
                contactAddress.getAddress().getHostAddress(), contactAddress.getPort() + 1);
        if (requested) {
            oversizedValueRequests.add(primaryKey.toHexString());
        }//  w w w  .  j  a  v a2  s .c  om
        break;
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.Standby.java

/**
 * Initialize the webserver so that the primary namenode can fetch
 * transaction logs from standby via http.
 *//*from  ww w  . ja v  a  2 s .  co m*/
void initSecondary(Configuration conf) throws IOException {

    fsName = AvatarNode.getRemoteNamenodeHttpName(conf, avatarNode.getInstanceId());

    // Initialize other scheduling parameters from the configuration
    checkpointEnabled = conf.getBoolean("fs.checkpoint.enabled", false);
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointTxnCount = NNStorageConfiguration.getCheckpointTxnCount(conf);
    delayedScheduledCheckpointTime = conf.getBoolean("fs.checkpoint.delayed", false)
            ? AvatarNode.now() + checkpointPeriod * 1000
            : 0;

    // 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);
    String infoBindIpAddress = infoSocAddr.getAddress().getHostAddress();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("secondary", infoBindIpAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", fsImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();
    avatarNode.httpServer.setAttribute("avatar.node", avatarNode);
    avatarNode.httpServer.addInternalServlet("outstandingnodes", "/outstandingnodes",
            OutStandingDatanodesServlet.class);

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindIpAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindIpAddress + ":" + infoPort);
    LOG.warn("Checkpoint Period   :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)");
    if (delayedScheduledCheckpointTime > 0) {
        LOG.warn("Standby: Checkpointing will be delayed by: " + checkpointPeriod + " seconds");
    }
    LOG.warn("Log Size Trigger    :" + checkpointTxnCount + " transactions.");
}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testStartTlsNotSupported() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//w w w  .ja v  a2 s. c om
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.sendCommand("STARTTLS");
        assertTrue(SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();
        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testUnknownCommand() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*from  ww w. ja  v a2 s  . c o  m*/
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.sendCommand("UNKNOWN");
        assertTrue(SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();
        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testNoop() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//from w  ww  .j a  v a2  s  .  c  om
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.noop();
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();
        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testInvalidHelo() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*www .j a  va 2s  .  c  om*/
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.helo("");
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testHeloEnforcement() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*w w  w. java 2 s .com*/
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.setSender(SENDER);
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();

        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientSecureProtocolSocketFactory.java

public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address must not be null"); //$NON-NLS-1$
    }//from  w w  w  .j  a  va2s . c  o m
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters must not be null"); //$NON-NLS-1$
    }

    if (socket == null) {
        SSLSocket sslSocket = (SSLSocket) this.sslSocketFactory.createSocket();

        performConnection(sslSocket, remoteAddress, localAddress, params);

        return wrapSocket(sslSocket);
    } else if (socket instanceof SSLSocket) {
        performConnection(socket, remoteAddress, localAddress, params);

        return wrapSocket(socket);
    }

    // If we were given a unconnected socket, we need to connect it first
    if (!socket.isConnected()) {
        performConnection(socket, remoteAddress, localAddress, params);
    }

    Socket layeredSocket = this.sslSocketFactory.createSocket(socket, remoteAddress.getHostName(),
            remoteAddress.getPort(), true);

    return wrapSocket(layeredSocket);
}