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.sharneng.net.misc.EchoServer.java

public EchoServer(InetSocketAddress from) throws IOException {
    this.from = from;
    serverSocket = new ServerSocket();
    serverSocket.setReuseAddress(true);//w  w w .ja  v  a 2  s  .  c om
    serverSocket.bind(from);
    String hostname = from.getHostName();
    if (hostname == null)
        hostname = "*";
    log.info("Ready to accept client connection on " + hostname + ":" + from.getPort());
}

From source file:net.ymate.platform.serv.nio.support.NioSession.java

private String __doGetRemoteAddress() {
    if (status() != ISession.Status.CLOSED && __selectionKey != null) {
        if (__channel != null) {
            InetSocketAddress _addr = __doGetChannelInetAddress();
            if (_addr != null) {
                return _addr.getHostName() + ":" + _addr.getPort();
            }/* w w w  .ja  va2s .c  o m*/
        }
    }
    return null;
}

From source file:com.kixeye.chassis.bootstrap.webapp.TestSpringWebApp.java

@Bean(initMethod = "start", destroyMethod = "stop", name = "httpServer")
@Order(0)//  w w w  . j a va  2  s.  c o  m
public Server httpServer(ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = new InetSocketAddress(SocketUtils.findAvailableTcpPort());

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[] { connector });
    server.setHandler(servlets);
    server.setStopAtShutdown(true);

    return server;
}

From source file:org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster.java

public static String getResolvedMRHistoryWebAppURLWithoutScheme(Configuration conf, boolean isSSLEnabled) {
    InetSocketAddress address = null;
    if (isSSLEnabled) {
        address = conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_HTTPS_PORT);
    } else {//from   w w w  . j a  v a2 s .  com
        address = conf.getSocketAddr(JHAdminConfig.MR_HISTORY_WEBAPP_ADDRESS,
                JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_ADDRESS, JHAdminConfig.DEFAULT_MR_HISTORY_WEBAPP_PORT);
    }
    address = NetUtils.getConnectAddress(address);
    StringBuffer sb = new StringBuffer();
    InetAddress resolved = address.getAddress();
    if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) {
        String lh = address.getHostName();
        try {
            lh = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            //Ignore and fallback.
        }
        sb.append(lh);
    } else {
        sb.append(address.getHostName());
    }
    sb.append(":").append(address.getPort());
    return sb.toString();
}

From source file:com.nesscomputing.service.discovery.client.DiscoveryClientModule.java

@Provides
@Singleton/*w  w w  . j ava  2s .  c om*/
@Named(ZOOKEEPER_CONNECT_NAME)
String getConnectString(@Named(ZOOKEEPER_CONNECT_NAME) final Map<Integer, InetSocketAddress> zookeeperServers,
        final DiscoveryClientConfig clientConfig) {
    final StringBuilder sb = new StringBuilder();

    for (final InetSocketAddress address : zookeeperServers.values()) {
        if (sb.length() > 0) {
            sb.append(',');
        }
        sb.append(address.getAddress().getHostAddress()).append(':').append(address.getPort());
    }

    if (sb.length() == 0) {
        if (clientConfig.isEnabled()) {
            throw new IllegalStateException("Service discovery is enabled but no servers found!");
        } else {
            LOG.info("No servers found!");
        }
    }
    return sb.toString();
}

From source file:com.pinterest.terrapin.zookeeper.ZooKeeperManagerTest.java

@Test
public void testGetControllerLeader() throws Exception {
    String host = "somehost";
    int port = 9090;
    String json = String.format("{\"id\": \"%s_%d\"}", host, port);
    when(zk.getData(eq("/" + CLUSTER_NAME + "/CONTROLLER/LEADER"), anyBoolean(), any(Stat.class)))
            .thenReturn(json.getBytes());
    InetSocketAddress address = zkManager.getControllerLeader();
    assertEquals(host, address.getHostName());
    assertEquals(port, address.getPort());
}

From source file:co.cask.cdap.client.util.RESTClientTest.java

private URI getBaseURI() throws URISyntaxException {
    InetSocketAddress bindAddress = httpService.getBindAddress();
    return new URI("http://" + bindAddress.getHostName() + ":" + bindAddress.getPort());
}

From source file:hudson.gridmaven.gridlayer.PluginImpl.java

/**
 * Determines the HDFS URL./* w  ww . j a v  a2 s .  c o m*/
 */
public String getHdfsUrl() throws MalformedURLException {
    InetSocketAddress a = getHdfsAddress();
    if (a == null)
        return null;
    return "hdfs://" + a.getHostName() + ":" + a.getPort() + "/";
}

From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNode.java

@Test
public void testHttpServer() throws Exception {
    InetSocketAddress addr = jn.getBoundHttpAddress();
    assertTrue(addr.getPort() > 0);

    String urlRoot = "http://localhost:" + addr.getPort();

    // TODO other servlets

    // Create some edits on server side
    int numTxns = 10;
    byte[] EDITS_DATA = QJMTestUtil.createTxnData(1, numTxns);
    IPCLoggerChannel ch = new IPCLoggerChannel(conf, FAKE_NSINFO, journalId, jn.getBoundIpcAddress());
    ch.newEpoch(1).get();/*from   ww  w.j a v  a 2  s.  co m*/
    ch.setEpoch(1);
    ch.startLogSegment(1).get();
    ch.sendEdits(1L, 1, numTxns, EDITS_DATA).get();
    ch.finalizeLogSegment(1, numTxns).get();

    // Attempt to retrieve via HTTP, ensure we get the data back
    // including the header we expected
    byte[] retrievedViaHttp = QJMTestUtil
            .urlGetBytes(new URL(urlRoot + "/getJournal?segmentTxId=1&position=0&jid=" + journalId));
    byte[] expected = Bytes.concat(Ints.toByteArray(FSConstants.LAYOUT_VERSION), EDITS_DATA);

    // retrieve partial edits
    int pos = 100;
    byte[] expectedPart = new byte[expected.length - pos];
    System.arraycopy(expected, pos, expectedPart, 0, expectedPart.length);
    retrievedViaHttp = QJMTestUtil
            .urlGetBytes(new URL(urlRoot + "/getJournal?segmentTxId=1&position=" + pos + "&jid=" + journalId));
    assertArrayEquals(expectedPart, retrievedViaHttp);

    // Attempt to fetch a non-existent file, check that we get an
    // error status code
    URL badUrl = new URL(urlRoot + "/getJournal?segmentTxId=12345&position=0&jid=" + journalId);
    HttpURLConnection connection = (HttpURLConnection) badUrl.openConnection();
    try {
        assertEquals(404, connection.getResponseCode());
    } finally {
        connection.disconnect();
    }
}

From source file:com.bitbreeds.webrtc.signaling.BindingService.java

public byte[] processBindingRequest(byte[] data, String userName, String password, InetSocketAddress sender) {

    logger.trace("Input: " + Hex.encodeHexString(data));

    StunMessage msg = StunMessage.fromBytes(data);

    logger.trace("InputParsed: " + msg);

    byte[] content = SignalUtil.joinBytesArrays(SignalUtil.twoBytesFromInt(0x01),
            SignalUtil.xor(SignalUtil.twoBytesFromInt(sender.getPort()),
                    Arrays.copyOf(msg.getHeader().getCookie(), 2)),
            SignalUtil.xor(sender.getAddress().getAddress(), msg.getHeader().getCookie()));

    StunAttribute attr = new StunAttribute(StunAttributeTypeEnum.XOR_MAPPED_ADDRESS, content);

    StunAttribute user = msg.getAttributeSet().get(StunAttributeTypeEnum.USERNAME);
    String strUser = new String(user.toBytes()).split(":")[0].trim();

    msg.validate(password, data);/*from w  w w  . j a  v  a2 s  .c o  m*/

    HashMap<StunAttributeTypeEnum, StunAttribute> outSet = new HashMap<>();
    outSet.put(StunAttributeTypeEnum.XOR_MAPPED_ADDRESS, attr);
    outSet.putAll(msg.getAttributeSet());

    StunMessage output = StunMessage.fromData(StunRequestTypeEnum.BINDING_RESPONSE, msg.getHeader().getCookie(),
            msg.getHeader().getTransactionID(), outSet, true, true, strUser, password);

    byte[] bt = output.toBytes();
    logger.trace("Response: " + Hex.encodeHexString(bt));
    return bt;
}